| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 
 | // Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/storage_monitor/storage_monitor_mac.h"
#include <stdint.h>
#include <memory>
#include "base/apple/foundation_util.h"
#include "base/functional/bind.h"
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "components/storage_monitor/image_capture_device_manager.h"
#include "components/storage_monitor/media_storage_util.h"
#include "components/storage_monitor/storage_info.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
namespace storage_monitor {
namespace {
const char16_t kDiskImageModelName[] = u"Disk Image";
std::u16string GetUTF16FromDictionary(CFDictionaryRef dictionary,
                                      CFStringRef key) {
  CFStringRef value =
      base::apple::GetValueFromDictionary<CFStringRef>(dictionary, key);
  if (!value)
    return std::u16string();
  return base::SysCFStringRefToUTF16(value);
}
std::u16string JoinName(const std::u16string& name,
                        const std::u16string& addition) {
  if (addition.empty())
    return name;
  if (name.empty())
    return addition;
  return name + u' ' + addition;
}
StorageInfo::Type GetDeviceType(bool is_removable, bool has_dcim) {
  if (!is_removable)
    return StorageInfo::FIXED_MASS_STORAGE;
  if (has_dcim)
    return StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM;
  return StorageInfo::REMOVABLE_MASS_STORAGE_NO_DCIM;
}
StorageInfo BuildStorageInfo(
    base::apple::ScopedCFTypeRef<CFDictionaryRef> scoped_dict,
    std::string* bsd_name) {
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);
  CFDictionaryRef dict = scoped_dict.get();
  CFStringRef device_bsd_name =
      base::apple::GetValueFromDictionary<CFStringRef>(
          dict, kDADiskDescriptionMediaBSDNameKey);
  if (device_bsd_name && bsd_name)
    *bsd_name = base::SysCFStringRefToUTF8(device_bsd_name);
  CFURLRef url = base::apple::GetValueFromDictionary<CFURLRef>(
      dict, kDADiskDescriptionVolumePathKey);
  base::FilePath location = base::apple::CFURLToFilePath(url);
  CFNumberRef size_number = base::apple::GetValueFromDictionary<CFNumberRef>(
      dict, kDADiskDescriptionMediaSizeKey);
  uint64_t size_in_bytes = 0;
  if (size_number)
    CFNumberGetValue(size_number, kCFNumberLongLongType, &size_in_bytes);
  std::u16string vendor =
      GetUTF16FromDictionary(dict, kDADiskDescriptionDeviceVendorKey);
  std::u16string model =
      GetUTF16FromDictionary(dict, kDADiskDescriptionDeviceModelKey);
  std::u16string label =
      GetUTF16FromDictionary(dict, kDADiskDescriptionVolumeNameKey);
  CFUUIDRef uuid = base::apple::GetValueFromDictionary<CFUUIDRef>(
      dict, kDADiskDescriptionVolumeUUIDKey);
  std::string unique_id;
  if (uuid) {
    base::apple::ScopedCFTypeRef<CFStringRef> uuid_string(
        CFUUIDCreateString(nullptr, uuid));
    if (uuid_string.get())
      unique_id = base::SysCFStringRefToUTF8(uuid_string.get());
  }
  if (unique_id.empty()) {
    std::u16string revision =
        GetUTF16FromDictionary(dict, kDADiskDescriptionDeviceRevisionKey);
    std::u16string unique_id2 = vendor;
    unique_id2 = JoinName(unique_id2, model);
    unique_id2 = JoinName(unique_id2, revision);
    unique_id = base::UTF16ToUTF8(unique_id2);
  }
  CFBooleanRef is_removable_ref =
      base::apple::GetValueFromDictionary<CFBooleanRef>(
          dict, kDADiskDescriptionMediaRemovableKey);
  bool is_removable = is_removable_ref && CFBooleanGetValue(is_removable_ref);
  // Checking for DCIM only matters on removable devices.
  bool has_dcim = is_removable && MediaStorageUtil::HasDcim(location);
  StorageInfo::Type device_type = GetDeviceType(is_removable, has_dcim);
  std::string device_id;
  if (!unique_id.empty())
    device_id = StorageInfo::MakeDeviceId(device_type, unique_id);
  return StorageInfo(device_id, location.value(), label, vendor, model,
                     size_in_bytes);
}
struct EjectDiskOptions {
  std::string bsd_name;
  base::OnceCallback<void(StorageMonitor::EjectStatus)> callback;
  base::apple::ScopedCFTypeRef<DADiskRef> disk;
};
void PostEjectCallback(DADiskRef disk,
                       DADissenterRef dissenter,
                       void* context) {
  std::unique_ptr<EjectDiskOptions> options_deleter(
      static_cast<EjectDiskOptions*>(context));
  if (dissenter) {
    std::move(options_deleter->callback).Run(StorageMonitor::EJECT_IN_USE);
    return;
  }
  std::move(options_deleter->callback).Run(StorageMonitor::EJECT_OK);
}
void PostUnmountCallback(DADiskRef disk,
                         DADissenterRef dissenter,
                         void* context) {
  std::unique_ptr<EjectDiskOptions> options_deleter(
      static_cast<EjectDiskOptions*>(context));
  if (dissenter) {
    std::move(options_deleter->callback).Run(StorageMonitor::EJECT_IN_USE);
    return;
  }
  DADiskEject(options_deleter->disk.get(), kDADiskEjectOptionDefault,
              PostEjectCallback, options_deleter.release());
}
void EjectDisk(EjectDiskOptions* options) {
  DADiskUnmount(options->disk.get(), kDADiskUnmountOptionWhole,
                PostUnmountCallback, options);
}
}  // namespace
StorageMonitorMac::StorageMonitorMac() = default;
StorageMonitorMac::~StorageMonitorMac() {
  if (session_.get()) {
    DASessionUnscheduleFromRunLoop(session_.get(), CFRunLoopGetCurrent(),
                                   kCFRunLoopCommonModes);
  }
}
void StorageMonitorMac::Init() {
  session_.reset(DASessionCreate(nullptr));
  // Register for callbacks for attached, changed, and removed devices.
  // This will send notifications for existing devices too.
  DARegisterDiskAppearedCallback(session_.get(),
                                 kDADiskDescriptionMatchVolumeMountable,
                                 DiskAppearedCallback, this);
  DARegisterDiskDisappearedCallback(session_.get(),
                                    kDADiskDescriptionMatchVolumeMountable,
                                    DiskDisappearedCallback, this);
  DARegisterDiskDescriptionChangedCallback(
      session_.get(), kDADiskDescriptionMatchVolumeMountable,
      kDADiskDescriptionWatchVolumePath, DiskDescriptionChangedCallback, this);
  DASessionScheduleWithRunLoop(session_.get(), CFRunLoopGetCurrent(),
                               kCFRunLoopCommonModes);
  image_capture_device_manager_ = std::make_unique<ImageCaptureDeviceManager>();
  image_capture_device_manager_->SetNotifications(receiver());
}
void StorageMonitorMac::UpdateDisk(UpdateType update_type,
                                   std::string* bsd_name,
                                   const StorageInfo& info) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(bsd_name);
  pending_disk_updates_--;
  bool initialization_complete = false;
  if (!IsInitialized() && pending_disk_updates_ == 0)
    initialization_complete = true;
  if (info.device_id().empty() || bsd_name->empty()) {
    if (initialization_complete)
      MarkInitialized();
    return;
  }
  std::map<std::string, StorageInfo>::iterator it =
      disk_info_map_.find(*bsd_name);
  if (it != disk_info_map_.end()) {
    // If an attached notification was previously posted then post a detached
    // notification now. This is used for devices that are being removed or
    // devices that have changed.
    if (ShouldPostNotificationForDisk(it->second)) {
      receiver()->ProcessDetach(it->second.device_id());
    }
  }
  if (update_type == UPDATE_DEVICE_REMOVED) {
    if (it != disk_info_map_.end())
      disk_info_map_.erase(it);
  } else {
    disk_info_map_[*bsd_name] = info;
    if (ShouldPostNotificationForDisk(info))
      receiver()->ProcessAttach(info);
  }
  // We're not really honestly sure we're done, but this looks the best we
  // can do. Any misses should go out through notifications.
  if (initialization_complete)
    MarkInitialized();
}
bool StorageMonitorMac::GetStorageInfoForPath(const base::FilePath& path,
                                              StorageInfo* device_info) const {
  DCHECK(device_info);
  if (!path.IsAbsolute())
    return false;
  base::FilePath current = path;
  const base::FilePath root(base::FilePath::kSeparators);
  while (current != root) {
    StorageInfo info;
    if (FindDiskWithMountPoint(current, &info)) {
      *device_info = info;
      return true;
    }
    current = current.DirName();
  }
  return false;
}
void StorageMonitorMac::EjectDevice(
    const std::string& device_id,
    base::OnceCallback<void(EjectStatus)> callback) {
  StorageInfo::Type type;
  std::string uuid;
  if (!StorageInfo::CrackDeviceId(device_id, &type, &uuid)) {
    std::move(callback).Run(EJECT_FAILURE);
    return;
  }
  if (type == StorageInfo::MAC_IMAGE_CAPTURE &&
      image_capture_device_manager_.get()) {
    image_capture_device_manager_->EjectDevice(uuid, std::move(callback));
    return;
  }
  std::string bsd_name;
  for (std::map<std::string, StorageInfo>::iterator
      it = disk_info_map_.begin(); it != disk_info_map_.end(); ++it) {
    if (it->second.device_id() == device_id) {
      bsd_name = it->first;
      disk_info_map_.erase(it);
      break;
    }
  }
  if (bsd_name.empty()) {
    std::move(callback).Run(EJECT_NO_SUCH_DEVICE);
    return;
  }
  receiver()->ProcessDetach(device_id);
  base::apple::ScopedCFTypeRef<DADiskRef> disk(
      DADiskCreateFromBSDName(nullptr, session_.get(), bsd_name.c_str()));
  if (!disk.get()) {
    std::move(callback).Run(StorageMonitor::EJECT_FAILURE);
    return;
  }
  // Get the reference to the full disk for ejecting.
  disk.reset(DADiskCopyWholeDisk(disk.get()));
  if (!disk.get()) {
    std::move(callback).Run(StorageMonitor::EJECT_FAILURE);
    return;
  }
  EjectDiskOptions* options = new EjectDiskOptions;
  options->bsd_name = bsd_name;
  options->callback = std::move(callback);
  options->disk = std::move(disk);
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(EjectDisk, options));
}
// static
void StorageMonitorMac::DiskAppearedCallback(DADiskRef disk, void* context) {
  StorageMonitorMac* monitor = static_cast<StorageMonitorMac*>(context);
  monitor->GetDiskInfoAndUpdate(disk, UPDATE_DEVICE_ADDED);
}
// static
void StorageMonitorMac::DiskDisappearedCallback(DADiskRef disk, void* context) {
  StorageMonitorMac* monitor = static_cast<StorageMonitorMac*>(context);
  monitor->GetDiskInfoAndUpdate(disk, UPDATE_DEVICE_REMOVED);
}
// static
void StorageMonitorMac::DiskDescriptionChangedCallback(DADiskRef disk,
                                                       CFArrayRef keys,
                                                       void *context) {
  StorageMonitorMac* monitor = static_cast<StorageMonitorMac*>(context);
  monitor->GetDiskInfoAndUpdate(disk, UPDATE_DEVICE_CHANGED);
}
void StorageMonitorMac::GetDiskInfoAndUpdate(
    DADiskRef disk,
    StorageMonitorMac::UpdateType update_type) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  pending_disk_updates_++;
  base::apple::ScopedCFTypeRef<CFDictionaryRef> dict(
      DADiskCopyDescription(disk));
  std::string* bsd_name = new std::string;
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
      base::BindOnce(&BuildStorageInfo, dict, bsd_name),
      base::BindOnce(&StorageMonitorMac::UpdateDisk,
                     weak_ptr_factory_.GetWeakPtr(), update_type,
                     base::Owned(bsd_name)));
}
bool StorageMonitorMac::ShouldPostNotificationForDisk(
    const StorageInfo& info) const {
  // Only post notifications about disks that have no empty fields and
  // are removable. Also exclude disk images (DMGs).
  return !info.device_id().empty() && !info.location().empty() &&
         info.model_name() != kDiskImageModelName &&
         StorageInfo::IsMassStorageDevice(info.device_id());
}
bool StorageMonitorMac::FindDiskWithMountPoint(
    const base::FilePath& mount_point,
    StorageInfo* info) const {
  for (const auto& disk_info : disk_info_map_) {
    if (disk_info.second.location() == mount_point.value()) {
      *info = disk_info.second;
      return true;
    }
  }
  return false;
}
StorageMonitor* StorageMonitor::CreateInternal() {
  return new StorageMonitorMac();
}
}  // namespace storage_monitor
 |