-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
drive_integration_service.cc
1548 lines (1346 loc) · 52.9 KB
/
drive_integration_service.cc
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/drive/drive_integration_service.h"
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "ash/constants/ash_features.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/containers/adapters.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/hash/md5.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chrome/browser/ash/drive/drivefs_native_message_host.h"
#include "chrome/browser/ash/drive/file_system_util.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/drive/drive_notification_manager_factory.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/components/drivefs/drivefs_bootstrap.h"
#include "chromeos/ash/components/drivefs/drivefs_pin_manager.h"
#include "chromeos/ash/components/network/network_handler.h"
#include "chromeos/ash/components/network/network_state.h"
#include "chromeos/ash/components/network/network_state_handler.h"
#include "chromeos/ash/components/network/network_state_handler_observer.h"
#include "components/drive/drive_api_util.h"
#include "components/drive/drive_notification_manager.h"
#include "components/drive/drive_pref_names.h"
#include "components/drive/event_logger.h"
#include "components/drive/resource_metadata_storage.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/user_manager/user.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/common/user_agent.h"
#include "google_apis/common/auth_service.h"
#include "google_apis/gaia/core_account_id.h"
#include "google_apis/gaia/gaia_constants.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/device/public/mojom/wake_lock_provider.mojom.h"
#include "services/network/public/cpp/network_connection_tracker.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "storage/browser/file_system/external_mount_points.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/chromeos/strings/grit/ui_chromeos_strings.h"
using content::BrowserContext;
using content::BrowserThread;
namespace drive {
namespace {
// Name of the directory used to store metadata.
const base::FilePath::CharType kMetadataDirectory[] = FILE_PATH_LITERAL("meta");
// Name of the directory used to store cached files.
const base::FilePath::CharType kCacheFileDirectory[] =
FILE_PATH_LITERAL("files");
// Name of the directory used to store temporary files.
const base::FilePath::CharType kTemporaryFileDirectory[] =
FILE_PATH_LITERAL("tmp");
void DeleteDirectoryContents(const base::FilePath& dir) {
base::FileEnumerator content_enumerator(
dir, false, base::FileEnumerator::FILES |
base::FileEnumerator::DIRECTORIES |
base::FileEnumerator::SHOW_SYM_LINKS);
for (base::FilePath path = content_enumerator.Next(); !path.empty();
path = content_enumerator.Next()) {
base::DeletePathRecursively(path);
}
}
base::FilePath FindUniquePath(const base::FilePath& base_name) {
auto target = base_name;
for (int uniquifier = 1; base::PathExists(target); ++uniquifier) {
target = base_name.InsertBeforeExtensionASCII(
base::StringPrintf(" (%d)", uniquifier));
}
return target;
}
base::FilePath GetRecoveredFilesPath(
const base::FilePath& downloads_directory) {
const std::string& dest_directory_name = l10n_util::GetStringUTF8(
IDS_FILE_BROWSER_RECOVERED_FILES_FROM_GOOGLE_DRIVE_DIRECTORY_NAME);
return FindUniquePath(downloads_directory.Append(dest_directory_name));
}
// Initializes FileCache and ResourceMetadata.
// Must be run on the same task runner used by |cache| and |resource_metadata|.
FileError InitializeMetadata(
const base::FilePath& cache_root_directory,
internal::ResourceMetadataStorage* metadata_storage,
const base::FilePath& downloads_directory) {
if (!base::DirectoryExists(
cache_root_directory.Append(kTemporaryFileDirectory))) {
if (base::SysInfo::IsRunningOnChromeOS())
LOG(ERROR) << "/tmp should have been created as clear.";
// Create /tmp directory as encrypted. Cryptohome will re-create /tmp
// direcotry at the next login.
if (!base::CreateDirectory(
cache_root_directory.Append(kTemporaryFileDirectory))) {
LOG(WARNING) << "Failed to create directories.";
return FILE_ERROR_FAILED;
}
}
// Files in temporary directory need not persist across sessions. Clean up
// the directory content while initialization. The directory itself should not
// be deleted because it's created by cryptohome in clear and shouldn't be
// re-created as encrypted.
DeleteDirectoryContents(cache_root_directory.Append(kTemporaryFileDirectory));
if (!base::CreateDirectory(cache_root_directory.Append(
kMetadataDirectory)) ||
!base::CreateDirectory(cache_root_directory.Append(
kCacheFileDirectory))) {
LOG(WARNING) << "Failed to create directories.";
return FILE_ERROR_FAILED;
}
// Change permissions of cache file directory to u+rwx,og+x (711) in order to
// allow archive files in that directory to be mounted by cros-disks.
base::SetPosixFilePermissions(
cache_root_directory.Append(kCacheFileDirectory),
base::FILE_PERMISSION_USER_MASK |
base::FILE_PERMISSION_EXECUTE_BY_GROUP |
base::FILE_PERMISSION_EXECUTE_BY_OTHERS);
// If attempting to migrate to DriveFS without previous Drive sync data
// present, skip the migration.
if (base::IsDirectoryEmpty(cache_root_directory.Append(kMetadataDirectory))) {
return FILE_ERROR_FAILED;
}
internal::ResourceMetadataStorage::UpgradeOldDB(
metadata_storage->directory_path());
if (!metadata_storage->Initialize()) {
LOG(WARNING) << "Failed to initialize the metadata storage.";
return FILE_ERROR_FAILED;
}
return FILE_ERROR_OK;
}
base::FilePath GetFullPath(internal::ResourceMetadataStorage* metadata_storage,
const ResourceEntry& entry) {
std::vector<std::string> path_components;
ResourceEntry current_entry = entry;
constexpr int kPathComponentSanityLimit = 100;
for (int i = 0; i < kPathComponentSanityLimit; ++i) {
path_components.push_back(current_entry.base_name());
if (!current_entry.has_parent_local_id()) {
// Ignore anything not contained within the drive grand root.
return {};
}
if (current_entry.parent_local_id() == util::kDriveGrandRootLocalId) {
// Omit the DriveGrantRoot directory from the path; DriveFS paths are
// relative to the mount point.
break;
}
if (metadata_storage->GetEntry(current_entry.parent_local_id(),
¤t_entry) != FILE_ERROR_OK) {
return {};
}
}
if (path_components.empty()) {
return {};
}
base::FilePath path("/");
for (const std::string& component : base::Reversed(path_components)) {
path = path.Append(component);
}
return path;
}
// Recover any dirty files in GCache/v1 to a recovered files directory in
// Downloads. This imitates the behavior of recovering cache files when database
// corruption occurs; however, in this case, we have an intact database so can
// use the exact file names, potentially with uniquifiers added since the
// directory structure is discarded.
void RecoverDirtyFiles(
const base::FilePath& cache_directory,
const base::FilePath& downloads_directory,
const std::vector<std::pair<base::FilePath, std::string>>& dirty_files) {
if (dirty_files.empty()) {
return;
}
auto recovery_directory = GetRecoveredFilesPath(downloads_directory);
if (!base::CreateDirectory(recovery_directory)) {
return;
}
for (auto& dirty_file : dirty_files) {
auto target_path =
FindUniquePath(recovery_directory.Append(dirty_file.first.BaseName()));
base::Move(cache_directory.Append(dirty_file.second), target_path);
}
}
// Remove the data used by the old Drive client, first moving any dirty files
// into the user's Downloads.
void CleanupGCacheV1(
const base::FilePath& cache_directory,
const base::FilePath& downloads_directory,
std::vector<std::pair<base::FilePath, std::string>> dirty_files) {
RecoverDirtyFiles(cache_directory.Append(kCacheFileDirectory),
downloads_directory, dirty_files);
DeleteDirectoryContents(cache_directory);
}
std::vector<base::FilePath> GetPinnedAndDirtyFiles(
std::unique_ptr<internal::ResourceMetadataStorage, util::DestroyHelper>
metadata_storage,
base::FilePath cache_directory,
base::FilePath downloads_directory) {
std::vector<base::FilePath> pinned_files;
std::vector<std::pair<base::FilePath, std::string>> dirty_files;
for (auto it = metadata_storage->GetIterator(); !it->IsAtEnd();
it->Advance()) {
const auto& value = it->GetValue();
if (!value.has_file_specific_info()) {
continue;
}
const auto& info = value.file_specific_info();
if (info.cache_state().is_pinned()) {
auto path = GetFullPath(metadata_storage.get(), value);
if (!path.empty()) {
pinned_files.push_back(std::move(path));
}
}
if (info.cache_state().is_dirty()) {
dirty_files.push_back(std::make_pair(
GetFullPath(metadata_storage.get(), value), value.local_id()));
}
}
// Destructing |metadata_storage| requires a posted task to run, so defer
// deleting its data until after it's been destructed. This also returns the
// list of files to pin to the UI thread without waiting for the remaining
// data to be cleared.
metadata_storage.reset();
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&CleanupGCacheV1, std::move(cache_directory),
std::move(downloads_directory), std::move(dirty_files)));
return pinned_files;
}
DriveMountStatus ConvertMountFailure(
drivefs::DriveFsHost::MountObserver::MountFailure failure) {
switch (failure) {
case drivefs::DriveFsHost::MountObserver::MountFailure::kInvocation:
return DriveMountStatus::kInvocationFailure;
case drivefs::DriveFsHost::MountObserver::MountFailure::kIpcDisconnect:
return DriveMountStatus::kUnexpectedDisconnect;
case drivefs::DriveFsHost::MountObserver::MountFailure::kNeedsRestart:
return DriveMountStatus::kTemporaryUnavailable;
case drivefs::DriveFsHost::MountObserver::MountFailure::kTimeout:
return DriveMountStatus::kTimeout;
case drivefs::DriveFsHost::MountObserver::MountFailure::kUnknown:
return DriveMountStatus::kUnknownFailure;
}
NOTREACHED();
}
bool EnsureDirectoryExists(const base::FilePath& path) {
return base::DirectoryExists(path) || base::CreateDirectory(path);
}
void UmaEmitMountStatus(DriveMountStatus status) {
UMA_HISTOGRAM_ENUMERATION("DriveCommon.Lifecycle.Mount", status);
}
void UmaEmitMountTime(DriveMountStatus status,
const base::TimeTicks& time_started) {
if (status == DriveMountStatus::kSuccess) {
UMA_HISTOGRAM_MEDIUM_TIMES("DriveCommon.Lifecycle.MountTime.SuccessTime",
base::TimeTicks::Now() - time_started);
} else {
UMA_HISTOGRAM_MEDIUM_TIMES("DriveCommon.Lifecycle.MountTime.FailTime",
base::TimeTicks::Now() - time_started);
}
}
void UmaEmitMountOutcome(DriveMountStatus status,
const base::TimeTicks& time_started) {
UmaEmitMountStatus(status);
UmaEmitMountTime(status, time_started);
}
void UmaEmitUnmountOutcome(DriveMountStatus status) {
UMA_HISTOGRAM_ENUMERATION("DriveCommon.Lifecycle.Unmount", status);
}
void UmaEmitFirstLaunch(const base::TimeTicks& time_started) {
UMA_HISTOGRAM_MEDIUM_TIMES("DriveCommon.Lifecycle.FirstLaunchTime",
base::TimeTicks::Now() - time_started);
}
// Clears the cache folder at |cache_path|, but preserve |logs_path|.
// |logs_path| should be a descendent of |cache_path|.
bool ClearCache(base::FilePath cache_path, base::FilePath logs_path) {
DCHECK(cache_path.IsParent(logs_path));
bool success = true;
base::FileEnumerator content_enumerator(
cache_path, false,
base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES |
base::FileEnumerator::SHOW_SYM_LINKS);
for (base::FilePath path = content_enumerator.Next(); !path.empty();
path = content_enumerator.Next()) {
// Keep the logs folder as it's useful for debugging.
if (path == logs_path) {
continue;
}
if (!base::DeletePathRecursively(path)) {
success = false;
break;
}
}
return success;
}
} // namespace
// Observes drive disable Preference's change.
class DriveIntegrationService::PreferenceWatcher
: public network::NetworkConnectionTracker::NetworkConnectionObserver,
public ash::NetworkStateHandlerObserver {
public:
explicit PreferenceWatcher(PrefService* pref_service)
: pref_service_(pref_service) {
DCHECK(pref_service);
pref_change_registrar_.Init(pref_service);
pref_change_registrar_.Add(
prefs::kDisableDrive,
base::BindRepeating(&PreferenceWatcher::OnPreferenceChanged,
weak_ptr_factory_.GetWeakPtr()));
pref_change_registrar_.Add(
prefs::kDisableDriveOverCellular,
base::BindRepeating(&PreferenceWatcher::UpdateSyncPauseState,
weak_ptr_factory_.GetWeakPtr()));
if (ash::features::IsDriveFsMirroringEnabled()) {
pref_change_registrar_.Add(
prefs::kDriveFsEnableMirrorSync,
base::BindRepeating(&PreferenceWatcher::ToggleLocalMirroring,
weak_ptr_factory_.GetWeakPtr()));
}
if (ash::features::IsDriveFsBulkPinningEnabled()) {
pref_change_registrar_.Add(
prefs::kDriveFsBulkPinningEnabled,
base::BindRepeating(&PreferenceWatcher::UpdateBulkPinningState,
weak_ptr_factory_.GetWeakPtr()));
}
}
PreferenceWatcher(const PreferenceWatcher&) = delete;
PreferenceWatcher& operator=(const PreferenceWatcher&) = delete;
~PreferenceWatcher() override {
if (integration_service_) {
content::GetNetworkConnectionTracker()->RemoveNetworkConnectionObserver(
this);
if (ash::NetworkHandler::IsInitialized()) {
ash::NetworkHandler::Get()->network_state_handler()->RemoveObserver(
this);
}
}
}
void SetIntegrationService(DriveIntegrationService* integration_service) {
integration_service_ = integration_service;
content::GetNetworkConnectionTracker()->AddNetworkConnectionObserver(this);
AddNetworkPortalDetectorObserver();
}
void UpdateSyncPauseState() {
auto type = network::mojom::ConnectionType::CONNECTION_UNKNOWN;
if (content::GetNetworkConnectionTracker()->GetConnectionType(
&type, base::BindOnce(&DriveIntegrationService::PreferenceWatcher::
OnConnectionChanged,
weak_ptr_factory_.GetWeakPtr()))) {
OnConnectionChanged(type);
}
}
bool is_offline() const {
return portal_state_ != ash::NetworkState::PortalState::kOnline &&
portal_state_ != ash::NetworkState::PortalState::kUnknown;
}
private:
void OnPreferenceChanged() {
DCHECK(integration_service_);
integration_service_->SetEnabled(
!pref_service_->GetBoolean(prefs::kDisableDrive));
}
void ToggleLocalMirroring() {
DCHECK(integration_service_);
if (!ash::features::IsDriveFsMirroringEnabled()) {
return;
}
if (pref_service_->GetBoolean(prefs::kDriveFsEnableMirrorSync)) {
integration_service_->ToggleMirroring(
true, base::BindOnce(
&DriveIntegrationService::OnEnableMirroringStatusUpdate,
integration_service_->weak_ptr_factory_.GetWeakPtr()));
} else {
integration_service_->ToggleMirroring(
false, base::BindOnce(
&DriveIntegrationService::OnDisableMirroringStatusUpdate,
integration_service_->weak_ptr_factory_.GetWeakPtr()));
}
}
void UpdateBulkPinningState() {
DCHECK(integration_service_);
if (!ash::features::IsDriveFsBulkPinningEnabled()) {
return;
}
VLOG(1) << "Updating the bulk pinning state";
auto* pin_manager = integration_service_->GetDriveFsPinManager();
if (!pin_manager) {
return;
}
bool enabled = pref_service_->GetBoolean(prefs::kDriveFsBulkPinningEnabled);
integration_service_->GetDriveFsPinManager()->SetBulkPinningEnabled(
enabled);
if (enabled) {
pin_manager->Start(base::DoNothing());
} else {
pin_manager->Stop();
}
}
void AddNetworkPortalDetectorObserver() {
if (!ash::NetworkHandler::IsInitialized())
return; // Test environment.
ash::NetworkStateHandler* handler =
ash::NetworkHandler::Get()->network_state_handler();
handler->AddObserver(this);
const ash::NetworkState* default_network = handler->DefaultNetwork();
ash::NetworkState::PortalState portal_state =
default_network ? default_network->GetPortalState()
: ash::NetworkState::PortalState::kUnknown;
PortalStateChanged(default_network, portal_state);
}
// ash::NetworkStateHandlerObserver
void PortalStateChanged(
const ash::NetworkState* default_network,
ash::NetworkState::PortalState portal_state) override {
portal_state_ = portal_state;
if (integration_service_->remount_when_online_ &&
portal_state == ash::NetworkState::PortalState::kOnline) {
integration_service_->remount_when_online_ = false;
integration_service_->mount_start_ = {};
integration_service_->AddDriveMountPoint();
}
}
void OnShuttingDown() override {
ash::NetworkHandler::Get()->network_state_handler()->RemoveObserver(this);
}
// network::NetworkConnectionTracker::NetworkConnectionObserver
void OnConnectionChanged(network::mojom::ConnectionType type) override {
if (!integration_service_->GetDriveFsInterface())
return;
integration_service_->GetDriveFsInterface()->UpdateNetworkState(
network::NetworkConnectionTracker::IsConnectionCellular(type) &&
pref_service_->GetBoolean(prefs::kDisableDriveOverCellular),
type == network::mojom::ConnectionType::CONNECTION_NONE);
}
PrefService* pref_service_;
PrefChangeRegistrar pref_change_registrar_;
DriveIntegrationService* integration_service_ = nullptr;
ash::NetworkState::PortalState portal_state_ =
ash::NetworkState::PortalState::kUnknown;
base::WeakPtrFactory<PreferenceWatcher> weak_ptr_factory_{this};
};
class DriveIntegrationService::DriveFsHolder
: public drivefs::DriveFsHost::Delegate,
public drivefs::DriveFsHost::MountObserver {
public:
DriveFsHolder(Profile* profile,
drivefs::DriveFsHost::MountObserver* mount_observer,
DriveFsMojoListenerFactory test_drivefs_mojo_listener_factory)
: profile_(profile),
mount_observer_(mount_observer),
test_drivefs_mojo_listener_factory_(
std::move(test_drivefs_mojo_listener_factory)),
drivefs_host_(profile_->GetPath(),
this,
this,
content::GetNetworkConnectionTracker(),
base::DefaultClock::GetInstance(),
ash::disks::DiskMountManager::GetInstance(),
std::make_unique<base::OneShotTimer>()) {}
DriveFsHolder(const DriveFsHolder&) = delete;
DriveFsHolder& operator=(const DriveFsHolder&) = delete;
drivefs::DriveFsHost* drivefs_host() { return &drivefs_host_; }
private:
// drivefs::DriveFsHost::Delegate:
scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory()
override {
return profile_->GetURLLoaderFactory();
}
signin::IdentityManager* GetIdentityManager() override {
return IdentityManagerFactory::GetForProfile(profile_);
}
const AccountId& GetAccountId() override {
return ash::ProfileHelper::Get()
->GetUserByProfile(profile_)
->GetAccountId();
}
std::string GetObfuscatedAccountId() override {
if (!GetAccountId().HasAccountIdKey()) {
return "";
}
return base::MD5String(GetProfileSalt() + "-" +
GetAccountId().GetAccountIdKey());
}
bool IsMetricsCollectionEnabled() override {
return g_browser_process->local_state()->GetBoolean(
metrics::prefs::kMetricsReportingEnabled);
}
DriveNotificationManager& GetDriveNotificationManager() override {
return *DriveNotificationManagerFactory::GetForBrowserContext(profile_);
}
void OnMountFailed(MountFailure failure,
absl::optional<base::TimeDelta> remount_delay) override {
mount_observer_->OnMountFailed(failure, std::move(remount_delay));
}
void OnMounted(const base::FilePath& path) override {
mount_observer_->OnMounted(path);
}
void OnUnmounted(absl::optional<base::TimeDelta> remount_delay) override {
mount_observer_->OnUnmounted(std::move(remount_delay));
}
const std::string& GetProfileSalt() {
if (!profile_salt_.empty()) {
return profile_salt_;
}
PrefService* prefs = profile_->GetPrefs();
profile_salt_ = prefs->GetString(prefs::kDriveFsProfileSalt);
if (profile_salt_.empty()) {
profile_salt_ = base::UnguessableToken::Create().ToString();
prefs->SetString(prefs::kDriveFsProfileSalt, profile_salt_);
}
return profile_salt_;
}
std::unique_ptr<drivefs::DriveFsBootstrapListener> CreateMojoListener()
override {
if (test_drivefs_mojo_listener_factory_)
return test_drivefs_mojo_listener_factory_.Run();
return Delegate::CreateMojoListener();
}
base::FilePath GetMyFilesPath() override {
return file_manager::util::GetMyFilesFolderForProfile(profile_);
}
std::string GetLostAndFoundDirectoryName() override {
return l10n_util::GetStringUTF8(
IDS_FILE_BROWSER_RECOVERED_FILES_FROM_GOOGLE_DRIVE_DIRECTORY_NAME);
}
bool IsVerboseLoggingEnabled() override {
return profile_->GetPrefs()->GetBoolean(
prefs::kDriveFsEnableVerboseLogging);
}
drivefs::mojom::DriveFsDelegate::ExtensionConnectionStatus ConnectToExtension(
drivefs::mojom::ExtensionConnectionParamsPtr params,
mojo::PendingReceiver<drivefs::mojom::NativeMessagingPort> port,
mojo::PendingRemote<drivefs::mojom::NativeMessagingHost> host) override {
return ConnectToDriveFsNativeMessageExtension(
profile_, params->extension_id, std::move(port), std::move(host));
}
const std::string GetMachineRootID() override {
if (!ash::features::IsDriveFsMirroringEnabled()) {
return "";
}
return profile_->GetPrefs()->GetString(
prefs::kDriveFsMirrorSyncMachineRootId);
}
void PersistMachineRootID(const std::string& id) override {
if (!ash::features::IsDriveFsMirroringEnabled()) {
return;
}
profile_->GetPrefs()->SetString(prefs::kDriveFsMirrorSyncMachineRootId, id);
}
Profile* const profile_;
drivefs::DriveFsHost::MountObserver* const mount_observer_;
const DriveFsMojoListenerFactory test_drivefs_mojo_listener_factory_;
drivefs::DriveFsHost drivefs_host_;
std::string profile_salt_;
};
DriveIntegrationService::DriveIntegrationService(
Profile* profile,
const std::string& test_mount_point_name,
const base::FilePath& test_cache_root,
DriveFsMojoListenerFactory test_drivefs_mojo_listener_factory)
: profile_(profile),
state_(NOT_INITIALIZED),
enabled_(false),
mount_point_name_(test_mount_point_name),
cache_root_directory_(!test_cache_root.empty()
? test_cache_root
: util::GetCacheRootPath(profile)),
drivefs_holder_(std::make_unique<DriveFsHolder>(
profile_,
this,
std::move(test_drivefs_mojo_listener_factory))) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(profile && !profile->IsOffTheRecord());
logger_ = std::make_unique<EventLogger>();
blocking_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_BLOCKING,
base::WithBaseSyncPrimitives()});
if (util::IsDriveAvailableForProfile(profile)) {
preference_watcher_ =
std::make_unique<PreferenceWatcher>(profile->GetPrefs());
preference_watcher_->SetIntegrationService(this);
}
bool migrated_to_drivefs =
profile_->GetPrefs()->GetBoolean(prefs::kDriveFsPinnedMigrated);
if (migrated_to_drivefs) {
state_ = INITIALIZED;
} else {
metadata_storage_.reset(new internal::ResourceMetadataStorage(
cache_root_directory_.Append(kMetadataDirectory),
blocking_task_runner_.get()));
}
SetEnabled(drive::util::IsDriveEnabledForProfile(profile));
}
DriveIntegrationService::~DriveIntegrationService() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
}
void DriveIntegrationService::Shutdown() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
weak_ptr_factory_.InvalidateWeakPtrs();
RemoveDriveMountPoint();
for (auto& observer : observers_)
observer.OnDriveIntegrationServiceDestroyed();
}
void DriveIntegrationService::SetEnabled(bool enabled) {
// If Drive is being disabled, ensure the download destination preference to
// be out of Drive. Do this before "Do nothing if not changed." because we
// want to run the check for the first SetEnabled() called in the constructor,
// which may be a change from false to false.
if (!enabled)
AvoidDriveAsDownloadDirectoryPreference();
// Do nothing if not changed.
if (enabled_ == enabled)
return;
if (enabled) {
enabled_ = true;
switch (state_) {
case NOT_INITIALIZED:
// If the initialization is not yet done, trigger it.
Initialize();
return;
case INITIALIZING:
case REMOUNTING:
// If the state is INITIALIZING or REMOUNTING, at the end of the
// process, it tries to mounting (with re-checking enabled state).
// Do nothing for now.
return;
case INITIALIZED:
// The integration service is already initialized. Add the mount point.
AddDriveMountPoint();
return;
}
NOTREACHED();
} else {
RemoveDriveMountPoint();
enabled_ = false;
drivefs_total_failures_count_ = 0;
drivefs_consecutive_failures_count_ = 0;
mount_failed_ = false;
mount_start_ = {};
}
}
bool DriveIntegrationService::IsMounted() const {
if (mount_point_name_.empty())
return false;
// Look up the registered path, and just discard it.
// GetRegisteredPath() returns true if the path is available.
base::FilePath unused;
storage::ExternalMountPoints* const mount_points =
storage::ExternalMountPoints::GetSystemInstance();
DCHECK(mount_points);
return mount_points->GetRegisteredPath(mount_point_name_, &unused);
}
base::FilePath DriveIntegrationService::GetMountPointPath() const {
return GetDriveFsHost()->GetMountPath();
}
base::FilePath DriveIntegrationService::GetDriveFsLogPath() const {
return GetDriveFsHost()->GetDataPath().Append("Logs/drivefs.txt");
}
bool DriveIntegrationService::GetRelativeDrivePath(
const base::FilePath& local_path,
base::FilePath* drive_path) const {
if (!IsMounted()) {
return false;
}
base::FilePath mount_point = GetMountPointPath();
base::FilePath relative("/");
if (!mount_point.AppendRelativePath(local_path, &relative)) {
return false;
}
if (drive_path) {
*drive_path = relative;
}
return true;
}
void DriveIntegrationService::AddObserver(
DriveIntegrationServiceObserver* observer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
observers_.AddObserver(observer);
}
void DriveIntegrationService::RemoveObserver(
DriveIntegrationServiceObserver* observer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
observers_.RemoveObserver(observer);
}
void DriveIntegrationService::ClearCacheAndRemountFileSystem(
base::OnceCallback<void(bool)> callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (in_clear_cache_) {
std::move(callback).Run(false);
return;
}
in_clear_cache_ = true;
base::TimeDelta delay;
if (IsMounted()) {
RemoveDriveMountPoint();
// TODO(crbug/1069328): We wait 2 seconds here so that DriveFS can unmount
// completely. Ideally we'd wait for an unmount complete callback.
delay = base::Seconds(2);
}
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(
&DriveIntegrationService::ClearCacheAndRemountFileSystemAfterDelay,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)),
delay);
}
void DriveIntegrationService::ClearCacheAndRemountFileSystemAfterDelay(
base::OnceCallback<void(bool)> callback) {
blocking_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&ClearCache, GetDriveFsHost()->GetDataPath(),
GetDriveFsLogPath().DirName()),
base::BindOnce(
&DriveIntegrationService::MaybeRemountFileSystemAfterClearCache,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void DriveIntegrationService::MaybeRemountFileSystemAfterClearCache(
base::OnceCallback<void(bool)> callback,
bool success) {
if (is_enabled()) {
AddDriveMountPoint();
}
in_clear_cache_ = false;
std::move(callback).Run(success);
}
drivefs::DriveFsHost* DriveIntegrationService::GetDriveFsHost() const {
return drivefs_holder_->drivefs_host();
}
drivefs::pinning::DriveFsPinManager*
DriveIntegrationService::GetDriveFsPinManager() {
if (!ash::features::IsDriveFsBulkPinningEnabled()) {
return nullptr;
}
return pin_manager_.get();
}
drivefs::mojom::DriveFs* DriveIntegrationService::GetDriveFsInterface() const {
return GetDriveFsHost()->GetDriveFsInterface();
}
void DriveIntegrationService::AddBackDriveMountPoint(
base::OnceCallback<void(bool)> callback,
FileError error) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(callback);
state_ = error == FILE_ERROR_OK ? INITIALIZED : NOT_INITIALIZED;
if (error != FILE_ERROR_OK || !enabled_) {
// Failed to reset, or Drive was disabled during the reset.
std::move(callback).Run(false);
return;
}
AddDriveMountPoint();
std::move(callback).Run(true);
}
void DriveIntegrationService::AddDriveMountPoint() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(INITIALIZED, state_);
DCHECK(enabled_);
weak_ptr_factory_.InvalidateWeakPtrs();
if (!GetDriveFsHost()->IsMounted()) {
PrefService* prefs = profile_->GetPrefs();
bool was_ever_mounted =
prefs->GetBoolean(prefs::kDriveFsWasLaunchedAtLeastOnce);
if (mount_start_.is_null() || was_ever_mounted) {
mount_start_ = base::TimeTicks::Now();
}
blocking_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&EnsureDirectoryExists, GetDriveFsHost()->GetDataPath()),
base::BindOnce(&DriveIntegrationService::MaybeMountDrive,
weak_ptr_factory_.GetWeakPtr()));
} else {
AddDriveMountPointAfterMounted();
}
}
void DriveIntegrationService::MaybeMountDrive(bool data_directory_exists) {
if (!data_directory_exists) {
LOG(ERROR) << "Could not create DriveFS data directory";
} else {
GetDriveFsHost()->Mount();
}
}
bool DriveIntegrationService::AddDriveMountPointAfterMounted() {
const base::FilePath& drive_mount_point = GetMountPointPath();
if (mount_point_name_.empty()) {
mount_point_name_ = drive_mount_point.BaseName().AsUTF8Unsafe();
}
storage::ExternalMountPoints* const mount_points =
storage::ExternalMountPoints::GetSystemInstance();
DCHECK(mount_points);
drivefs_consecutive_failures_count_ = 0;
bool success = mount_points->RegisterFileSystem(
mount_point_name_, storage::kFileSystemTypeDriveFs,
storage::FileSystemMountOption(), drive_mount_point);
if (success) {
logger_->Log(logging::LOG_INFO, "Drive mount point is added");
for (auto& observer : observers_)
observer.OnFileSystemMounted();
}
if (preference_watcher_) {
preference_watcher_->UpdateSyncPauseState();
}
if (!profile_->GetPrefs()->GetBoolean(prefs::kDriveFsPinnedMigrated)) {
MigratePinnedFiles();
}
return success;
}
void DriveIntegrationService::RemoveDriveMountPoint() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
weak_ptr_factory_.InvalidateWeakPtrs();
remount_when_online_ = false;
if (!mount_point_name_.empty()) {
if (storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
mount_point_name_)) {
for (auto& observer : observers_) {
observer.OnFileSystemBeingUnmounted();
}
logger_->Log(logging::LOG_INFO, "Drive mount point is removed");
}
}
GetDriveFsHost()->Unmount();
if (ash::features::IsDriveFsBulkPinningEnabled() && pin_manager_) {
pin_manager_->Stop();
GetDriveFsHost()->RemoveObserver(pin_manager_.get());
pin_manager_.reset();
}
}
void DriveIntegrationService::MaybeRemountFileSystem(
absl::optional<base::TimeDelta> remount_delay,
bool failed_to_mount) {
DCHECK_EQ(INITIALIZED, state_);
RemoveDriveMountPoint();
if (!remount_delay) {
if (failed_to_mount && preference_watcher_ &&
preference_watcher_->is_offline()) {
logger_->Log(logging::LOG_WARNING,
"DriveFs failed to start, will retry when online.");
remount_when_online_ = true;
return;
}
// If DriveFs didn't specify retry time it's likely unexpected error, e.g.
// crash. Use limited exponential backoff for retry.
++drivefs_consecutive_failures_count_;
++drivefs_total_failures_count_;
if (drivefs_total_failures_count_ > 10) {
mount_failed_ = true;
logger_->Log(logging::LOG_ERROR,
"DriveFs is too crashy. Leaving it alone.");
for (auto& observer : observers_)
observer.OnFileSystemMountFailed();
return;