Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(288)

Unified Diff: chrome/browser/chromeos/dbus/cros_disks_client.cc

Issue 8386031: Move chromeos_mount.cc from libcros to Chrome tree (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix for review comments Created 9 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: chrome/browser/chromeos/dbus/cros_disks_client.cc
diff --git a/chrome/browser/chromeos/dbus/cros_disks_client.cc b/chrome/browser/chromeos/dbus/cros_disks_client.cc
new file mode 100644
index 0000000000000000000000000000000000000000..f9bc3747dee284309f0fdeb36aef191f9d48e19d
--- /dev/null
+++ b/chrome/browser/chromeos/dbus/cros_disks_client.cc
@@ -0,0 +1,1148 @@
+// Copyright (c) 2011 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/chromeos/dbus/cros_disks_client.h"
+
+#include <set>
+#include <vector>
+
+#include <sys/statvfs.h>
+
+#include "base/bind.h"
+#include "base/memory/scoped_vector.h"
+#include "base/string_util.h"
+#include "chrome/browser/chromeos/system/runtime_environment.h"
+#include "content/public/browser/browser_thread.h"
+#include "dbus/bus.h"
+#include "dbus/message.h"
+#include "dbus/object_proxy.h"
+#include "third_party/cros_system_api/dbus/service_constants.h"
+
+using content::BrowserThread;
+
+namespace chromeos {
+
+namespace {
+
+const char* kDeviceNotFound = "Device could not be found";
+
+const char* kDefaultMountOptions[] = {
+ "rw",
+ "nodev",
+ "noexec",
+ "nosuid",
+ "sync"
+};
+const char* kDefaultUnmountOptions[] = {
+ "force"
+};
+
+enum MountEventType {
+ DISK_ADDED,
+ DISK_REMOVED,
+ DISK_CHANGED,
+ DEVICE_ADDED,
+ DEVICE_REMOVED,
+ DEVICE_SCANNED,
+ FORMATTING_FINISHED,
+};
+
+class DiskInfo {
+ public:
+ DiskInfo(const std::string& device_path, dbus::Response* response)
+ : device_path_(device_path),
+ is_drive_(false),
+ has_media_(false),
+ on_boot_device_(false),
+ device_type_(UNDEFINED),
+ total_size_(0),
+ is_read_only_(false),
+ is_hidden_(true) {
+ InitializeFromResponse(response);
+ }
+
+ // Device path. (e.g. /sys/devices/pci0000:00/.../8:0:0:0/block/sdb/sdb1)
+ std::string device_path() const { return device_path_; }
+
+ // Disk mount path. (e.g. /media/removable/VOLUME)
+ std::string mount_path() const { return mount_path_; }
+
+ // Disk system path given by udev.
+ // (e.g. /sys/devices/pci0000:00/.../8:0:0:0/block/sdb/sdb1)
+ std::string system_path() const { return system_path_; }
+
+ // Is disk into a drive (i.e. /dev/sdb vs, /dev/sdb1).
+ bool is_drive() const { return is_drive_; }
+
+ // Does the disk have media content.
+ bool has_media() const { return has_media_; }
+
+ // Is the disk on deveice we booted the machien from.
+ bool on_boot_device() const { return on_boot_device_; }
+
+ // Disk file path (e.g /dev/sdb).
+ std::string file_path() const { return file_path_; }
+
+ // Disk label.
+ std::string label() const { return label_; }
+
+ // Disk model
+ std::string drive_label() const { return drive_model_; }
+
+ // Partition table path of the device, if device is partition.
+ std::string partition_slave() const { return partition_slave_; }
+
+ // Device type. Not working well, yet.
+ DeviceType device_type() const { return device_type_; }
+
+ // Total size of the disk.
+ uint64 size() const { return total_size_; }
+
+ // Is the device read-only.
+ bool is_read_only() const { return is_read_only_; }
+
+ bool is_hidden() const { return is_hidden_; }
+
+ private:
+ // Returns the device type from the given arguments.
+ DeviceType GetDeviceType(bool is_optical, bool is_rotational) {
+ if (is_optical)
+ return OPTICAL;
+ if (is_rotational)
+ return HDD;
+ return FLASH;
+ }
+
+ // Pops a bool value when |reader| is not NULL.
+ // It returns true when a value is popped, false otherwise.
+ bool MaybePopBool(dbus::MessageReader* reader, bool* value) {
+ if (!reader)
+ return false;
+ return reader->PopBool(value);
+ }
+
+ // Pops a string value when |reader| is not NULL.
+ // It returns true when a value is popped, false otherwise.
+ bool MaybePopString(dbus::MessageReader* reader, std::string* value) {
+ if (!reader)
+ return false;
+ return reader->PopString(value);
+ }
+
+ // Pops a uint64 value when |reader| is not NULL.
+ // It returns true when a value is popped, false otherwise.
+ bool MaybePopUint64(dbus::MessageReader* reader, uint64* value) {
+ if (!reader)
+ return false;
+ return reader->PopUint64(value);
+ }
+
+ // Pops an array of strings when |reader| is not NULL.
+ // It returns true when an array is popped, false otherwise.
+ bool MaybePopArrayOfStrings(dbus::MessageReader* reader,
+ std::vector<std::string>* value) {
+ if (!reader)
+ return false;
+ return reader->PopArrayOfStrings(value);
+ }
+
+ // Initialize |this| from |response| given by the cros-disks service.
+ void InitializeFromResponse(dbus::Response* response) {
+ dbus::MessageReader response_reader(response);
+ dbus::MessageReader array_reader(response);
+ if (!response_reader.PopArray(&array_reader)) {
+ LOG(ERROR) << "Invalid response: " << response->ToString();
+ return;
+ }
+ // TODO(satorux): Rework this code using Protocol Buffers. crosbug.com/22626
+ ScopedVector<dbus::MessageReader> value_readers_owner;
+ std::map<std::string, dbus::MessageReader*> properties;
+ while (array_reader.HasMoreData()) {
+ // |value_readers_owner| is responsible to delete |value_reader|
+ dbus::MessageReader* value_reader = new dbus::MessageReader(response);
+ value_readers_owner.push_back(value_reader);
+ dbus::MessageReader dict_entry_reader(response);
+ std::string key;
+ if (!array_reader.PopDictEntry(&dict_entry_reader) ||
+ !dict_entry_reader.PopString(&key) ||
+ !dict_entry_reader.PopVariant(value_reader)) {
+ LOG(ERROR) << "Invalid response: " << response->ToString();
+ return;
+ }
+ properties[key] = value_reader;
+ }
+ MaybePopBool(properties[cros_disks::kDeviceIsDrive], &is_drive_);
+ MaybePopBool(properties[cros_disks::kDeviceIsReadOnly], &is_read_only_);
+ MaybePopBool(properties[cros_disks::kDevicePresentationHide], &is_hidden_);
+ MaybePopBool(properties[cros_disks::kDeviceIsMediaAvailable], &has_media_);
+ MaybePopBool(properties[cros_disks::kDeviceIsOnBootDevice],
+ &on_boot_device_);
+ MaybePopString(properties[cros_disks::kNativePath], &system_path_);
+ MaybePopString(properties[cros_disks::kDeviceFile], &file_path_);
+ MaybePopString(properties[cros_disks::kDriveModel], &drive_model_);
+ MaybePopString(properties[cros_disks::kIdLabel], &label_);
+ MaybePopUint64(properties[cros_disks::kDeviceSize], &total_size_);
+
+ std::vector<std::string> mount_paths;
+ if (MaybePopArrayOfStrings(properties[cros_disks::kDeviceMountPaths],
+ &mount_paths) && !mount_paths.empty())
+ mount_path_ = mount_paths[0];
+
+ bool is_rotational, is_optical;
+ if (MaybePopBool(properties[cros_disks::kDriveIsRotational],
+ &is_rotational) &&
+ MaybePopBool(properties[cros_disks::kDeviceIsOpticalDisc],
+ &is_optical))
+ device_type_ = GetDeviceType(is_optical, is_rotational);
+ }
+
+ std::string device_path_;
+ std::string mount_path_;
+ std::string system_path_;
+ bool is_drive_;
+ bool has_media_;
+ bool on_boot_device_;
+
+ std::string file_path_;
+ std::string label_;
+ std::string drive_model_;
+ std::string partition_slave_;
+ DeviceType device_type_;
+ uint64 total_size_;
+ bool is_read_only_;
+ bool is_hidden_;
+};
+
+// A class to make the actual DBus calls for cros-disks service.
+// This class only makes calls, result/error handling should be done
+// by callbacks.
+class CrosDisksDBusProxy {
+ public:
+ // A callback to be called when DBus method call fails.
+ typedef base::Callback<void()> ErrorCallback;
+
+ // A callback to handle the result of Mount.
+ typedef base::Callback<void()> MountCallback;
+
+ // A callback to handle the result of Unmount.
+ // The argument is the device path.
+ typedef base::Callback<void(const std::string&)> UnmountCallback;
+
+ // A callback to handle the result of EnumerateAutoMountableDevices.
+ // The argument is the enumerated device paths.
+ typedef base::Callback<void(const std::vector<std::string>&)
+ > EnumerateAutoMountableDevicesCallback;
+
+ // A callback to handle the result of FormatDevice.
+ // The first argument is the device path.
+ // The second argument is true when formatting succeeded, false otherwise.
+ typedef base::Callback<void(const std::string&, bool)> FormatDeviceCallback;
+
+ // A callback to handle the result of GetDeviceProperties.
+ // The argument is the information about the specified device.
+ typedef base::Callback<void(const DiskInfo&)> GetDevicePropertiesCallback;
+
+ // A callback to handle MountCompleted signal.
+ // The first argument is the error code.
+ // The second argument is the source path.
+ // The third argument is the mount type.
+ // The fourth argument is the mount path.
+ typedef base::Callback<void(MountError, const std::string&, MountType,
+ const std::string&)> MountCompletedHandler;
+
+ // A callback to handle mount events.
+ // The first argument is the event type.
+ // The second argument is the device path.
+ typedef base::Callback<void(MountEventType, const std::string&)
+ > MountEventHandler;
+
+ explicit CrosDisksDBusProxy(dbus::Bus* bus)
+ : proxy_(bus->GetObjectProxy(cros_disks::kCrosDisksServiceName,
+ cros_disks::kCrosDisksServicePath)),
+ weak_ptr_factory_(this) {
+ }
+
+ // Calls Mount method. |callback| is called after the method call succeeds,
+ // otherwise, |error_callback| is called.
+ void Mount(const std::string& source_path,
+ MountType type,
+ const MountPathOptions& options,
+ MountCallback callback,
+ ErrorCallback error_callback) {
+ dbus::MethodCall method_call(cros_disks::kCrosDisksInterface,
+ cros_disks::kMount);
+ dbus::MessageWriter writer(&method_call);
+ writer.AppendString(source_path);
+ writer.AppendString(""); // auto detect filesystem.
+ std::vector<std::string> mount_options(kDefaultMountOptions,
+ kDefaultMountOptions +
+ arraysize(kDefaultMountOptions));
+ writer.AppendArrayOfStrings(mount_options);
+ proxy_->CallMethod(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
+ base::Bind(&CrosDisksDBusProxy::OnMount,
+ weak_ptr_factory_.GetWeakPtr(),
+ callback,
+ error_callback));
+ }
+
+ // Calls Unmount method. |callback| is called after the method call succeeds,
+ // otherwise, |error_callback| is called.
+ void Unmount(const std::string& device_path,
+ UnmountCallback callback,
+ ErrorCallback error_callback) {
+ dbus::MethodCall method_call(cros_disks::kCrosDisksInterface,
+ cros_disks::kUnmount);
+ dbus::MessageWriter writer(&method_call);
+ writer.AppendString(device_path);
+ std::vector<std::string> unmount_options(kDefaultUnmountOptions,
+ kDefaultUnmountOptions +
+ arraysize(kDefaultUnmountOptions));
+ writer.AppendArrayOfStrings(unmount_options);
+ proxy_->CallMethod(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
+ base::Bind(&CrosDisksDBusProxy::OnUnmount,
+ weak_ptr_factory_.GetWeakPtr(),
+ device_path,
+ callback,
+ error_callback));
+ }
+
+ // Calls EnumerateAutoMountableDevices method. |callback| is called after the
+ // method call succeeds, otherwise, |error_callback| is called.
+ void EnumerateAutoMountableDevices(
+ EnumerateAutoMountableDevicesCallback callback,
+ ErrorCallback error_callback) {
+ dbus::MethodCall method_call(cros_disks::kCrosDisksInterface,
+ cros_disks::kEnumerateAutoMountableDevices);
+ proxy_->CallMethod(
+ &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
+ base::Bind(&CrosDisksDBusProxy::OnEnumerateAutoMountableDevices,
+ weak_ptr_factory_.GetWeakPtr(),
+ callback,
+ error_callback));
+ }
+
+ // Calls FormatDevice method. |callback| is called after the method call
+ // succeeds, otherwise, |error_callback| is called.
+ void FormatDevice(const std::string& device_path,
+ const std::string& filesystem,
+ FormatDeviceCallback callback,
+ ErrorCallback error_callback) {
+ dbus::MethodCall method_call(cros_disks::kCrosDisksInterface,
+ cros_disks::kFormatDevice);
+ dbus::MessageWriter writer(&method_call);
+ writer.AppendString(device_path);
+ writer.AppendString(filesystem);
+ proxy_->CallMethod(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
+ base::Bind(&CrosDisksDBusProxy::OnFormatDevice,
+ weak_ptr_factory_.GetWeakPtr(),
+ device_path,
+ callback,
+ error_callback));
+ }
+
+ // Calls GetDeviceProperties method. |callback| is called after the method
+ // call succeeds, otherwise, |error_callback| is called.
+ void GetDeviceProperties(const std::string& device_path,
+ GetDevicePropertiesCallback callback,
+ ErrorCallback error_callback) {
+ dbus::MethodCall method_call(cros_disks::kCrosDisksInterface,
+ cros_disks::kGetDeviceProperties);
+ dbus::MessageWriter writer(&method_call);
+ writer.AppendString(device_path);
+ proxy_->CallMethod(&method_call,
+ dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
+ base::Bind(&CrosDisksDBusProxy::OnGetDeviceProperties,
+ weak_ptr_factory_.GetWeakPtr(),
+ device_path,
+ callback,
+ error_callback));
+ }
+
+ // Registers given callback for events.
+ // |mount_event_handler| is called when mount event signal is received.
+ // |mount_completed_handler| is called when MountCompleted signal is received.
+ void SetUpConnections(MountEventHandler mount_event_handler,
+ MountCompletedHandler mount_completed_handler) {
+ static const SignalEventTuple kSignalEventTuples[] = {
+ { "DeviceAdded", DEVICE_ADDED },
+ { "DeviceScanned", DEVICE_SCANNED },
+ { "DeviceRemoved", DEVICE_REMOVED },
+ { "DiskAdded", DISK_ADDED },
+ { "DiskChanged", DISK_CHANGED },
+ { "DiskRemoved", DISK_REMOVED },
+ { "FormattingFinished", FORMATTING_FINISHED },
+ };
+ const size_t kNumSignalEventTuples = arraysize(kSignalEventTuples);
+
+ for (size_t i = 0; i < kNumSignalEventTuples; ++i) {
+ proxy_->ConnectToSignal(
+ cros_disks::kCrosDisksInterface,
+ kSignalEventTuples[i].signal_name,
+ base::Bind(&CrosDisksDBusProxy::OnMountEvent,
+ weak_ptr_factory_.GetWeakPtr(),
+ kSignalEventTuples[i].event_type,
+ mount_event_handler),
+ base::Bind(&CrosDisksDBusProxy::OnSignalConnected,
+ weak_ptr_factory_.GetWeakPtr()));
+ }
+ proxy_->ConnectToSignal(
+ cros_disks::kCrosDisksInterface,
+ "MountCompleted",
+ base::Bind(&CrosDisksDBusProxy::OnMountCompleted,
+ weak_ptr_factory_.GetWeakPtr(),
+ mount_completed_handler ),
+ base::Bind(&CrosDisksDBusProxy::OnSignalConnected,
+ weak_ptr_factory_.GetWeakPtr()));
+ }
+
+ private:
+ struct SignalEventTuple {
+ const char *signal_name;
+ MountEventType event_type;
+ };
+
+ // Handles the result of Mount and calls |callback| or |error_callback|
+ void OnMount(MountCallback callback,
+ ErrorCallback error_callback,
+ dbus::Response* response) {
+ if (!response) {
+ error_callback.Run();
+ return;
+ }
+ callback.Run();
+ }
+
+ // Handles the result of Unount and calls |callback| or |error_callback|
+ void OnUnmount(const std::string& device_path,
+ UnmountCallback callback,
+ ErrorCallback error_callback,
+ dbus::Response* response) {
+ if (!response) {
+ error_callback.Run();
+ return;
+ }
+ callback.Run(device_path);
+ }
+
+ // Handles the result of EnumerateAutoMountableDevices and calls |callback| or
+ // |error_callback|
+ void OnEnumerateAutoMountableDevices(
+ EnumerateAutoMountableDevicesCallback callback,
+ ErrorCallback error_callback,
+ dbus::Response* response) {
+ if (!response) {
+ error_callback.Run();
+ return;
+ }
+ dbus::MessageReader reader(response);
+ std::vector<std::string> device_paths;
+ if (!reader.PopArrayOfStrings(&device_paths)) {
+ LOG(ERROR) << "Invalid response: " << response->ToString();
+ error_callback.Run();
+ return;
+ }
+ callback.Run(device_paths);
+ }
+
+ // Handles the result of FormatDevice and calls |callback| or |error_callback|
+ void OnFormatDevice(const std::string& device_path,
+ FormatDeviceCallback callback,
+ ErrorCallback error_callback,
+ dbus::Response* response) {
+ if (!response) {
+ error_callback.Run();
+ return;
+ }
+ dbus::MessageReader reader(response);
+ bool success = false;
+ if (!reader.PopBool(&success)) {
+ LOG(ERROR) << "Invalid response: " << response->ToString();
+ error_callback.Run();
+ return;
+ }
+ callback.Run(device_path, success);
+ }
+
+ // Handles the result of GetDeviceProperties and calls |callback| or
+ // |error_callback|
+ void OnGetDeviceProperties(const std::string& device_path,
+ GetDevicePropertiesCallback callback,
+ ErrorCallback error_callback,
+ dbus::Response* response) {
+ if (!response) {
+ error_callback.Run();
+ return;
+ }
+ DiskInfo disk(device_path, response);
+ callback.Run(disk);
+ }
+
+ // Handles mount event signals and calls |handler|
+ void OnMountEvent(MountEventType event_type,
+ MountEventHandler handler,
+ dbus::Signal* signal) {
+ dbus::MessageReader reader(signal);
+ std::string device;
+ if (!reader.PopString(&device)) {
+ LOG(ERROR) << "Invalid signal: " << signal->ToString();
+ return;
+ }
+ handler.Run(event_type, device);
+ }
+
+ // Handles MountCompleted signal and calls |handler|
+ void OnMountCompleted(MountCompletedHandler handler, dbus::Signal* signal) {
+ dbus::MessageReader reader(signal);
+ unsigned int error_code = 0;
+ std::string source_path;
+ unsigned int mount_type = 0;
+ std::string mount_path;
+ if (!reader.PopUint32(&error_code) ||
+ !reader.PopString(&source_path) ||
+ !reader.PopUint32(&mount_type) ||
+ !reader.PopString(&mount_path)) {
+ LOG(ERROR) << "Invalid signal: " << signal->ToString();
+ return;
+ }
+ handler.Run(static_cast<MountError>(error_code), source_path,
+ static_cast<MountType>(mount_type), mount_path);
+ }
+
+ // Handles the result of signal connection setup.
+ void OnSignalConnected(const std::string& interface,
+ const std::string& signal,
+ bool successed) {
+ LOG_IF(ERROR, !successed) << "Connect to " << interface << " " <<
+ signal << " failed.";
+ }
+
+ dbus::ObjectProxy* proxy_;
+ base::WeakPtrFactory<CrosDisksDBusProxy> weak_ptr_factory_;
+};
+
+// The cros-disks implementation.
+class CrosDisksClientImpl : public CrosDisksClient {
+ public:
+ explicit CrosDisksClientImpl(dbus::Bus* bus)
+ : dbus_proxy_(new CrosDisksDBusProxy(bus)),
+ weak_ptr_factory_(this) {
+ dbus_proxy_->SetUpConnections(
+ base::Bind(&CrosDisksClientImpl::OnMountEvent,
+ weak_ptr_factory_.GetWeakPtr()),
+ base::Bind(&CrosDisksClientImpl::OnMountCompleted,
+ weak_ptr_factory_.GetWeakPtr()));
+ }
+
+ ~CrosDisksClientImpl() {
+ }
+
+ virtual void AddObserver(Observer* observer) OVERRIDE {
+ observers_.AddObserver(observer);
+ }
+
+ virtual void RemoveObserver(Observer* observer) OVERRIDE {
+ observers_.RemoveObserver(observer);
+ }
+
+ virtual void MountPath(const std::string& source_path,
+ MountType type,
+ const MountPathOptions& options) OVERRIDE {
+ // Hidden and non-existent devices should not be mounted.
+ if (type == MOUNT_TYPE_DEVICE) {
+ DiskMap::const_iterator it = disks_.find(source_path);
+ if (it == disks_.end() || it->second->is_hidden()) {
+ OnMountCompleted(MOUNT_ERROR_INTERNAL, source_path, type, "");
+ return;
+ }
+ }
+ CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ dbus_proxy_->Mount(source_path, type, options,
+ // When succeeds, OnMountCompleted will be called by
+ // "MountCompleted" signal instead.
+ base::Bind(&DoNothing),
+ base::Bind(&CrosDisksClientImpl::OnMountCompleted,
+ weak_ptr_factory_.GetWeakPtr(),
+ MOUNT_ERROR_INTERNAL,
+ source_path,
+ type,
+ ""));
+ }
+
+ virtual void UnmountPath(const std::string& mount_path) OVERRIDE {
+ CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ dbus_proxy_->Unmount(mount_path,
+ base::Bind(&CrosDisksClientImpl::OnUnmountPath,
+ weak_ptr_factory_.GetWeakPtr()),
+ base::Bind(&DoNothing));
+ }
+
+ virtual void GetSizeStatsOnFileThread(const std::string& mount_path,
+ size_t* total_size_kb,
+ size_t* remaining_size_kb) OVERRIDE {
+ CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
+
+ uint64_t total_size_uint64 = 0;
+ uint64_t remaining_size_uint64 = 0;
+
+ struct statvfs stat = {}; // Zero-clear
+ if (statvfs(mount_path.c_str(), &stat) == 0) {
+ total_size_uint64 =
+ static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize;
+ remaining_size_uint64 =
+ static_cast<uint64_t>(stat.f_bfree) * stat.f_frsize;
+ }
+ *total_size_kb = static_cast<size_t>(total_size_uint64 / 1024);
+ *remaining_size_kb = static_cast<size_t>(remaining_size_uint64 / 1024);
+ }
+
+ virtual void FormatUnmountedDevice(const std::string& file_path) OVERRIDE {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ for (CrosDisksClient::DiskMap::iterator it = disks_.begin();
+ it != disks_.end(); ++it) {
+ if (it->second->file_path() == file_path &&
+ !it->second->mount_path().empty()) {
+ LOG(ERROR) << "Device is still mounted: " << file_path;
+ OnFormatDevice(file_path, false);
+ return;
+ }
+ }
+ const char kFormatVFAT[] = "vfat";
+ dbus_proxy_->FormatDevice(file_path, kFormatVFAT,
+ base::Bind(&CrosDisksClientImpl::OnFormatDevice,
+ weak_ptr_factory_.GetWeakPtr()),
+ base::Bind(&CrosDisksClientImpl::OnFormatDevice,
+ weak_ptr_factory_.GetWeakPtr(),
+ file_path,
+ false));
+ }
+
+ virtual void FormatMountedDevice(const std::string& mount_path) OVERRIDE {
+ Disk* disk = NULL;
+ for (CrosDisksClient::DiskMap::iterator it = disks_.begin();
+ it != disks_.end(); ++it) {
+ if (it->second->mount_path() == mount_path) {
+ disk = it->second;
+ break;
+ }
+ }
+ if (!disk) {
+ LOG(ERROR) << "Device with this mount path not found: " << mount_path;
+ OnFormatDevice(mount_path, false);
+ return;
+ }
+ if (formatting_pending_.find(disk->device_path()) !=
+ formatting_pending_.end()) {
+ LOG(ERROR) << "Formatting is already pending: " << mount_path;
+ OnFormatDevice(mount_path, false);
+ return;
+ }
+ // Formatting process continues, after unmounting.
+ formatting_pending_[disk->device_path()] = disk->file_path();
+ UnmountPath(disk->mount_path());
+ }
+
+ virtual void UnmountDeviceRecursive(
+ const std::string& device_path,
+ UnmountDeviceRecursiveCallbackType callback,
+ void* user_data) OVERRIDE {
+ bool success = true;
+ std::string error_message;
+ std::vector<std::string> devices_to_unmount;
+
+ // Get list of all devices to unmount.
+ int device_path_len = device_path.length();
+ for (DiskMap::iterator it = disks_.begin(); it != disks_.end(); ++it) {
+ if (!it->second->mount_path().empty() &&
+ strncmp(device_path.c_str(), it->second->device_path().c_str(),
+ device_path_len) == 0) {
+ devices_to_unmount.push_back(it->second->mount_path());
+ }
+ }
+ // We should detect at least original device.
+ if (devices_to_unmount.empty()) {
+ if (disks_.find(device_path) == disks_.end()) {
+ success = false;
+ error_message = kDeviceNotFound;
+ } else {
+ // Nothing to unmount.
+ callback(user_data, true);
+ return;
+ }
+ }
+ if (success) {
+ // We will send the same callback data object to all Unmount calls and use
+ // it to syncronize callbacks.
+ UnmountDeviceRecursiveCallbackData* cb_data =
+ new UnmountDeviceRecursiveCallbackData(user_data, callback,
+ devices_to_unmount.size());
+ for (std::vector<std::string>::iterator it = devices_to_unmount.begin();
+ it != devices_to_unmount.end();
+ ++it) {
+ dbus_proxy_->Unmount(
+ *it,
+ base::Bind(&CrosDisksClientImpl::OnUnmountDeviceRecursive,
+ weak_ptr_factory_.GetWeakPtr(), cb_data, true),
+ base::Bind(&CrosDisksClientImpl::OnUnmountDeviceRecursive,
+ weak_ptr_factory_.GetWeakPtr(), cb_data, false, *it));
+ }
+ } else {
+ LOG(WARNING) << "Unmount recursive request failed for device "
+ << device_path << ", with error: " << error_message;
+ callback(user_data, false);
+ }
+ }
+
+ virtual void RequestMountInfoRefresh() OVERRIDE {
+ CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ dbus_proxy_->EnumerateAutoMountableDevices(
+ base::Bind(&CrosDisksClientImpl::OnRequestMountInfo,
+ weak_ptr_factory_.GetWeakPtr()),
+ base::Bind(&DoNothing));
+ }
+
+ const DiskMap& disks() const OVERRIDE { return disks_; }
+ const MountPointMap& mount_points() const OVERRIDE { return mount_points_; }
+
+ private:
+ struct UnmountDeviceRecursiveCallbackData {
+ void* user_data;
+ UnmountDeviceRecursiveCallbackType callback;
+ size_t pending_callbacks_count;
+
+ UnmountDeviceRecursiveCallbackData(void* ud,
+ UnmountDeviceRecursiveCallbackType cb,
+ int count)
+ : user_data(ud),
+ callback(cb),
+ pending_callbacks_count(count) {
+ }
+ };
+
+ // Callback for UnmountDeviceRecursive.
+ void OnUnmountDeviceRecursive(UnmountDeviceRecursiveCallbackData* cb_data,
+ bool success,
+ const std::string& mount_path) {
+ if (success) {
+ // Do standard processing for Unmount event.
+ OnUnmountPath(mount_path);
+ LOG(INFO) << mount_path << " unmounted.";
+ }
+ // This is safe as long as all callbacks are called on the same thread as
+ // UnmountDeviceRecursive.
+ cb_data->pending_callbacks_count--;
+
+ if (cb_data->pending_callbacks_count == 0) {
+ cb_data->callback(cb_data->user_data, success);
+ delete cb_data;
+ }
+ }
+
+ // Callback to handle MountCompleted signal and Mount method call failure.
+ void OnMountCompleted(MountError error_code,
+ const std::string& source_path,
+ MountType type,
+ const std::string& mount_path) {
+ MountCondition mount_condition = MOUNT_CONDITION_NONE;
+ if (type == MOUNT_TYPE_DEVICE) {
+ if (error_code == MOUNT_ERROR_UNKNOWN_FILESYSTEM)
+ mount_condition = MOUNT_CONDITION_UNKNOWN_FILESYSTEM;
+ if (error_code == MOUNT_ERROR_UNSUPORTED_FILESYSTEM)
+ mount_condition = MOUNT_CONDITION_UNSUPPORTED_FILESYSTEM;
+ }
+ const MountPointInfo mount_info(source_path, mount_path, type,
+ mount_condition);
+
+ FireMountCompleted(MOUNTING, error_code, mount_info);
+
+ // If the device is corrupted but it's still possible to format it, it will
+ // be fake mounted.
+ if ((error_code == MOUNT_ERROR_NONE || mount_info.mount_condition) &&
+ mount_points_.find(mount_info.mount_path) == mount_points_.end()) {
+ mount_points_.insert(MountPointMap::value_type(mount_info.mount_path,
+ mount_info));
+ }
+ if ((error_code == MOUNT_ERROR_NONE || mount_info.mount_condition) &&
+ mount_info.mount_type == MOUNT_TYPE_DEVICE &&
+ !mount_info.source_path.empty() &&
+ !mount_info.mount_path.empty()) {
+ DiskMap::iterator iter = disks_.find(mount_info.source_path);
+ if (iter == disks_.end()) {
+ // disk might have been removed by now?
+ return;
+ }
+ Disk* disk = iter->second;
+ DCHECK(disk);
+ disk->set_mount_path(mount_info.mount_path);
+ FireDiskStatusUpdate(MOUNT_DISK_MOUNTED, disk);
+ }
+ }
+
+ // Callback for UnmountPath.
+ void OnUnmountPath(const std::string& mount_path) {
+ MountPointMap::iterator mount_points_it = mount_points_.find(mount_path);
+ if (mount_points_it == mount_points_.end())
+ return;
+ // TODO(tbarzic): Add separate, PathUnmounted event to Observer.
+ FireMountCompleted(UNMOUNTING,
+ MOUNT_ERROR_NONE,
+ MountPointInfo(mount_points_it->second.source_path,
+ mount_points_it->second.mount_path,
+ mount_points_it->second.mount_type,
+ mount_points_it->second.mount_condition));
+ std::string path(mount_points_it->second.source_path);
+ mount_points_.erase(mount_points_it);
+ DiskMap::iterator iter = disks_.find(path);
+ if (iter == disks_.end()) {
+ // disk might have been removed by now.
+ return;
+ }
+ Disk* disk = iter->second;
+ DCHECK(disk);
+ disk->clear_mount_path();
+ // Check if there is a formatting scheduled
+ PathMap::iterator it = formatting_pending_.find(disk->device_path());
+ if (it != formatting_pending_.end()) {
+ const std::string file_path = it->second;
+ formatting_pending_.erase(it);
+ FormatUnmountedDevice(file_path);
+ }
+ }
+
+ // Callback for FormatDevice.
+ void OnFormatDevice(const std::string& device_path, bool success) {
+ if (success) {
+ FireDeviceStatusUpdate(MOUNT_FORMATTING_STARTED, device_path);
+ } else {
+ FireDeviceStatusUpdate(MOUNT_FORMATTING_STARTED,
+ std::string("!") + device_path);
+ LOG(WARNING) << "Format request failed for device " << device_path;
+ }
+ }
+
+ // Callbcak for GetDeviceProperties.
+ void OnGetDeviceProperties(const DiskInfo& disk_info) {
+ // TODO(zelidrag): Find a better way to filter these out before we
+ // fetch the properties:
+ // Ignore disks coming from the device we booted the system from.
+ if (disk_info.on_boot_device())
+ return;
+
+ LOG(WARNING) << "Found disk " << disk_info.device_path();
+ // Delete previous disk info for this path:
+ bool is_new = true;
+ DiskMap::iterator iter = disks_.find(disk_info.device_path());
+ if (iter != disks_.end()) {
+ delete iter->second;
+ disks_.erase(iter);
+ is_new = false;
+ }
+ Disk* disk = new Disk(disk_info.device_path(),
+ disk_info.mount_path(),
+ disk_info.system_path(),
+ disk_info.file_path(),
+ disk_info.label(),
+ disk_info.drive_label(),
+ disk_info.partition_slave(),
+ FindSystemPathPrefix(disk_info.system_path()),
+ disk_info.device_type(),
+ disk_info.size(),
+ disk_info.is_drive(),
+ disk_info.is_read_only(),
+ disk_info.has_media(),
+ disk_info.on_boot_device(),
+ disk_info.is_hidden());
+ disks_.insert(std::pair<std::string, Disk*>(disk_info.device_path(),
+ disk));
+ FireDiskStatusUpdate(is_new ? MOUNT_DISK_ADDED : MOUNT_DISK_CHANGED, disk);
+ }
+
+ // Callbcak for RequestMountInfo.
+ void OnRequestMountInfo(const std::vector<std::string>& devices) {
+ std::set<std::string> current_device_set;
+ if (!devices.empty()) {
+ // Initiate properties fetch for all removable disks,
+ for (size_t i = 0; i < devices.size(); i++) {
+ current_device_set.insert(devices[i]);
+ // Initiate disk property retrieval for each relevant device path.
+ dbus_proxy_->GetDeviceProperties(
+ devices[i],
+ base::Bind(&CrosDisksClientImpl::OnGetDeviceProperties,
+ weak_ptr_factory_.GetWeakPtr()),
+ base::Bind(&DoNothing));
+ }
+ }
+ // Search and remove disks that are no longer present.
+ for (DiskMap::iterator iter = disks_.begin(); iter != disks_.end(); ) {
+ if (current_device_set.find(iter->first) == current_device_set.end()) {
+ Disk* disk = iter->second;
+ FireDiskStatusUpdate(MOUNT_DISK_REMOVED, disk);
+ delete iter->second;
+ disks_.erase(iter++);
+ } else {
+ ++iter;
+ }
+ }
+ }
+
+ // Callback to handle mount event signals.
+ void OnMountEvent(MountEventType evt, std::string device_path) {
+ CrosDisksClientEventType type = MOUNT_DEVICE_ADDED;
+ switch (evt) {
+ case DISK_ADDED: {
+ dbus_proxy_->GetDeviceProperties(
+ device_path,
+ base::Bind(&CrosDisksClientImpl::OnGetDeviceProperties,
+ weak_ptr_factory_.GetWeakPtr()),
+ base::Bind(&DoNothing));
+ return;
+ }
+ case DISK_REMOVED: {
+ // Search and remove disks that are no longer present.
+ CrosDisksClient::DiskMap::iterator iter = disks_.find(device_path);
+ if (iter != disks_.end()) {
+ Disk* disk = iter->second;
+ FireDiskStatusUpdate(MOUNT_DISK_REMOVED, disk);
+ delete iter->second;
+ disks_.erase(iter);
+ }
+ return;
+ }
+ case DEVICE_ADDED: {
+ type = MOUNT_DEVICE_ADDED;
+ system_path_prefixes_.insert(device_path);
+ break;
+ }
+ case DEVICE_REMOVED: {
+ type = MOUNT_DEVICE_REMOVED;
+ system_path_prefixes_.erase(device_path);
+ break;
+ }
+ case DEVICE_SCANNED: {
+ type = MOUNT_DEVICE_SCANNED;
+ break;
+ }
+ case FORMATTING_FINISHED: {
+ // FORMATTING_FINISHED actually returns file path instead of device
+ // path.
+ device_path = FilePathToDevicePath(device_path);
+ if (device_path.empty()) {
+ LOG(ERROR) << "Error while handling disks metadata. Cannot find "
+ << "device that is being formatted.";
+ return;
+ }
+ type = MOUNT_FORMATTING_FINISHED;
+ break;
+ }
+ default: {
+ return;
+ }
+ }
+ FireDeviceStatusUpdate(type, device_path);
+ }
+
+ // Notifies all observers about disk status update.
+ void FireDiskStatusUpdate(CrosDisksClientEventType evt, const Disk* disk) {
+ // Make sure we run on UI thread.
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ FOR_EACH_OBSERVER(Observer, observers_, DiskChanged(evt, disk));
+ }
+
+ // Notifies all observers about device status update.
+ void FireDeviceStatusUpdate(CrosDisksClientEventType evt,
+ const std::string& device_path) {
+ // Make sure we run on UI thread.
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ FOR_EACH_OBSERVER(Observer, observers_, DeviceChanged(evt, device_path));
+ }
+
+ // Notifies all observers about mount completion.
+ void FireMountCompleted(MountEvent event_type,
+ MountError error_code,
+ const MountPointInfo& mount_info) {
+ // Make sure we run on UI thread.
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ FOR_EACH_OBSERVER(Observer, observers_,
+ MountCompleted(event_type, error_code, mount_info));
+ }
+
+ // Converts file path to device path.
+ std::string FilePathToDevicePath(const std::string& file_path) {
+ int failed = (file_path[0] == '!') ? 1 : 0;
+ for (CrosDisksClient::DiskMap::iterator it = disks_.begin();
+ it != disks_.end(); ++it) {
+ if (it->second->file_path().compare(file_path.c_str() + failed) == 0) {
+ if (failed)
+ return std::string("!") + it->second->device_path();
+ else
+ return it->second->device_path();
+ }
+ }
+ return EmptyString();
+ }
+
+ // Finds system path prefix from |system_path|
+ const std::string& FindSystemPathPrefix(const std::string& system_path) {
+ if (system_path.empty())
+ return EmptyString();
+ for (SystemPathPrefixSet::const_iterator it = system_path_prefixes_.begin();
+ it != system_path_prefixes_.end();
+ ++it) {
+ if (system_path.find(*it, 0) == 0)
+ return *it;
+ }
+ return EmptyString();
+ }
+
+ // A function to be used as an empty callback
+ static void DoNothing() {
+ }
+
+ // Mount event change observers.
+ ObserverList<Observer> observers_;
+
+ scoped_ptr<CrosDisksDBusProxy> dbus_proxy_;
+
+ // The list of disks found.
+ CrosDisksClient::DiskMap disks_;
+
+ CrosDisksClient::MountPointMap mount_points_;
+
+ typedef std::set<std::string> SystemPathPrefixSet;
+ SystemPathPrefixSet system_path_prefixes_;
+
+ // Set of devices that are supposed to be formated, but are currently waiting
+ // to be unmounted. When device is in this map, the formatting process HAVEN'T
+ // started yet.
+ PathMap formatting_pending_;
+
+ base::WeakPtrFactory<CrosDisksClientImpl> weak_ptr_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(CrosDisksClientImpl);
+};
+
+// A stub implementaion of CrosDisksClient
+class CrosDisksClientStubImpl : public CrosDisksClient {
+ public:
+ CrosDisksClientStubImpl() {}
+ virtual ~CrosDisksClientStubImpl() {}
+
+ // CrosDisksClient overrides.
+ virtual void AddObserver(Observer* observer) OVERRIDE {}
+ virtual void RemoveObserver(Observer* observer) OVERRIDE {}
+ virtual const DiskMap& disks() const OVERRIDE { return disks_; }
+ virtual const MountPointMap& mount_points() const OVERRIDE {
+ return mount_points_;
+ }
+ virtual void RequestMountInfoRefresh() OVERRIDE {}
+ virtual void MountPath(const std::string& source_path,
+ MountType type,
+ const MountPathOptions& options) OVERRIDE {}
+ virtual void UnmountPath(const std::string& mount_path) OVERRIDE {}
+ virtual void GetSizeStatsOnFileThread(const std::string& mount_path,
+ size_t* total_size_kb,
+ size_t* remaining_size_kb) OVERRIDE {}
+ virtual void FormatUnmountedDevice(const std::string& device_path) OVERRIDE {}
+ virtual void FormatMountedDevice(const std::string& mount_path) OVERRIDE {}
+ virtual void UnmountDeviceRecursive(
+ const std::string& device_path,
+ UnmountDeviceRecursiveCallbackType callback,
+ void* user_data) OVERRIDE {}
+ private:
+ DiskMap disks_; // The list of disks found.
+ MountPointMap mount_points_;
+
+ DISALLOW_COPY_AND_ASSIGN(CrosDisksClientStubImpl);
+};
+
+} // namespace
+
+// static
+std::string CrosDisksClient::MountTypeToString(MountType type) {
+ switch (type) {
+ case MOUNT_TYPE_DEVICE:
+ return "device";
+ case MOUNT_TYPE_ARCHIVE:
+ return "file";
+ case MOUNT_TYPE_NETWORK_STORAGE:
+ return "network";
+ case MOUNT_TYPE_INVALID:
+ return "invalid";
+ default:
+ NOTREACHED();
+ }
+ return EmptyString();
+}
+
+// static
+std::string CrosDisksClient::MountConditionToString(MountCondition condition) {
+ switch (condition) {
+ case MOUNT_CONDITION_NONE:
+ return EmptyString();
+ case MOUNT_CONDITION_UNKNOWN_FILESYSTEM:
+ return "unknown_filesystem";
+ case MOUNT_CONDITION_UNSUPPORTED_FILESYSTEM:
+ return "unsupported_filesystem";
+ default:
+ NOTREACHED();
+ }
+ return EmptyString();
+}
+
+// static
+MountType CrosDisksClient::MountTypeFromString(const std::string& type_str) {
+ if (type_str == "device")
+ return MOUNT_TYPE_DEVICE;
+ else if (type_str == "network")
+ return MOUNT_TYPE_NETWORK_STORAGE;
+ else if (type_str == "file")
+ return MOUNT_TYPE_ARCHIVE;
+ else
+ return MOUNT_TYPE_INVALID;
+}
+
+CrosDisksClient::Disk::Disk(const std::string& device_path,
+ const std::string& mount_path,
+ const std::string& system_path,
+ const std::string& file_path,
+ const std::string& device_label,
+ const std::string& drive_label,
+ const std::string& parent_path,
+ const std::string& system_path_prefix,
+ DeviceType device_type,
+ uint64 total_size,
+ bool is_parent,
+ bool is_read_only,
+ bool has_media,
+ bool on_boot_device,
+ bool is_hidden)
+ : device_path_(device_path),
+ mount_path_(mount_path),
+ system_path_(system_path),
+ file_path_(file_path),
+ device_label_(device_label),
+ drive_label_(drive_label),
+ parent_path_(parent_path),
+ system_path_prefix_(system_path_prefix),
+ device_type_(device_type),
+ total_size_(total_size),
+ is_parent_(is_parent),
+ is_read_only_(is_read_only),
+ has_media_(has_media),
+ on_boot_device_(on_boot_device),
+ is_hidden_(is_hidden) {
+}
+
+CrosDisksClient::Disk::~Disk() {}
+
+// static
+CrosDisksClient* CrosDisksClient::Create(dbus::Bus* bus) {
+ CrosDisksClient* impl;
+ if (system::runtime_environment::IsRunningOnChromeOS())
+ impl = new CrosDisksClientImpl(bus);
+ else
+ impl = new CrosDisksClientStubImpl();
+ return impl;
+}
+
+} // namespace chromeos
« no previous file with comments | « chrome/browser/chromeos/dbus/cros_disks_client.h ('k') | chrome/browser/chromeos/dbus/dbus_thread_manager.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698