Rename GetIconID to GetIconId
[chromium-blink-merge.git] / components / storage_monitor / volume_mount_watcher_win.cc
blob168d2eb14dea19b21c28d6fd932dd62955dcce2c
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/storage_monitor/volume_mount_watcher_win.h"
7 #include <windows.h>
9 #include <dbt.h>
10 #include <fileapi.h>
11 #include <shlobj.h>
12 #include <winioctl.h>
14 #include "base/bind_helpers.h"
15 #include "base/metrics/histogram.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/task_runner_util.h"
22 #include "base/time/time.h"
23 #include "base/win/scoped_handle.h"
24 #include "components/storage_monitor/media_storage_util.h"
25 #include "components/storage_monitor/storage_info.h"
26 #include "content/public/browser/browser_thread.h"
27 #include "content/public/browser/user_metrics.h"
29 using content::BrowserThread;
31 namespace storage_monitor {
33 namespace {
35 const DWORD kMaxPathBufLen = MAX_PATH + 1;
37 const char kDeviceInfoTaskRunnerName[] = "device-info-task-runner";
39 enum DeviceType {
40 FLOPPY,
41 REMOVABLE,
42 FIXED,
45 // Histogram values for recording frequencies of eject attempts and
46 // outcomes.
47 enum EjectWinLockOutcomes {
48 LOCK_ATTEMPT,
49 LOCK_TIMEOUT,
50 LOCK_TIMEOUT2,
51 NUM_LOCK_OUTCOMES,
54 // We are trying to figure out whether the drive is a fixed volume,
55 // a removable storage, or a floppy. A "floppy" here means "a volume we
56 // want to basically ignore because it won't fit media and will spin
57 // if we touch it to get volume metadata." GetDriveType returns DRIVE_REMOVABLE
58 // on either floppy or removable volumes. The DRIVE_CDROM type is handled
59 // as a floppy, as are DRIVE_UNKNOWN and DRIVE_NO_ROOT_DIR, as there are
60 // reports that some floppy drives don't report as DRIVE_REMOVABLE.
61 DeviceType GetDeviceType(const base::string16& mount_point) {
62 UINT drive_type = GetDriveType(mount_point.c_str());
63 if (drive_type == DRIVE_FIXED || drive_type == DRIVE_REMOTE ||
64 drive_type == DRIVE_RAMDISK) {
65 return FIXED;
67 if (drive_type != DRIVE_REMOVABLE)
68 return FLOPPY;
70 // Check device strings of the form "X:" and "\\.\X:"
71 // For floppy drives, these will return strings like "/Device/Floppy0"
72 base::string16 device = mount_point;
73 if (base::EndsWith(mount_point, L"\\", base::CompareCase::INSENSITIVE_ASCII))
74 device = mount_point.substr(0, mount_point.length() - 1);
75 base::string16 device_path;
76 base::string16 device_path_slash;
77 DWORD dos_device = QueryDosDevice(
78 device.c_str(), base::WriteInto(&device_path, kMaxPathBufLen),
79 kMaxPathBufLen);
80 base::string16 device_slash = base::string16(L"\\\\.\\");
81 device_slash += device;
82 DWORD dos_device_slash = QueryDosDevice(
83 device_slash.c_str(), base::WriteInto(&device_path_slash, kMaxPathBufLen),
84 kMaxPathBufLen);
85 if (dos_device == 0 && dos_device_slash == 0)
86 return FLOPPY;
87 if (device_path.find(L"Floppy") != base::string16::npos ||
88 device_path_slash.find(L"Floppy") != base::string16::npos) {
89 return FLOPPY;
92 return REMOVABLE;
95 // Returns 0 if the devicetype is not volume.
96 uint32 GetVolumeBitMaskFromBroadcastHeader(LPARAM data) {
97 DEV_BROADCAST_VOLUME* dev_broadcast_volume =
98 reinterpret_cast<DEV_BROADCAST_VOLUME*>(data);
99 if (dev_broadcast_volume->dbcv_devicetype == DBT_DEVTYP_VOLUME)
100 return dev_broadcast_volume->dbcv_unitmask;
101 return 0;
104 // Returns true if |data| represents a logical volume structure.
105 bool IsLogicalVolumeStructure(LPARAM data) {
106 DEV_BROADCAST_HDR* broadcast_hdr =
107 reinterpret_cast<DEV_BROADCAST_HDR*>(data);
108 return broadcast_hdr != NULL &&
109 broadcast_hdr->dbch_devicetype == DBT_DEVTYP_VOLUME;
112 // Gets the total volume of the |mount_point| in bytes.
113 uint64 GetVolumeSize(const base::string16& mount_point) {
114 ULARGE_INTEGER total;
115 if (!GetDiskFreeSpaceExW(mount_point.c_str(), NULL, &total, NULL))
116 return 0;
117 return total.QuadPart;
120 // Gets mass storage device information given a |device_path|. On success,
121 // returns true and fills in |info|.
122 // The following msdn blog entry is helpful for understanding disk volumes
123 // and how they are treated in Windows:
124 // http://blogs.msdn.com/b/adioltean/archive/2005/04/16/408947.aspx.
125 bool GetDeviceDetails(const base::FilePath& device_path, StorageInfo* info) {
126 DCHECK(info);
128 base::string16 mount_point;
129 if (!GetVolumePathName(device_path.value().c_str(),
130 base::WriteInto(&mount_point, kMaxPathBufLen),
131 kMaxPathBufLen)) {
132 return false;
134 mount_point.resize(wcslen(mount_point.c_str()));
136 // Note: experimentally this code does not spin a floppy drive. It
137 // returns a GUID associated with the device, not the volume.
138 base::string16 guid;
139 if (!GetVolumeNameForVolumeMountPoint(mount_point.c_str(),
140 base::WriteInto(&guid, kMaxPathBufLen),
141 kMaxPathBufLen)) {
142 return false;
144 // In case it has two GUID's (see above mentioned blog), do it again.
145 if (!GetVolumeNameForVolumeMountPoint(guid.c_str(),
146 base::WriteInto(&guid, kMaxPathBufLen),
147 kMaxPathBufLen)) {
148 return false;
151 // If we're adding a floppy drive, return without querying any more
152 // drive metadata -- it will cause the floppy drive to seek.
153 // Note: treats FLOPPY as FIXED_MASS_STORAGE. This is intentional.
154 DeviceType device_type = GetDeviceType(mount_point);
155 if (device_type == FLOPPY) {
156 info->set_device_id(StorageInfo::MakeDeviceId(
157 StorageInfo::FIXED_MASS_STORAGE, base::UTF16ToUTF8(guid)));
158 return true;
161 StorageInfo::Type type = StorageInfo::FIXED_MASS_STORAGE;
162 if (device_type == REMOVABLE) {
163 type = StorageInfo::REMOVABLE_MASS_STORAGE_NO_DCIM;
164 if (MediaStorageUtil::HasDcim(base::FilePath(mount_point)))
165 type = StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM;
168 // NOTE: experimentally, this function returns false if there is no volume
169 // name set.
170 base::string16 volume_label;
171 GetVolumeInformationW(device_path.value().c_str(),
172 base::WriteInto(&volume_label, kMaxPathBufLen),
173 kMaxPathBufLen, NULL, NULL, NULL, NULL, 0);
175 uint64 total_size_in_bytes = GetVolumeSize(mount_point);
176 std::string device_id =
177 StorageInfo::MakeDeviceId(type, base::UTF16ToUTF8(guid));
179 // TODO(gbillock): if volume_label.empty(), get the vendor/model information
180 // for the volume.
181 *info = StorageInfo(device_id, mount_point, volume_label, base::string16(),
182 base::string16(), total_size_in_bytes);
183 return true;
186 // Returns a vector of all the removable mass storage devices that are
187 // connected.
188 std::vector<base::FilePath> GetAttachedDevices() {
189 std::vector<base::FilePath> result;
190 base::string16 volume_name;
191 HANDLE find_handle = FindFirstVolume(
192 base::WriteInto(&volume_name, kMaxPathBufLen), kMaxPathBufLen);
193 if (find_handle == INVALID_HANDLE_VALUE)
194 return result;
196 while (true) {
197 base::string16 volume_path;
198 DWORD return_count;
199 if (GetVolumePathNamesForVolumeName(
200 volume_name.c_str(), base::WriteInto(&volume_path, kMaxPathBufLen),
201 kMaxPathBufLen, &return_count)) {
202 result.push_back(base::FilePath(volume_path));
204 if (!FindNextVolume(find_handle,
205 base::WriteInto(&volume_name, kMaxPathBufLen),
206 kMaxPathBufLen)) {
207 if (GetLastError() != ERROR_NO_MORE_FILES)
208 DPLOG(ERROR);
209 break;
213 FindVolumeClose(find_handle);
214 return result;
217 // Eject a removable volume at the specified |device| path. This works by
218 // 1) locking the volume,
219 // 2) unmounting the volume,
220 // 3) ejecting the volume.
221 // If the lock fails, it will re-schedule itself.
222 // See http://support.microsoft.com/kb/165721
223 void EjectDeviceInThreadPool(
224 const base::FilePath& device,
225 base::Callback<void(StorageMonitor::EjectStatus)> callback,
226 scoped_refptr<base::SequencedTaskRunner> task_runner,
227 int iteration) {
228 base::FilePath::StringType volume_name;
229 base::FilePath::CharType drive_letter = device.value()[0];
230 // Don't try to eject if the path isn't a simple one -- we're not
231 // sure how to do that yet. Need to figure out how to eject volumes mounted
232 // at not-just-drive-letter paths.
233 if (drive_letter < L'A' || drive_letter > L'Z' ||
234 device != device.DirName()) {
235 BrowserThread::PostTask(
236 BrowserThread::UI, FROM_HERE,
237 base::Bind(callback, StorageMonitor::EJECT_FAILURE));
238 return;
240 base::SStringPrintf(&volume_name, L"\\\\.\\%lc:", drive_letter);
242 base::win::ScopedHandle volume_handle(CreateFile(
243 volume_name.c_str(),
244 GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
245 NULL, OPEN_EXISTING, 0, NULL));
247 if (!volume_handle.IsValid()) {
248 BrowserThread::PostTask(
249 BrowserThread::UI, FROM_HERE,
250 base::Bind(callback, StorageMonitor::EJECT_FAILURE));
251 return;
254 DWORD bytes_returned = 0; // Unused, but necessary for ioctl's.
256 // Lock the drive to be ejected (so that other processes can't open
257 // files on it). If this fails, it means some other process has files
258 // open on the device. Note that the lock is released when the volume
259 // handle is closed, and this is done by the ScopedHandle above.
260 BOOL locked = DeviceIoControl(volume_handle.Get(), FSCTL_LOCK_VOLUME,
261 NULL, 0, NULL, 0, &bytes_returned, NULL);
262 UMA_HISTOGRAM_ENUMERATION("StorageMonitor.EjectWinLock",
263 LOCK_ATTEMPT, NUM_LOCK_OUTCOMES);
264 if (!locked) {
265 UMA_HISTOGRAM_ENUMERATION("StorageMonitor.EjectWinLock",
266 iteration == 0 ? LOCK_TIMEOUT : LOCK_TIMEOUT2,
267 NUM_LOCK_OUTCOMES);
268 const int kNumLockRetries = 1;
269 const base::TimeDelta kLockRetryInterval =
270 base::TimeDelta::FromMilliseconds(500);
271 if (iteration < kNumLockRetries) {
272 // Try again -- the lock may have been a transient one. This happens on
273 // things like AV disk lock for some reason, or another process
274 // transient disk lock.
275 task_runner->PostDelayedTask(
276 FROM_HERE,
277 base::Bind(&EjectDeviceInThreadPool,
278 device, callback, task_runner, iteration + 1),
279 kLockRetryInterval);
280 return;
283 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
284 base::Bind(callback, StorageMonitor::EJECT_IN_USE));
285 return;
288 // Unmount the device from the filesystem -- this will remove it from
289 // the file picker, drive enumerations, etc.
290 BOOL dismounted = DeviceIoControl(volume_handle.Get(), FSCTL_DISMOUNT_VOLUME,
291 NULL, 0, NULL, 0, &bytes_returned, NULL);
293 // Reached if we acquired a lock, but could not dismount. This might
294 // occur if another process unmounted without locking. Call this OK,
295 // since the volume is now unreachable.
296 if (!dismounted) {
297 DeviceIoControl(volume_handle.Get(), FSCTL_UNLOCK_VOLUME,
298 NULL, 0, NULL, 0, &bytes_returned, NULL);
299 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
300 base::Bind(callback, StorageMonitor::EJECT_OK));
301 return;
304 PREVENT_MEDIA_REMOVAL pmr_buffer;
305 pmr_buffer.PreventMediaRemoval = FALSE;
306 // Mark the device as safe to remove.
307 if (!DeviceIoControl(volume_handle.Get(), IOCTL_STORAGE_MEDIA_REMOVAL,
308 &pmr_buffer, sizeof(PREVENT_MEDIA_REMOVAL),
309 NULL, 0, &bytes_returned, NULL)) {
310 BrowserThread::PostTask(
311 BrowserThread::UI, FROM_HERE,
312 base::Bind(callback, StorageMonitor::EJECT_FAILURE));
313 return;
316 // Physically eject or soft-eject the device.
317 if (!DeviceIoControl(volume_handle.Get(), IOCTL_STORAGE_EJECT_MEDIA,
318 NULL, 0, NULL, 0, &bytes_returned, NULL)) {
319 BrowserThread::PostTask(
320 BrowserThread::UI, FROM_HERE,
321 base::Bind(callback, StorageMonitor::EJECT_FAILURE));
322 return;
325 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
326 base::Bind(callback, StorageMonitor::EJECT_OK));
329 } // namespace
331 VolumeMountWatcherWin::VolumeMountWatcherWin()
332 : notifications_(NULL), weak_factory_(this) {
333 base::SequencedWorkerPool* pool = content::BrowserThread::GetBlockingPool();
334 device_info_task_runner_ = pool->GetSequencedTaskRunnerWithShutdownBehavior(
335 pool->GetNamedSequenceToken(kDeviceInfoTaskRunnerName),
336 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN);
339 // static
340 base::FilePath VolumeMountWatcherWin::DriveNumberToFilePath(int drive_number) {
341 if (drive_number < 0 || drive_number > 25)
342 return base::FilePath();
343 base::string16 path(L"_:\\");
344 path[0] = static_cast<base::char16>('A' + drive_number);
345 return base::FilePath(path);
348 // In order to get all the weak pointers created on the UI thread, and doing
349 // synchronous Windows calls in the worker pool, this kicks off a chain of
350 // events which will
351 // a) Enumerate attached devices
352 // b) Create weak pointers for which to send completion signals from
353 // c) Retrieve metadata on the volumes and then
354 // d) Notify that metadata to listeners.
355 void VolumeMountWatcherWin::Init() {
356 DCHECK_CURRENTLY_ON(BrowserThread::UI);
358 // When VolumeMountWatcherWin is created, the message pumps are not running
359 // so a posted task from the constructor would never run. Therefore, do all
360 // the initializations here.
361 base::PostTaskAndReplyWithResult(
362 device_info_task_runner_.get(), FROM_HERE, GetAttachedDevicesCallback(),
363 base::Bind(&VolumeMountWatcherWin::AddDevicesOnUIThread,
364 weak_factory_.GetWeakPtr()));
367 void VolumeMountWatcherWin::AddDevicesOnUIThread(
368 std::vector<base::FilePath> removable_devices) {
369 DCHECK_CURRENTLY_ON(BrowserThread::UI);
371 for (size_t i = 0; i < removable_devices.size(); i++) {
372 if (ContainsKey(pending_device_checks_, removable_devices[i]))
373 continue;
374 pending_device_checks_.insert(removable_devices[i]);
375 device_info_task_runner_->PostTask(
376 FROM_HERE,
377 base::Bind(&VolumeMountWatcherWin::RetrieveInfoForDeviceAndAdd,
378 removable_devices[i], GetDeviceDetailsCallback(),
379 weak_factory_.GetWeakPtr()));
383 // static
384 void VolumeMountWatcherWin::RetrieveInfoForDeviceAndAdd(
385 const base::FilePath& device_path,
386 const GetDeviceDetailsCallbackType& get_device_details_callback,
387 base::WeakPtr<VolumeMountWatcherWin> volume_watcher) {
388 StorageInfo info;
389 if (!get_device_details_callback.Run(device_path, &info)) {
390 BrowserThread::PostTask(
391 BrowserThread::UI, FROM_HERE,
392 base::Bind(&VolumeMountWatcherWin::DeviceCheckComplete,
393 volume_watcher, device_path));
394 return;
397 BrowserThread::PostTask(
398 BrowserThread::UI, FROM_HERE,
399 base::Bind(&VolumeMountWatcherWin::HandleDeviceAttachEventOnUIThread,
400 volume_watcher, device_path, info));
403 void VolumeMountWatcherWin::DeviceCheckComplete(
404 const base::FilePath& device_path) {
405 DCHECK_CURRENTLY_ON(BrowserThread::UI);
406 pending_device_checks_.erase(device_path);
408 if (pending_device_checks_.size() == 0) {
409 if (notifications_)
410 notifications_->MarkInitialized();
414 VolumeMountWatcherWin::GetAttachedDevicesCallbackType
415 VolumeMountWatcherWin::GetAttachedDevicesCallback() const {
416 return base::Bind(&GetAttachedDevices);
419 VolumeMountWatcherWin::GetDeviceDetailsCallbackType
420 VolumeMountWatcherWin::GetDeviceDetailsCallback() const {
421 return base::Bind(&GetDeviceDetails);
424 bool VolumeMountWatcherWin::GetDeviceInfo(const base::FilePath& device_path,
425 StorageInfo* info) const {
426 DCHECK_CURRENTLY_ON(BrowserThread::UI);
427 DCHECK(info);
428 base::FilePath path(device_path);
429 MountPointDeviceMetadataMap::const_iterator iter =
430 device_metadata_.find(path);
431 while (iter == device_metadata_.end() && path.DirName() != path) {
432 path = path.DirName();
433 iter = device_metadata_.find(path);
436 if (iter == device_metadata_.end())
437 return false;
439 *info = iter->second;
440 return true;
443 void VolumeMountWatcherWin::OnWindowMessage(UINT event_type, LPARAM data) {
444 DCHECK_CURRENTLY_ON(BrowserThread::UI);
445 switch (event_type) {
446 case DBT_DEVICEARRIVAL: {
447 if (IsLogicalVolumeStructure(data)) {
448 DWORD unitmask = GetVolumeBitMaskFromBroadcastHeader(data);
449 std::vector<base::FilePath> paths;
450 for (int i = 0; unitmask; ++i, unitmask >>= 1) {
451 if (!(unitmask & 0x01))
452 continue;
453 paths.push_back(DriveNumberToFilePath(i));
455 AddDevicesOnUIThread(paths);
457 break;
459 case DBT_DEVICEREMOVECOMPLETE: {
460 if (IsLogicalVolumeStructure(data)) {
461 DWORD unitmask = GetVolumeBitMaskFromBroadcastHeader(data);
462 for (int i = 0; unitmask; ++i, unitmask >>= 1) {
463 if (!(unitmask & 0x01))
464 continue;
465 HandleDeviceDetachEventOnUIThread(DriveNumberToFilePath(i).value());
468 break;
473 void VolumeMountWatcherWin::OnMediaChange(WPARAM wparam, LPARAM lparam) {
474 if (lparam == SHCNE_MEDIAINSERTED || lparam == SHCNE_MEDIAREMOVED) {
475 struct _ITEMIDLIST* pidl = *reinterpret_cast<struct _ITEMIDLIST**>(
476 wparam);
477 wchar_t sPath[MAX_PATH];
478 if (!SHGetPathFromIDList(pidl, sPath)) {
479 DVLOG(1) << "MediaInserted: SHGetPathFromIDList failed";
480 return;
482 switch (lparam) {
483 case SHCNE_MEDIAINSERTED: {
484 std::vector<base::FilePath> paths;
485 paths.push_back(base::FilePath(sPath));
486 AddDevicesOnUIThread(paths);
487 break;
489 case SHCNE_MEDIAREMOVED: {
490 HandleDeviceDetachEventOnUIThread(sPath);
491 break;
497 void VolumeMountWatcherWin::SetNotifications(
498 StorageMonitor::Receiver* notifications) {
499 notifications_ = notifications;
502 VolumeMountWatcherWin::~VolumeMountWatcherWin() {
503 weak_factory_.InvalidateWeakPtrs();
506 void VolumeMountWatcherWin::HandleDeviceAttachEventOnUIThread(
507 const base::FilePath& device_path,
508 const StorageInfo& info) {
509 DCHECK_CURRENTLY_ON(BrowserThread::UI);
511 device_metadata_[device_path] = info;
513 if (notifications_)
514 notifications_->ProcessAttach(info);
516 DeviceCheckComplete(device_path);
519 void VolumeMountWatcherWin::HandleDeviceDetachEventOnUIThread(
520 const base::string16& device_location) {
521 DCHECK_CURRENTLY_ON(BrowserThread::UI);
523 MountPointDeviceMetadataMap::const_iterator device_info =
524 device_metadata_.find(base::FilePath(device_location));
525 // If the device isn't type removable (like a CD), it won't be there.
526 if (device_info == device_metadata_.end())
527 return;
529 if (notifications_)
530 notifications_->ProcessDetach(device_info->second.device_id());
531 device_metadata_.erase(device_info);
534 void VolumeMountWatcherWin::EjectDevice(
535 const std::string& device_id,
536 base::Callback<void(StorageMonitor::EjectStatus)> callback) {
537 DCHECK_CURRENTLY_ON(BrowserThread::UI);
538 base::FilePath device = MediaStorageUtil::FindDevicePathById(device_id);
539 if (device.empty()) {
540 callback.Run(StorageMonitor::EJECT_FAILURE);
541 return;
543 if (device_metadata_.erase(device) == 0) {
544 callback.Run(StorageMonitor::EJECT_FAILURE);
545 return;
548 device_info_task_runner_->PostTask(
549 FROM_HERE, base::Bind(&EjectDeviceInThreadPool, device, callback,
550 device_info_task_runner_, 0));
553 } // namespace storage_monitor