Elim cr-checkbox
[chromium-blink-merge.git] / chrome / browser / chromeos / file_manager / volume_manager.cc
blob0d3f439606edbbe385d601782485eab0f4f09b3a
1 // Copyright 2013 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 "chrome/browser/chromeos/file_manager/volume_manager.h"
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/logging.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/metrics/histogram.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "chrome/browser/chromeos/drive/drive_integration_service.h"
19 #include "chrome/browser/chromeos/drive/file_system_util.h"
20 #include "chrome/browser/chromeos/file_manager/path_util.h"
21 #include "chrome/browser/chromeos/file_manager/snapshot_manager.h"
22 #include "chrome/browser/chromeos/file_manager/volume_manager_factory.h"
23 #include "chrome/browser/chromeos/file_manager/volume_manager_observer.h"
24 #include "chrome/browser/chromeos/file_system_provider/provided_file_system_info.h"
25 #include "chrome/browser/chromeos/profiles/profile_helper.h"
26 #include "chrome/browser/media_galleries/fileapi/mtp_device_map_service.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/common/pref_names.h"
29 #include "chromeos/chromeos_switches.h"
30 #include "chromeos/disks/disk_mount_manager.h"
31 #include "components/drive/file_system_core_util.h"
32 #include "components/drive/file_system_interface.h"
33 #include "components/storage_monitor/storage_monitor.h"
34 #include "content/public/browser/browser_context.h"
35 #include "content/public/browser/browser_thread.h"
36 #include "device/media_transfer_protocol/media_transfer_protocol_manager.h"
37 #include "storage/browser/fileapi/external_mount_points.h"
39 namespace file_manager {
40 namespace {
42 const uint32 kAccessCapabilityReadWrite = 0;
43 const uint32 kFilesystemTypeGenericHierarchical = 2;
44 const char kFileManagerMTPMountNamePrefix[] = "fileman-mtp-";
45 const char kMtpVolumeIdPrefix [] = "mtp:";
46 const char kRootPath[] = "/";
48 // Registers |path| as the "Downloads" folder to the FileSystem API backend.
49 // If another folder is already mounted. It revokes and overrides the old one.
50 bool RegisterDownloadsMountPoint(Profile* profile, const base::FilePath& path) {
51 // Although we show only profile's own "Downloads" folder in Files.app,
52 // in the backend we need to mount all profile's download directory globally.
53 // Otherwise, Files.app cannot support cross-profile file copies, etc.
54 // For this reason, we need to register to the global GetSystemInstance().
55 const std::string mount_point_name =
56 file_manager::util::GetDownloadsMountPointName(profile);
57 storage::ExternalMountPoints* const mount_points =
58 storage::ExternalMountPoints::GetSystemInstance();
60 // In some tests we want to override existing Downloads mount point, so we
61 // first revoke the existing mount point (if any).
62 mount_points->RevokeFileSystem(mount_point_name);
63 return mount_points->RegisterFileSystem(mount_point_name,
64 storage::kFileSystemTypeNativeLocal,
65 storage::FileSystemMountOption(),
66 path);
69 // Finds the path register as the "Downloads" folder to FileSystem API backend.
70 // Returns false if it is not registered.
71 bool FindDownloadsMountPointPath(Profile* profile, base::FilePath* path) {
72 const std::string mount_point_name =
73 util::GetDownloadsMountPointName(profile);
74 storage::ExternalMountPoints* const mount_points =
75 storage::ExternalMountPoints::GetSystemInstance();
77 return mount_points->GetRegisteredPath(mount_point_name, path);
80 VolumeType MountTypeToVolumeType(chromeos::MountType type) {
81 switch (type) {
82 case chromeos::MOUNT_TYPE_INVALID:
83 // We don't expect this value, but list here, so that when any value
84 // is added to the enum definition but this is not edited, the compiler
85 // warns it.
86 break;
87 case chromeos::MOUNT_TYPE_DEVICE:
88 return VOLUME_TYPE_REMOVABLE_DISK_PARTITION;
89 case chromeos::MOUNT_TYPE_ARCHIVE:
90 return VOLUME_TYPE_MOUNTED_ARCHIVE_FILE;
93 NOTREACHED();
94 return VOLUME_TYPE_DOWNLOADS_DIRECTORY;
97 // Returns a string representation of the given volume type.
98 std::string VolumeTypeToString(VolumeType type) {
99 switch (type) {
100 case VOLUME_TYPE_GOOGLE_DRIVE:
101 return "drive";
102 case VOLUME_TYPE_DOWNLOADS_DIRECTORY:
103 return "downloads";
104 case VOLUME_TYPE_REMOVABLE_DISK_PARTITION:
105 return "removable";
106 case VOLUME_TYPE_MOUNTED_ARCHIVE_FILE:
107 return "archive";
108 case VOLUME_TYPE_PROVIDED:
109 return "provided";
110 case VOLUME_TYPE_MTP:
111 return "mtp";
112 case VOLUME_TYPE_TESTING:
113 return "testing";
114 case NUM_VOLUME_TYPE:
115 break;
117 NOTREACHED();
118 return "";
121 // Generates a unique volume ID for the given volume info.
122 std::string GenerateVolumeId(const Volume& volume) {
123 // For the same volume type, base names are unique, as mount points are
124 // flat for the same volume type.
125 return (VolumeTypeToString(volume.type()) + ":" +
126 volume.mount_path().BaseName().AsUTF8Unsafe());
129 std::string GetMountPointNameForMediaStorage(
130 const storage_monitor::StorageInfo& info) {
131 std::string name(kFileManagerMTPMountNamePrefix);
132 name += info.device_id();
133 return name;
136 } // namespace
138 Volume::Volume()
139 : source_(SOURCE_FILE),
140 type_(VOLUME_TYPE_GOOGLE_DRIVE),
141 device_type_(chromeos::DEVICE_TYPE_UNKNOWN),
142 mount_condition_(chromeos::disks::MOUNT_CONDITION_NONE),
143 mount_context_(MOUNT_CONTEXT_UNKNOWN),
144 is_parent_(false),
145 is_read_only_(false),
146 has_media_(false),
147 configurable_(false),
148 watchable_(false) {
151 Volume::~Volume() {
154 // static
155 Volume* Volume::CreateForDrive(Profile* profile) {
156 const base::FilePath& drive_path =
157 drive::util::GetDriveMountPointPath(profile);
158 Volume* const volume = new Volume;
159 volume->type_ = VOLUME_TYPE_GOOGLE_DRIVE;
160 volume->device_type_ = chromeos::DEVICE_TYPE_UNKNOWN;
161 volume->source_path_ = drive_path;
162 volume->source_ = SOURCE_NETWORK;
163 volume->mount_path_ = drive_path;
164 volume->mount_condition_ = chromeos::disks::MOUNT_CONDITION_NONE;
165 volume->volume_id_ = GenerateVolumeId(*volume);
166 volume->watchable_ = true;
167 return volume;
170 // static
171 Volume* Volume::CreateForDownloads(const base::FilePath& downloads_path) {
172 Volume* const volume = new Volume;
173 volume->type_ = VOLUME_TYPE_DOWNLOADS_DIRECTORY;
174 volume->device_type_ = chromeos::DEVICE_TYPE_UNKNOWN;
175 // Keep source_path empty.
176 volume->source_ = SOURCE_SYSTEM;
177 volume->mount_path_ = downloads_path;
178 volume->mount_condition_ = chromeos::disks::MOUNT_CONDITION_NONE;
179 volume->volume_id_ = GenerateVolumeId(*volume);
180 volume->watchable_ = true;
181 return volume;
184 // static
185 Volume* Volume::CreateForRemovable(
186 const chromeos::disks::DiskMountManager::MountPointInfo& mount_point,
187 const chromeos::disks::DiskMountManager::Disk* disk) {
188 Volume* const volume = new Volume;
189 volume->type_ = MountTypeToVolumeType(mount_point.mount_type);
190 volume->source_path_ = base::FilePath(mount_point.source_path);
191 volume->source_ = mount_point.mount_type == chromeos::MOUNT_TYPE_ARCHIVE
192 ? SOURCE_FILE
193 : SOURCE_DEVICE;
194 volume->mount_path_ = base::FilePath(mount_point.mount_path);
195 volume->mount_condition_ = mount_point.mount_condition;
196 volume->volume_label_ = volume->mount_path().BaseName().AsUTF8Unsafe();
197 if (disk) {
198 volume->device_type_ = disk->device_type();
199 volume->system_path_prefix_ = base::FilePath(disk->system_path_prefix());
200 volume->is_parent_ = disk->is_parent();
201 volume->is_read_only_ = disk->is_read_only();
202 volume->has_media_ = disk->has_media();
203 } else {
204 volume->device_type_ = chromeos::DEVICE_TYPE_UNKNOWN;
205 volume->is_read_only_ =
206 (mount_point.mount_type == chromeos::MOUNT_TYPE_ARCHIVE);
208 volume->volume_id_ = GenerateVolumeId(*volume);
209 volume->watchable_ = true;
210 return volume;
213 // static
214 Volume* Volume::CreateForProvidedFileSystem(
215 const chromeos::file_system_provider::ProvidedFileSystemInfo&
216 file_system_info,
217 MountContext mount_context) {
218 Volume* const volume = new Volume;
219 volume->file_system_id_ = file_system_info.file_system_id();
220 volume->extension_id_ = file_system_info.extension_id();
221 switch (file_system_info.source()) {
222 case extensions::SOURCE_FILE:
223 volume->source_ = SOURCE_FILE;
224 break;
225 case extensions::SOURCE_DEVICE:
226 volume->source_ = SOURCE_DEVICE;
227 break;
228 case extensions::SOURCE_NETWORK:
229 volume->source_ = SOURCE_NETWORK;
230 break;
232 volume->volume_label_ = file_system_info.display_name();
233 volume->type_ = VOLUME_TYPE_PROVIDED;
234 volume->mount_path_ = file_system_info.mount_path();
235 volume->mount_condition_ = chromeos::disks::MOUNT_CONDITION_NONE;
236 volume->mount_context_ = mount_context;
237 volume->is_parent_ = true;
238 volume->is_read_only_ = !file_system_info.writable();
239 volume->configurable_ = file_system_info.configurable();
240 volume->watchable_ = file_system_info.watchable();
241 volume->volume_id_ = GenerateVolumeId(*volume);
242 return volume;
245 // static
246 Volume* Volume::CreateForMTP(const base::FilePath& mount_path,
247 const std::string& label,
248 bool read_only) {
249 Volume* const volume = new Volume;
250 volume->type_ = VOLUME_TYPE_MTP;
251 volume->mount_path_ = mount_path;
252 volume->mount_condition_ = chromeos::disks::MOUNT_CONDITION_NONE;
253 volume->is_parent_ = true;
254 volume->is_read_only_ = read_only;
255 volume->volume_id_ = kMtpVolumeIdPrefix + label;
256 volume->volume_label_ = label;
257 volume->source_path_ = mount_path;
258 volume->source_ = SOURCE_DEVICE;
259 volume->device_type_ = chromeos::DEVICE_TYPE_MOBILE;
260 return volume;
263 // static
264 Volume* Volume::CreateForTesting(const base::FilePath& path,
265 VolumeType volume_type,
266 chromeos::DeviceType device_type,
267 bool read_only) {
268 Volume* const volume = new Volume;
269 volume->type_ = volume_type;
270 volume->device_type_ = device_type;
271 // Keep source_path empty.
272 volume->source_ = SOURCE_DEVICE;
273 volume->mount_path_ = path;
274 volume->mount_condition_ = chromeos::disks::MOUNT_CONDITION_NONE;
275 volume->is_read_only_ = read_only;
276 volume->volume_id_ = GenerateVolumeId(*volume);
277 return volume;
280 // static
281 Volume* Volume::CreateForTesting(const base::FilePath& device_path,
282 const base::FilePath& mount_path) {
283 Volume* const volume = new Volume;
284 volume->system_path_prefix_ = device_path;
285 volume->mount_path_ = mount_path;
286 return volume;
289 VolumeManager::VolumeManager(
290 Profile* profile,
291 drive::DriveIntegrationService* drive_integration_service,
292 chromeos::PowerManagerClient* power_manager_client,
293 chromeos::disks::DiskMountManager* disk_mount_manager,
294 chromeos::file_system_provider::Service* file_system_provider_service,
295 GetMtpStorageInfoCallback get_mtp_storage_info_callback)
296 : profile_(profile),
297 drive_integration_service_(drive_integration_service),
298 disk_mount_manager_(disk_mount_manager),
299 file_system_provider_service_(file_system_provider_service),
300 get_mtp_storage_info_callback_(get_mtp_storage_info_callback),
301 snapshot_manager_(new SnapshotManager(profile_)),
302 weak_ptr_factory_(this) {
303 DCHECK(disk_mount_manager);
306 VolumeManager::~VolumeManager() {
309 VolumeManager* VolumeManager::Get(content::BrowserContext* context) {
310 return VolumeManagerFactory::Get(context);
313 void VolumeManager::Initialize() {
314 // If in Sign in profile, then skip mounting and listening for mount events.
315 if (chromeos::ProfileHelper::IsSigninProfile(profile_))
316 return;
318 // Register 'Downloads' folder for the profile to the file system.
319 const base::FilePath downloads =
320 file_manager::util::GetDownloadsFolderForProfile(profile_);
321 const bool success = RegisterDownloadsMountPoint(profile_, downloads);
322 DCHECK(success);
324 DoMountEvent(chromeos::MOUNT_ERROR_NONE,
325 make_linked_ptr(Volume::CreateForDownloads(downloads)));
327 // Subscribe to DriveIntegrationService.
328 if (drive_integration_service_) {
329 drive_integration_service_->AddObserver(this);
330 if (drive_integration_service_->IsMounted()) {
331 DoMountEvent(chromeos::MOUNT_ERROR_NONE,
332 make_linked_ptr(Volume::CreateForDrive(profile_)));
336 // Subscribe to DiskMountManager.
337 disk_mount_manager_->AddObserver(this);
338 disk_mount_manager_->EnsureMountInfoRefreshed(
339 base::Bind(&VolumeManager::OnDiskMountManagerRefreshed,
340 weak_ptr_factory_.GetWeakPtr()),
341 false /* force */);
343 // Subscribe to FileSystemProviderService and register currently mounted
344 // volumes for the profile.
345 if (file_system_provider_service_) {
346 using chromeos::file_system_provider::ProvidedFileSystemInfo;
347 file_system_provider_service_->AddObserver(this);
349 std::vector<ProvidedFileSystemInfo> file_system_info_list =
350 file_system_provider_service_->GetProvidedFileSystemInfoList();
351 for (size_t i = 0; i < file_system_info_list.size(); ++i) {
352 linked_ptr<Volume> volume(Volume::CreateForProvidedFileSystem(
353 file_system_info_list[i], MOUNT_CONTEXT_AUTO));
354 DoMountEvent(chromeos::MOUNT_ERROR_NONE, volume);
358 // Subscribe to Profile Preference change.
359 pref_change_registrar_.Init(profile_->GetPrefs());
360 pref_change_registrar_.Add(
361 prefs::kExternalStorageDisabled,
362 base::Bind(&VolumeManager::OnExternalStorageDisabledChanged,
363 weak_ptr_factory_.GetWeakPtr()));
365 // Subscribe to storage monitor for MTP notifications.
366 if (storage_monitor::StorageMonitor::GetInstance()) {
367 storage_monitor::StorageMonitor::GetInstance()->EnsureInitialized(
368 base::Bind(&VolumeManager::OnStorageMonitorInitialized,
369 weak_ptr_factory_.GetWeakPtr()));
373 void VolumeManager::Shutdown() {
374 weak_ptr_factory_.InvalidateWeakPtrs();
376 snapshot_manager_.reset();
377 pref_change_registrar_.RemoveAll();
378 disk_mount_manager_->RemoveObserver(this);
379 if (storage_monitor::StorageMonitor::GetInstance())
380 storage_monitor::StorageMonitor::GetInstance()->RemoveObserver(this);
382 if (drive_integration_service_)
383 drive_integration_service_->RemoveObserver(this);
385 if (file_system_provider_service_)
386 file_system_provider_service_->RemoveObserver(this);
389 void VolumeManager::AddObserver(VolumeManagerObserver* observer) {
390 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
391 DCHECK(observer);
392 observers_.AddObserver(observer);
395 void VolumeManager::RemoveObserver(VolumeManagerObserver* observer) {
396 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
397 DCHECK(observer);
398 observers_.RemoveObserver(observer);
401 std::vector<base::WeakPtr<Volume>> VolumeManager::GetVolumeList() {
402 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
404 std::vector<base::WeakPtr<Volume>> result;
405 for (const auto& pair : mounted_volumes_) {
406 result.push_back(pair.second->AsWeakPtr());
408 return result;
411 base::WeakPtr<Volume> VolumeManager::FindVolumeById(
412 const std::string& volume_id) {
413 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
415 const auto it = mounted_volumes_.find(volume_id);
416 if (it != mounted_volumes_.end())
417 return it->second->AsWeakPtr();
418 return base::WeakPtr<Volume>();
421 bool VolumeManager::RegisterDownloadsDirectoryForTesting(
422 const base::FilePath& path) {
423 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
425 base::FilePath old_path;
426 if (FindDownloadsMountPointPath(profile_, &old_path)) {
427 DoUnmountEvent(chromeos::MOUNT_ERROR_NONE,
428 make_linked_ptr(Volume::CreateForDownloads(old_path)));
431 bool success = RegisterDownloadsMountPoint(profile_, path);
432 DoMountEvent(
433 success ? chromeos::MOUNT_ERROR_NONE : chromeos::MOUNT_ERROR_INVALID_PATH,
434 make_linked_ptr(Volume::CreateForDownloads(path)));
435 return success;
438 void VolumeManager::AddVolumeForTesting(const base::FilePath& path,
439 VolumeType volume_type,
440 chromeos::DeviceType device_type,
441 bool read_only) {
442 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
443 DoMountEvent(chromeos::MOUNT_ERROR_NONE,
444 make_linked_ptr(Volume::CreateForTesting(
445 path, volume_type, device_type, read_only)));
448 void VolumeManager::AddVolumeForTesting(const linked_ptr<Volume>& volume) {
449 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
450 DoMountEvent(chromeos::MOUNT_ERROR_NONE, volume);
453 void VolumeManager::OnFileSystemMounted() {
454 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
456 // Raise mount event.
457 // We can pass chromeos::MOUNT_ERROR_NONE even when authentication is failed
458 // or network is unreachable. These two errors will be handled later.
459 linked_ptr<Volume> volume(Volume::CreateForDrive(profile_));
460 DoMountEvent(chromeos::MOUNT_ERROR_NONE, volume);
463 void VolumeManager::OnFileSystemBeingUnmounted() {
464 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
466 linked_ptr<Volume> volume(Volume::CreateForDrive(profile_));
467 DoUnmountEvent(chromeos::MOUNT_ERROR_NONE, volume);
470 void VolumeManager::OnDiskEvent(
471 chromeos::disks::DiskMountManager::DiskEvent event,
472 const chromeos::disks::DiskMountManager::Disk* disk) {
473 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
475 // Disregard hidden devices.
476 if (disk->is_hidden())
477 return;
479 switch (event) {
480 case chromeos::disks::DiskMountManager::DISK_ADDED:
481 case chromeos::disks::DiskMountManager::DISK_CHANGED: {
482 if (disk->device_path().empty()) {
483 DVLOG(1) << "Empty system path for " << disk->device_path();
484 return;
487 bool mounting = false;
488 if (disk->mount_path().empty() && disk->has_media() &&
489 !profile_->GetPrefs()->GetBoolean(prefs::kExternalStorageDisabled)) {
490 // If disk is not mounted yet and it has media and there is no policy
491 // forbidding external storage, give it a try.
492 // Initiate disk mount operation. MountPath auto-detects the filesystem
493 // format if the second argument is empty. The third argument (mount
494 // label) is not used in a disk mount operation.
495 disk_mount_manager_->MountPath(
496 disk->device_path(), std::string(), std::string(),
497 chromeos::MOUNT_TYPE_DEVICE);
498 mounting = true;
501 // Notify to observers.
502 FOR_EACH_OBSERVER(VolumeManagerObserver, observers_,
503 OnDiskAdded(*disk, mounting));
504 return;
507 case chromeos::disks::DiskMountManager::DISK_REMOVED:
508 // If the disk is already mounted, unmount it.
509 if (!disk->mount_path().empty()) {
510 disk_mount_manager_->UnmountPath(
511 disk->mount_path(),
512 chromeos::UNMOUNT_OPTIONS_LAZY,
513 chromeos::disks::DiskMountManager::UnmountPathCallback());
516 // Notify to observers.
517 FOR_EACH_OBSERVER(VolumeManagerObserver, observers_,
518 OnDiskRemoved(*disk));
519 return;
521 NOTREACHED();
524 void VolumeManager::OnDeviceEvent(
525 chromeos::disks::DiskMountManager::DeviceEvent event,
526 const std::string& device_path) {
527 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
529 DVLOG(1) << "OnDeviceEvent: " << event << ", " << device_path;
530 switch (event) {
531 case chromeos::disks::DiskMountManager::DEVICE_ADDED:
532 FOR_EACH_OBSERVER(VolumeManagerObserver, observers_,
533 OnDeviceAdded(device_path));
534 return;
535 case chromeos::disks::DiskMountManager::DEVICE_REMOVED: {
536 FOR_EACH_OBSERVER(
537 VolumeManagerObserver, observers_, OnDeviceRemoved(device_path));
538 return;
540 case chromeos::disks::DiskMountManager::DEVICE_SCANNED:
541 DVLOG(1) << "Ignore SCANNED event: " << device_path;
542 return;
544 NOTREACHED();
547 void VolumeManager::OnMountEvent(
548 chromeos::disks::DiskMountManager::MountEvent event,
549 chromeos::MountError error_code,
550 const chromeos::disks::DiskMountManager::MountPointInfo& mount_info) {
551 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
552 DCHECK_NE(chromeos::MOUNT_TYPE_INVALID, mount_info.mount_type);
554 if (mount_info.mount_type == chromeos::MOUNT_TYPE_ARCHIVE) {
555 // If the file is not mounted now, tell it to drive file system so that
556 // it can handle file caching correctly.
557 // Note that drive file system knows if the file is managed by drive file
558 // system or not, so here we report all paths.
559 if ((event == chromeos::disks::DiskMountManager::MOUNTING &&
560 error_code != chromeos::MOUNT_ERROR_NONE) ||
561 (event == chromeos::disks::DiskMountManager::UNMOUNTING &&
562 error_code == chromeos::MOUNT_ERROR_NONE)) {
563 drive::FileSystemInterface* const file_system =
564 drive::util::GetFileSystemByProfile(profile_);
565 if (file_system) {
566 file_system->MarkCacheFileAsUnmounted(
567 base::FilePath(mount_info.source_path),
568 base::Bind(&drive::util::EmptyFileOperationCallback));
573 // Notify a mounting/unmounting event to observers.
574 const chromeos::disks::DiskMountManager::Disk* const disk =
575 disk_mount_manager_->FindDiskBySourcePath(mount_info.source_path);
576 linked_ptr<Volume> volume(Volume::CreateForRemovable(mount_info, disk));
577 switch (event) {
578 case chromeos::disks::DiskMountManager::MOUNTING: {
579 DoMountEvent(error_code, volume);
580 return;
582 case chromeos::disks::DiskMountManager::UNMOUNTING:
583 DoUnmountEvent(error_code, volume);
584 return;
586 NOTREACHED();
589 void VolumeManager::OnFormatEvent(
590 chromeos::disks::DiskMountManager::FormatEvent event,
591 chromeos::FormatError error_code,
592 const std::string& device_path) {
593 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
594 DVLOG(1) << "OnDeviceEvent: " << event << ", " << error_code
595 << ", " << device_path;
597 switch (event) {
598 case chromeos::disks::DiskMountManager::FORMAT_STARTED:
599 FOR_EACH_OBSERVER(
600 VolumeManagerObserver, observers_,
601 OnFormatStarted(device_path,
602 error_code == chromeos::FORMAT_ERROR_NONE));
603 return;
604 case chromeos::disks::DiskMountManager::FORMAT_COMPLETED:
605 if (error_code == chromeos::FORMAT_ERROR_NONE) {
606 // If format is completed successfully, try to mount the device.
607 // MountPath auto-detects filesystem format if second argument is
608 // empty. The third argument (mount label) is not used in a disk mount
609 // operation.
610 disk_mount_manager_->MountPath(
611 device_path, std::string(), std::string(),
612 chromeos::MOUNT_TYPE_DEVICE);
615 FOR_EACH_OBSERVER(
616 VolumeManagerObserver, observers_,
617 OnFormatCompleted(device_path,
618 error_code == chromeos::FORMAT_ERROR_NONE));
620 return;
622 NOTREACHED();
625 void VolumeManager::OnProvidedFileSystemMount(
626 const chromeos::file_system_provider::ProvidedFileSystemInfo&
627 file_system_info,
628 chromeos::file_system_provider::MountContext context,
629 base::File::Error error) {
630 MountContext volume_context = MOUNT_CONTEXT_UNKNOWN;
631 switch (context) {
632 case chromeos::file_system_provider::MOUNT_CONTEXT_USER:
633 volume_context = MOUNT_CONTEXT_USER;
634 break;
635 case chromeos::file_system_provider::MOUNT_CONTEXT_RESTORE:
636 volume_context = MOUNT_CONTEXT_AUTO;
637 break;
640 linked_ptr<Volume> volume(
641 Volume::CreateForProvidedFileSystem(file_system_info, volume_context));
643 // TODO(mtomasz): Introduce own type, and avoid using MountError internally,
644 // since it is related to cros disks only.
645 chromeos::MountError mount_error;
646 switch (error) {
647 case base::File::FILE_OK:
648 mount_error = chromeos::MOUNT_ERROR_NONE;
649 break;
650 case base::File::FILE_ERROR_EXISTS:
651 mount_error = chromeos::MOUNT_ERROR_PATH_ALREADY_MOUNTED;
652 break;
653 default:
654 mount_error = chromeos::MOUNT_ERROR_UNKNOWN;
655 break;
658 DoMountEvent(mount_error, volume);
661 void VolumeManager::OnProvidedFileSystemUnmount(
662 const chromeos::file_system_provider::ProvidedFileSystemInfo&
663 file_system_info,
664 base::File::Error error) {
665 // TODO(mtomasz): Introduce own type, and avoid using MountError internally,
666 // since it is related to cros disks only.
667 const chromeos::MountError mount_error = error == base::File::FILE_OK
668 ? chromeos::MOUNT_ERROR_NONE
669 : chromeos::MOUNT_ERROR_UNKNOWN;
670 linked_ptr<Volume> volume(Volume::CreateForProvidedFileSystem(
671 file_system_info, MOUNT_CONTEXT_UNKNOWN));
672 DoUnmountEvent(mount_error, volume);
675 void VolumeManager::OnExternalStorageDisabledChanged() {
676 // If the policy just got disabled we have to unmount every device currently
677 // mounted. The opposite is fine - we can let the user re-plug her device to
678 // make it available.
679 if (profile_->GetPrefs()->GetBoolean(prefs::kExternalStorageDisabled)) {
680 // We do not iterate on mount_points directly, because mount_points can
681 // be changed by UnmountPath().
682 // TODO(hidehiko): Is it necessary to unmount mounted archives, too, here?
683 while (!disk_mount_manager_->mount_points().empty()) {
684 std::string mount_path =
685 disk_mount_manager_->mount_points().begin()->second.mount_path;
686 disk_mount_manager_->UnmountPath(
687 mount_path,
688 chromeos::UNMOUNT_OPTIONS_NONE,
689 chromeos::disks::DiskMountManager::UnmountPathCallback());
694 void VolumeManager::OnRemovableStorageAttached(
695 const storage_monitor::StorageInfo& info) {
696 if (!storage_monitor::StorageInfo::IsMTPDevice(info.device_id()))
697 return;
698 if (profile_->GetPrefs()->GetBoolean(prefs::kExternalStorageDisabled))
699 return;
701 const base::FilePath path = base::FilePath::FromUTF8Unsafe(info.location());
702 const std::string fsid = GetMountPointNameForMediaStorage(info);
703 const std::string base_name = base::UTF16ToUTF8(info.model_name());
705 // Assign a fresh volume ID based on the volume name.
706 std::string label = base_name;
707 for (int i = 2; mounted_volumes_.count(kMtpVolumeIdPrefix + label); ++i)
708 label = base_name + base::StringPrintf(" (%d)", i);
710 bool result =
711 storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
712 fsid,
713 storage::kFileSystemTypeDeviceMediaAsFileStorage,
714 storage::FileSystemMountOption(),
715 path);
716 DCHECK(result);
718 // Resolve mtp storage name and get MtpStorageInfo.
719 std::string storage_name;
720 base::RemoveChars(info.location(), kRootPath, &storage_name);
721 DCHECK(!storage_name.empty());
723 const MtpStorageInfo* mtp_storage_info;
724 if (get_mtp_storage_info_callback_.is_null()) {
725 mtp_storage_info = storage_monitor::StorageMonitor::GetInstance()
726 ->media_transfer_protocol_manager()
727 ->GetStorageInfo(storage_name);
728 } else {
729 mtp_storage_info = get_mtp_storage_info_callback_.Run(storage_name);
731 DCHECK(mtp_storage_info);
733 // Mtp write is enabled only when the device is writable and supports generic
734 // hierarchical file system.
735 const bool read_only =
736 base::CommandLine::ForCurrentProcess()->HasSwitch(
737 chromeos::switches::kDisableMtpWriteSupport) ||
738 mtp_storage_info->access_capability() != kAccessCapabilityReadWrite ||
739 mtp_storage_info->filesystem_type() != kFilesystemTypeGenericHierarchical;
741 content::BrowserThread::PostTask(
742 content::BrowserThread::IO, FROM_HERE,
743 base::Bind(&MTPDeviceMapService::RegisterMTPFileSystem,
744 base::Unretained(MTPDeviceMapService::GetInstance()),
745 info.location(), fsid, read_only));
747 linked_ptr<Volume> volume(Volume::CreateForMTP(path, label, read_only));
748 DoMountEvent(chromeos::MOUNT_ERROR_NONE, volume);
751 void VolumeManager::OnRemovableStorageDetached(
752 const storage_monitor::StorageInfo& info) {
753 if (!storage_monitor::StorageInfo::IsMTPDevice(info.device_id()))
754 return;
756 for (const auto mounted_volume : mounted_volumes_) {
757 if (mounted_volume.second->source_path().value() == info.location()) {
758 DoUnmountEvent(chromeos::MOUNT_ERROR_NONE, mounted_volume.second);
760 const std::string fsid = GetMountPointNameForMediaStorage(info);
761 storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(fsid);
762 content::BrowserThread::PostTask(
763 content::BrowserThread::IO, FROM_HERE, base::Bind(
764 &MTPDeviceMapService::RevokeMTPFileSystem,
765 base::Unretained(MTPDeviceMapService::GetInstance()),
766 fsid));
767 return;
772 void VolumeManager::OnDiskMountManagerRefreshed(bool success) {
773 if (!success) {
774 LOG(ERROR) << "Failed to refresh disk mount manager";
775 return;
778 std::vector<linked_ptr<Volume>> archives;
780 const chromeos::disks::DiskMountManager::MountPointMap& mount_points =
781 disk_mount_manager_->mount_points();
782 for (chromeos::disks::DiskMountManager::MountPointMap::const_iterator it =
783 mount_points.begin();
784 it != mount_points.end();
785 ++it) {
786 if (it->second.mount_type == chromeos::MOUNT_TYPE_ARCHIVE) {
787 // Archives are mounted after other types of volume. See below.
788 archives.push_back(
789 make_linked_ptr(Volume::CreateForRemovable(it->second, NULL)));
790 continue;
792 DoMountEvent(chromeos::MOUNT_ERROR_NONE,
793 make_linked_ptr(Volume::CreateForRemovable(
794 it->second, disk_mount_manager_->FindDiskBySourcePath(
795 it->second.source_path))));
798 // We mount archives only if they are opened from currently mounted volumes.
799 // To check the condition correctly in DoMountEvent, we care about the order.
800 std::vector<bool> done(archives.size(), false);
801 for (size_t i = 0; i < archives.size(); ++i) {
802 if (done[i])
803 continue;
805 std::vector<linked_ptr<Volume>> chain;
806 done[i] = true;
807 chain.push_back(archives[i]);
809 // If archives[i]'s source_path is in another archive, mount it first.
810 for (size_t parent = i + 1; parent < archives.size(); ++parent) {
811 if (!done[parent] &&
812 archives[parent]->mount_path().IsParent(
813 chain.back()->source_path())) {
814 done[parent] = true;
815 chain.push_back(archives[parent]);
816 parent = i + 1; // Search archives[parent]'s parent from the beginning.
820 // Mount from the tail of chain.
821 for (size_t i = chain.size(); i > 0; --i) {
822 DoMountEvent(chromeos::MOUNT_ERROR_NONE, chain[i - 1]);
827 void VolumeManager::OnStorageMonitorInitialized() {
828 std::vector<storage_monitor::StorageInfo> storages =
829 storage_monitor::StorageMonitor::GetInstance()->GetAllAvailableStorages();
830 for (size_t i = 0; i < storages.size(); ++i)
831 OnRemovableStorageAttached(storages[i]);
832 storage_monitor::StorageMonitor::GetInstance()->AddObserver(this);
835 void VolumeManager::DoMountEvent(chromeos::MountError error_code,
836 const linked_ptr<Volume>& volume) {
837 // Archive files are mounted globally in system. We however don't want to show
838 // archives from profile-specific folders (Drive/Downloads) of other users in
839 // multi-profile session. To this end, we filter out archives not on the
840 // volumes already mounted on this VolumeManager instance.
841 if (volume->type() == VOLUME_TYPE_MOUNTED_ARCHIVE_FILE) {
842 // Source may be in Drive cache folder under the current profile directory.
843 bool from_current_profile =
844 profile_->GetPath().IsParent(volume->source_path());
845 for (const auto& mounted_volume : mounted_volumes_) {
846 if (mounted_volume.second->mount_path().IsParent(volume->source_path())) {
847 from_current_profile = true;
848 break;
851 if (!from_current_profile)
852 return;
855 // Filter out removable disks if forbidden by policy for this profile.
856 if (volume->type() == VOLUME_TYPE_REMOVABLE_DISK_PARTITION &&
857 profile_->GetPrefs()->GetBoolean(prefs::kExternalStorageDisabled)) {
858 return;
861 if (error_code == chromeos::MOUNT_ERROR_NONE || volume->mount_condition()) {
862 mounted_volumes_[volume->volume_id()] = volume;
863 UMA_HISTOGRAM_ENUMERATION("FileBrowser.VolumeType", volume->type(),
864 NUM_VOLUME_TYPE);
867 FOR_EACH_OBSERVER(VolumeManagerObserver, observers_,
868 OnVolumeMounted(error_code, *volume));
871 void VolumeManager::DoUnmountEvent(chromeos::MountError error_code,
872 const linked_ptr<Volume>& volume) {
873 if (mounted_volumes_.find(volume->volume_id()) == mounted_volumes_.end())
874 return;
875 if (error_code == chromeos::MOUNT_ERROR_NONE)
876 mounted_volumes_.erase(volume->volume_id());
878 FOR_EACH_OBSERVER(VolumeManagerObserver, observers_,
879 OnVolumeUnmounted(error_code, *volume.get()));
882 } // namespace file_manager