summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/cros/mount_library.cc
blob: df0b2c0c807d7704e44a25102825f924b6d7c183 (plain)
1
2
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
// 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/cros/mount_library.h"

#include <set>

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "content/browser/browser_thread.h"

const char* kLibraryNotLoaded = "Cros Library not loaded";
const char* kDeviceNotFound = "Device could not be found";

namespace chromeos {

// static
std::string MountLibrary::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 "";
}

// static
MountType MountLibrary::MountTypeFromString(
    const std::string& type_str)
    OVERRIDE {
  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;
  }
}

MountLibrary::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,
     DeviceType device_type,
     uint64 total_size,
     bool is_parent,
     bool is_read_only,
     bool has_media,
     bool on_boot_device)
    : 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),
      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) {
  // Add trailing slash to mount path.
  if (mount_path_.length() && mount_path_.at(mount_path_.length() -1) != '/')
    mount_path_ = mount_path_.append("/");
}

MountLibrary::Disk::~Disk() {}

class MountLibraryImpl : public MountLibrary {

  struct UnmountDeviceRecursiveCallbackData {
    MountLibraryImpl* const object;
    void* user_data;
    UnmountDeviceRecursiveCallbackType callback;
    size_t pending_callbacks_count;
    bool success;

    UnmountDeviceRecursiveCallbackData(MountLibraryImpl* const o, void* ud,
        UnmountDeviceRecursiveCallbackType cb, int count)
         : object(o),
          user_data(ud),
          callback(cb),
          pending_callbacks_count(count),
          success(true) {
    }
  };

 public:
  MountLibraryImpl() : mount_status_connection_(NULL) {
    if (CrosLibrary::Get()->EnsureLoaded())
      Init();
    else
      LOG(ERROR) << kLibraryNotLoaded;
  }

  virtual ~MountLibraryImpl() {
    if (mount_status_connection_)
      DisconnectMountEventMonitor(mount_status_connection_);
  }

  // MountLibrary overrides.
  virtual void AddObserver(Observer* observer) OVERRIDE {
    observers_.AddObserver(observer);
  }

  virtual void RemoveObserver(Observer* observer) OVERRIDE {
    observers_.RemoveObserver(observer);
  }

  virtual void MountPath(const char* source_path,
                         MountType type,
                         const MountPathOptions& options) OVERRIDE {
    CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!CrosLibrary::Get()->EnsureLoaded()) {
      OnMountCompleted(MOUNT_ERROR_LIBRARY_NOT_LOADED,
                       MountPointInfo(source_path, NULL, type));
      return;
    }
    MountSourcePath(source_path, type, options, &MountCompletedHandler, this);
  }

  virtual void UnmountPath(const char* path) OVERRIDE {
    CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!CrosLibrary::Get()->EnsureLoaded()) {
      OnUnmountPath(path,
                    MOUNT_METHOD_ERROR_LOCAL,
                    kLibraryNotLoaded);
      return;
    }
    UnmountMountPoint(path, &MountLibraryImpl::UnmountMountPointCallback, this);
  }

  virtual void UnmountDeviceRecursive(const char* device_path,
      UnmountDeviceRecursiveCallbackType callback, void* user_data)
      OVERRIDE {
    bool success = true;
    const char* error_message = NULL;
    std::vector<const char*> devices_to_unmount;

    if (!CrosLibrary::Get()->EnsureLoaded()) {
      success = false;
      error_message = kLibraryNotLoaded;
    } else {
      // Get list of all devices to unmount.
      int device_path_len = strlen(device_path);
      for (DiskMap::iterator it = disks_.begin(); it != disks_.end(); ++it) {
        if (strncmp(device_path, it->second->device_path().c_str(),
            device_path_len) == 0) {
          devices_to_unmount.push_back(it->second->device_path().c_str());
        }
      }

      // We should detect at least original device.
      if (devices_to_unmount.size() == 0) {
        success = false;
        error_message = kDeviceNotFound;
      }
    }

    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(this, user_data,
          callback, devices_to_unmount.size());
      for (std::vector<const char*>::iterator it = devices_to_unmount.begin();
           it != devices_to_unmount.end();
           ++it) {
        UnmountMountPoint(
            *it,
            &MountLibraryImpl::UnmountDeviceRecursiveCallback,
            cb_data);
      }
    } 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));
    if (!CrosLibrary::Get()->EnsureLoaded()) {
      OnRequestMountInfo(NULL,
                         0,
                         MOUNT_METHOD_ERROR_LOCAL,
                         kLibraryNotLoaded);
      return;
    }
    RequestMountInfo(&MountLibraryImpl::RequestMountInfoCallback,
                     this);
  }

  const DiskMap& disks() const OVERRIDE { return disks_; }
  const MountPointMap& mount_points() const OVERRIDE { return mount_points_; }

 private:
  // Callback for MountComplete signal and MountSourcePath method.
  static void MountCompletedHandler(void* object,
                                    MountError error_code,
                                    const char* source_path,
                                    MountType type,
                                    const char* mount_path) {
    DCHECK(object);
    MountLibraryImpl* self = static_cast<MountLibraryImpl*>(object);
    self->OnMountCompleted(static_cast<MountError>(error_code),
                           MountPointInfo(source_path, mount_path, type));
  }

  // Callback for UnmountRemovableDevice method.
  static void UnmountMountPointCallback(void* object,
                                        const char* device_path,
                                        MountMethodErrorType error,
                                        const char* error_message) {
    DCHECK(object);
    MountLibraryImpl* self = static_cast<MountLibraryImpl*>(object);
    self->OnUnmountPath(device_path, error, error_message);
  }

  // Callback for UnmountDeviceRecursive.
  static void UnmountDeviceRecursiveCallback(void* object,
                                             const char* device_path,
                                             MountMethodErrorType error,
                                             const char* error_message) {
    DCHECK(object);
    UnmountDeviceRecursiveCallbackData* cb_data =
        static_cast<UnmountDeviceRecursiveCallbackData*>(object);

    // Do standard processing for Unmount event.
    cb_data->object->OnUnmountPath(device_path,
                                   error,
                                   error_message);
    if (error == MOUNT_METHOD_ERROR_LOCAL) {
      cb_data->success = false;
    } else if (error == MOUNT_METHOD_ERROR_NONE) {
      LOG(WARNING) << device_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, cb_data->success);
      delete cb_data;
    }
  }

  // Callback for disk information retrieval calls.
  static void GetDiskPropertiesCallback(void* object,
                                        const char* device_path,
                                        const DiskInfo* disk,
                                        MountMethodErrorType error,
                                        const char* error_message) {
    DCHECK(object);
    MountLibraryImpl* self = static_cast<MountLibraryImpl*>(object);
    self->OnGetDiskProperties(device_path,
                              disk,
                              error,
                              error_message);
  }

  // Callback for RequestMountInfo call.
  static void RequestMountInfoCallback(void* object,
                                       const char** devices,
                                       size_t device_len,
                                       MountMethodErrorType error,
                                       const char* error_message) {
    DCHECK(object);
    MountLibraryImpl* self = static_cast<MountLibraryImpl*>(object);
    self->OnRequestMountInfo(devices,
                             device_len,
                             error,
                             error_message);
  }

  // This method will receive events that are caused by drive status changes.
  static void MonitorMountEventsHandler(void* object,
                                        MountEventType evt,
                                        const char* device_path) {
    DCHECK(object);
    MountLibraryImpl* self = static_cast<MountLibraryImpl*>(object);
    self->OnMountEvent(evt, device_path);
  }


  void OnMountCompleted(MountError error_code,
                        const MountPointInfo& mount_info) {
    DCHECK(!mount_info.source_path.empty());

    FireMountCompleted(MOUNTING,
                       error_code,
                       mount_info);

    if (error_code == MOUNT_ERROR_NONE &&
        mount_points_.find(mount_info.source_path) == mount_points_.end()) {
      mount_points_.insert(MountPointMap::value_type(
                               mount_info.source_path.c_str(),
                               mount_info));
    }

    if (error_code == MOUNT_ERROR_NONE &&
        mount_info.mount_type == MOUNT_TYPE_DEVICE &&
        !mount_info.source_path.empty() &&
        !mount_info.mount_path.empty()) {
      std::string path(mount_info.source_path);
      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->set_mount_path(mount_info.mount_path.c_str());
      FireDiskStatusUpdate(MOUNT_DISK_MOUNTED, disk);
    }
  }

  void OnUnmountPath(const char* source_path,
                     MountMethodErrorType error,
                     const char* error_message) {
    DCHECK(source_path);

    if (error == MOUNT_METHOD_ERROR_NONE && source_path) {
      MountPointMap::iterator mount_points_it = mount_points_.find(source_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.c_str(),
                         mount_points_it->second.mount_path.c_str(),
                         mount_points_it->second.mount_type));
      mount_points_.erase(mount_points_it);

      std::string path(source_path);
      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();
      FireDiskStatusUpdate(MOUNT_DISK_UNMOUNTED, disk);
    } else {
      LOG(WARNING) << "Unmount request failed for device "
                   << source_path << ", with error: "
                   << (error_message ? error_message : "Unknown");
    }
  }

  void OnGetDiskProperties(const char* device_path,
                           const DiskInfo* disk1,
                           MountMethodErrorType error,
                           const char* error_message) {
    DCHECK(device_path);
    if (error == MOUNT_METHOD_ERROR_NONE && device_path) {
      // 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.

      // This cast is temporal solution, until we merge DiskInfo and
      // DiskInfoAdvanced into single interface.
      const DiskInfoAdvanced* disk =
          reinterpret_cast<const DiskInfoAdvanced*>(disk1);
      if (disk->on_boot_device())
        return;

      LOG(WARNING) << "Found disk " << device_path;
      // Delete previous disk info for this path:
      bool is_new = true;
      std::string device_path_string(device_path);
      DiskMap::iterator iter = disks_.find(device_path_string);
      if (iter != disks_.end()) {
        delete iter->second;
        disks_.erase(iter);
        is_new = false;
      }
      std::string path;
      std::string mountpath;
      std::string systempath;
      std::string filepath;
      std::string devicelabel;
      std::string drivelabel;
      std::string parentpath;

      if (disk->path() != NULL)
        path = disk->path();

      if (disk->mount_path() != NULL)
        mountpath = disk->mount_path();

      if (disk->system_path() != NULL)
        systempath = disk->system_path();

      if (disk->file_path() != NULL)
        filepath = disk->file_path();

      if (disk->label() != NULL)
        devicelabel = disk->label();

      if (disk->drive_label() != NULL)
        drivelabel = disk->drive_label();

      if (disk->partition_slave() != NULL)
        parentpath = disk->partition_slave();

      Disk* new_disk = new Disk(path,
                                mountpath,
                                systempath,
                                filepath,
                                devicelabel,
                                drivelabel,
                                parentpath,
                                disk->device_type(),
                                disk->size(),
                                disk->is_drive(),
                                disk->is_read_only(),
                                disk->has_media(),
                                disk->on_boot_device());
      disks_.insert(
          std::pair<std::string, Disk*>(device_path_string, new_disk));
      FireDiskStatusUpdate(is_new ? MOUNT_DISK_ADDED : MOUNT_DISK_CHANGED,
                           new_disk);
    } else {
      LOG(WARNING) << "Property retrieval request failed for device "
                   << device_path << ", with error: "
                   << (error_message ? error_message : "Unknown");
    }
  }

  void OnRequestMountInfo(const char** devices,
                          size_t devices_len,
                          MountMethodErrorType error,
                          const char* error_message) {
    std::set<std::string> current_device_set;
    if (error == MOUNT_METHOD_ERROR_NONE && devices && devices_len) {
      // Initiate properties fetch for all removable disks,
      bool found_disk = false;
      for (size_t i = 0; i < devices_len; i++) {
        if (!devices[i]) {
          NOTREACHED();
          continue;
        }
        current_device_set.insert(std::string(devices[i]));
        found_disk = true;
        // Initiate disk property retrieval for each relevant device path.
        GetDiskProperties(devices[i],
                          &MountLibraryImpl::GetDiskPropertiesCallback,
                          this);
      }
    } else if (error != MOUNT_METHOD_ERROR_NONE) {
      LOG(WARNING) << "Request mount info retrieval request failed with error: "
                   << (error_message ? error_message : "Unknown");
    }
    // Search and remove disks that are no longer present.
    for (MountLibrary::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;
      }
    }
  }

  void OnMountEvent(MountEventType evt,
                    const char* device_path) {
    if (!device_path)
      return;
    MountLibraryEventType type = MOUNT_DEVICE_ADDED;
    switch (evt) {
      case DISK_ADDED:
      case DISK_CHANGED: {
        GetDiskProperties(device_path,
                          &MountLibraryImpl::GetDiskPropertiesCallback,
                          this);
        return;
      }
      case DISK_REMOVED: {
        // Search and remove disks that are no longer present.
        MountLibrary::DiskMap::iterator iter =
            disks_.find(std::string(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;
        break;
      }
      case DEVICE_REMOVED: {
        type = MOUNT_DEVICE_REMOVED;
        break;
      }
      case DEVICE_SCANNED: {
        type = MOUNT_DEVICE_SCANNED;
        break;
      }
      default: {
        return;
      }
    }
    FireDeviceStatusUpdate(type, std::string(device_path));
  }

  void Init() {
    // Getting the monitor status so that the daemon starts up.
    mount_status_connection_ = MonitorAllMountEvents(
        &MonitorMountEventsHandler, &MountCompletedHandler, this);
  }

  void FireDiskStatusUpdate(MountLibraryEventType evt,
                            const Disk* disk) {
    // Make sure we run on UI thread.
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    FOR_EACH_OBSERVER(
        Observer, observers_, DiskChanged(evt, disk));
  }

  void FireDeviceStatusUpdate(MountLibraryEventType 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));
  }

  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));
  }

  // Mount event change observers.
  ObserverList<Observer> observers_;

  // A reference to the  mount api, to allow callbacks when the mount
  // status changes.
  MountEventConnection mount_status_connection_;

  // The list of disks found.
  MountLibrary::DiskMap disks_;

  MountLibrary::MountPointMap mount_points_;

  DISALLOW_COPY_AND_ASSIGN(MountLibraryImpl);
};

class MountLibraryStubImpl : public MountLibrary {
 public:
  MountLibraryStubImpl() {}
  virtual ~MountLibraryStubImpl() {}

  // MountLibrary 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 std::string MountTypeToString(MountType type) const OVERRIDE {
    return "";
  }
  virtual MountType MountTypeFromString(const std::string& type_str) const
      OVERRIDE {
    return MOUNT_TYPE_INVALID;
  }
  virtual void RequestMountInfoRefresh() OVERRIDE {}
  virtual void MountPath(const char* source_path, MountType type,
                         const MountPathOptions& options) OVERRIDE {}
  virtual void UnmountPath(const char* path) OVERRIDE {}
  virtual void UnmountDeviceRecursive(const char* device_path,
      UnmountDeviceRecursiveCallbackType callback, void* user_data)
      OVERRIDE {}

 private:
  // The list of disks found.
  DiskMap disks_;
  MountPointMap mount_points_;

  DISALLOW_COPY_AND_ASSIGN(MountLibraryStubImpl);
};

// static
MountLibrary* MountLibrary::GetImpl(bool stub) {
  if (stub)
    return new MountLibraryStubImpl();
  else
    return new MountLibraryImpl();
}

}  // namespace chromeos

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::MountLibraryImpl);