File: drivefs_host.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (413 lines) | stat: -rw-r--r-- 14,261 bytes parent folder | download | duplicates (6)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/drivefs/drivefs_host.h"

#include <memory>
#include <utility>

#include "ash/constants/ash_features.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/strcat.h"
#include "base/timer/timer.h"
#include "chromeos/ash/components/drivefs/drivefs_bootstrap.h"
#include "chromeos/ash/components/drivefs/drivefs_host.h"
#include "chromeos/ash/components/drivefs/drivefs_http_client.h"
#include "chromeos/ash/components/drivefs/drivefs_search.h"
#include "chromeos/ash/components/drivefs/drivefs_search_query.h"
#include "chromeos/ash/components/drivefs/mojom/drivefs.mojom.h"
#include "chromeos/ash/components/drivefs/mojom/notifications.mojom.h"
#include "chromeos/components/drivefs/mojom/drivefs_native_messaging.mojom.h"
#include "components/account_id/account_id.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "services/network/public/cpp/network_connection_tracker.h"

namespace drivefs {

namespace {

constexpr char kDataPath[] = "GCache/v2";

}  // namespace

std::ostream& operator<<(std::ostream& os, const drivefs::SyncStatus& status) {
  switch (status) {
    case SyncStatus::kNotFound:
      return os << "not_found";
    case SyncStatus::kCompleted:
      return os << "completed";
    case SyncStatus::kQueued:
      return os << "queued";
    case SyncStatus::kInProgress:
      return os << "in_progress";
    case SyncStatus::kError:
      return os << "error";
    default:
      return os << "unknown";
  }
}

std::unique_ptr<DriveFsBootstrapListener>
DriveFsHost::Delegate::CreateMojoListener() {
  return std::make_unique<DriveFsBootstrapListener>();
}

// A container of state tied to a particular mounting of DriveFS. None of this
// should be shared between mounts.
class DriveFsHost::MountState : public DriveFsSession {
 public:
  explicit MountState(DriveFsHost* host)
      : DriveFsSession(host->timer_.get(),
                       DiskMounter::Create(host->disk_mount_manager_),
                       CreateMojoConnection(host->account_token_delegate_.get(),
                                            host->delegate_),
                       host->GetDataPath(),
                       host->delegate_->GetMyFilesPath(),
                       host->GetDefaultMountDirName(),
                       host->mount_observer_),
        host_(host) {
    token_fetch_attempted_ =
        bool{host->account_token_delegate_->GetCachedAccessToken()};
    search_ = std::make_unique<DriveFsSearch>(
        drivefs_interface(), host_->network_connection_tracker_, host_->clock_);
    http_client_ = std::make_unique<DriveFsHttpClient>(
        host_->delegate_->GetURLLoaderFactory());
  }

  MountState(const MountState&) = delete;
  MountState& operator=(const MountState&) = delete;

  ~MountState() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(host_->sequence_checker_);
    if (is_mounted()) {
      for (Observer& observer : host_->observers_) {
        DCHECK_EQ(observer.GetHost(), host_);
        observer.OnUnmounted();
      }
    }
  }

  static std::unique_ptr<DriveFsConnection> CreateMojoConnection(
      DriveFsAuth* auth_delegate,
      DriveFsHost::Delegate* delegate) {
    auto access_token = auth_delegate->GetCachedAccessToken();
    mojom::DriveFsConfigurationPtr config = {
        std::in_place,
        auth_delegate->GetAccountId().GetUserEmail(),
        std::move(access_token),
        auth_delegate->IsMetricsCollectionEnabled(),
        delegate->GetLostAndFoundDirectoryName(),
        base::FeatureList::IsEnabled(ash::features::kDriveFsMirroring),
        delegate->IsVerboseLoggingEnabled(),
        base::FeatureList::IsEnabled(ash::features::kDriveFsShowCSEFiles)
            ? mojom::CSESupport::kListing
            : mojom::CSESupport::kNone,
        ash::features::IsLauncherContinueSectionWithRecentsEnabled(),
        ash::features::IsShowSharingUserInLauncherContinueSectionEnabled(),
    };
    return DriveFsConnection::Create(delegate->CreateMojoListener(),
                                     std::move(config));
  }

  std::unique_ptr<DriveFsSearchQuery> CreateSearchQuery(
      mojom::QueryParametersPtr query) {
    return search_->CreateQuery(std::move(query));
  }

  mojom::QueryParameters::QuerySource SearchDriveFs(
      mojom::QueryParametersPtr query,
      mojom::SearchQuery::GetNextPageCallback callback) {
    return search_->PerformSearch(std::move(query), std::move(callback));
  }

 private:
  // mojom::DriveFsDelegate:
  void GetAccessToken(const std::string& client_id,
                      const std::string& app_id,
                      const std::vector<std::string>& scopes,
                      GetAccessTokenCallback callback) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(host_->sequence_checker_);
    host_->account_token_delegate_->GetAccessToken(
        !token_fetch_attempted_,
        base::BindOnce(
            [](GetAccessTokenCallback callback, mojom::AccessTokenStatus status,
               mojom::AccessTokenPtr access_token) {
              if (status != mojom::AccessTokenStatus::kSuccess) {
                std::move(callback).Run(status, "");
                return;
              }
              std::move(callback).Run(status, access_token->token);
            },
            std::move(callback)));
    token_fetch_attempted_ = true;
  }

  void GetAccessTokenWithExpiry(
      const std::string& client_id,
      const std::string& app_id,
      const std::vector<std::string>& scopes,
      GetAccessTokenWithExpiryCallback callback) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(host_->sequence_checker_);
    host_->account_token_delegate_->GetAccessToken(!token_fetch_attempted_,
                                                   std::move(callback));
    token_fetch_attempted_ = true;
  }

  void OnItemProgress(const mojom::ProgressEventPtr progress_event) override {
    for (Observer& observer : host_->observers_) {
      DCHECK_EQ(observer.GetHost(), host_);
      observer.OnItemProgress(*progress_event);
    }
  }

  void OnSyncingStatusUpdate(mojom::SyncingStatusPtr status) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(host_->sequence_checker_);

    for (auto& observer : host_->observers_) {
      observer.OnSyncingStatusUpdate(*status);
    }
  }

  void OnMirrorSyncingStatusUpdate(mojom::SyncingStatusPtr status) override {
    for (Observer& observer : host_->observers_) {
      DCHECK_EQ(observer.GetHost(), host_);
      observer.OnMirrorSyncingStatusUpdate(*status);
    }
  }

  void OnFilesChanged(std::vector<mojom::FileChangePtr> changes) override {
    std::vector<mojom::FileChange> changes_values;
    changes_values.reserve(changes.size());
    for (mojom::FileChangePtr& change : changes) {
      changes_values.emplace_back(std::move(*change));
    }
    for (Observer& observer : host_->observers_) {
      DCHECK_EQ(observer.GetHost(), host_);
      observer.OnFilesChanged(changes_values);
    }
  }

  void OnError(mojom::DriveErrorPtr error) override {
    if (!IsKnownEnumValue(error->type)) {
      return;
    }
    for (Observer& observer : host_->observers_) {
      DCHECK_EQ(observer.GetHost(), host_);
      observer.OnError(*error);
    }
  }

  void OnTeamDrivesListReady(
      const std::vector<std::string>& team_drive_ids) override {}

  void OnTeamDriveChanged(const std::string& team_drive_id,
                          CreateOrDelete change_type) override {}

  void ConnectToExtension(
      mojom::ExtensionConnectionParamsPtr params,
      mojo::PendingReceiver<mojom::NativeMessagingPort> port,
      mojo::PendingRemote<mojom::NativeMessagingHost> host,
      ConnectToExtensionCallback callback) override {
    host_->delegate_->ConnectToExtension(std::move(params), std::move(port),
                                         std::move(host), std::move(callback));
  }

  void DisplayConfirmDialog(mojom::DialogReasonPtr error,
                            DisplayConfirmDialogCallback callback) override {
    if (!IsKnownEnumValue(error->type) || !host_->dialog_handler_) {
      std::move(callback).Run(mojom::DialogResult::kNotDisplayed);
      return;
    }
    host_->dialog_handler_.Run(
        *error, mojo::WrapCallbackWithDefaultInvokeIfNotRun(
                    std::move(callback), mojom::DialogResult::kNotDisplayed));
  }

  void ExecuteHttpRequest(
      mojom::HttpRequestPtr request,
      mojo::PendingRemote<mojom::HttpDelegate> delegate) override {
    if (!http_client_) {
      // The Chrome Network Service <-> DriveFS bridge is not enabled. Ignore
      // the request and allow the |delegate| to close itself. DriveFS will
      // pick up on the |delegate| closure and fallback to cURL.
      return;
    }
    http_client_->ExecuteHttpRequest(std::move(request), std::move(delegate));
  }

  void GetMachineRootID(GetMachineRootIDCallback callback) override {
    if (!ash::features::IsDriveFsMirroringEnabled()) {
      std::move(callback).Run({});
      return;
    }
    std::move(callback).Run(host_->delegate_->GetMachineRootID());
  }

  void PersistMachineRootID(const std::string& id) override {
    if (!ash::features::IsDriveFsMirroringEnabled()) {
      return;
    }
    host_->delegate_->PersistMachineRootID(std::move(id));
  }

  void OnNotificationReceived(
      mojom::DriveFsNotificationPtr notification) override {
    if (!ash::features::IsDriveFsMirroringEnabled()) {
      return;
    }
    host_->delegate_->PersistNotification(std::move(notification));
  }

  void OnMirrorSyncError(mojom::MirrorSyncErrorListPtr error_list) override {
    if (ash::features::IsDriveFsMirroringEnabled()) {
      host_->delegate_->PersistSyncErrors(std::move(error_list));
    }
  }

  // Owns |this|.
  const raw_ptr<DriveFsHost> host_;

  std::unique_ptr<DriveFsSearch> search_;
  std::unique_ptr<DriveFsHttpClient> http_client_;

  bool token_fetch_attempted_ = false;

  // Used to dispatch individual sync status updates in a debounced manner, only
  // sending the sync states that have changed since the last dispatched event.
  std::unique_ptr<base::RetainingOneShotTimer> sync_throttle_timer_;
};

DriveFsHost::DriveFsHost(
    const base::FilePath& profile_path,
    DriveFsHost::Delegate* delegate,
    DriveFsHost::MountObserver* mount_observer,
    network::NetworkConnectionTracker* network_connection_tracker,
    const base::Clock* clock,
    ash::disks::DiskMountManager* disk_mount_manager,
    std::unique_ptr<base::OneShotTimer> timer)
    : profile_path_(profile_path),
      delegate_(delegate),
      mount_observer_(mount_observer),
      network_connection_tracker_(network_connection_tracker),
      clock_(clock),
      disk_mount_manager_(disk_mount_manager),
      timer_(std::move(timer)),
      account_token_delegate_(
          std::make_unique<DriveFsAuth>(clock,
                                        profile_path,
                                        std::make_unique<base::OneShotTimer>(),
                                        delegate)) {
  DCHECK(delegate_);
  DCHECK(mount_observer_);
  DCHECK(network_connection_tracker_);
  DCHECK(clock_);
}

DriveFsHost::~DriveFsHost() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  for (Observer& observer : observers_) {
    DCHECK_EQ(observer.GetHost(), this);
    observer.OnHostDestroyed();
    observer.Reset();
  }

  // Reset `mount_state_` manually to avoid accessing a partially-destructed
  // `this` in ~MountState().
  mount_state_.reset();
}

bool DriveFsHost::Mount() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // TODO(b/336831215): Remove these logs once bug has been fixed.
  LOG(ERROR) << "DriveFs mounted";
  const AccountId& account_id = delegate_->GetAccountId();
  if (mount_state_ || !account_id.HasAccountIdKey() ||
      account_id.GetUserEmail().empty()) {
    return false;
  }
  mount_state_ = std::make_unique<MountState>(this);
  return true;
}

void DriveFsHost::Unmount() {
  // TODO(b/336831215): Remove these logs once bug has been fixed.
  LOG(ERROR) << "DriveFs unmounted";
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  mount_state_.reset();
}

bool DriveFsHost::IsMounted() const {
  return mount_state_ && mount_state_->is_mounted();
}

base::FilePath DriveFsHost::GetMountPath() const {
  return mount_state_ && mount_state_->is_mounted()
             ? mount_state_->mount_path()
             : base::FilePath("/media/fuse").Append(GetDefaultMountDirName());
}

base::FilePath DriveFsHost::GetDataPath() const {
  return profile_path_.Append(kDataPath).Append(
      delegate_->GetObfuscatedAccountId());
}

mojom::DriveFs* DriveFsHost::GetDriveFsInterface() const {
  if (!mount_state_ || !mount_state_->is_mounted()) {
    return nullptr;
  }
  return mount_state_->drivefs_interface();
}

std::unique_ptr<DriveFsSearchQuery> DriveFsHost::CreateSearchQuery(
    mojom::QueryParametersPtr query) {
  if (!mount_state_ || !mount_state_->is_mounted()) {
    return nullptr;
  }
  return mount_state_->CreateSearchQuery(std::move(query));
}

mojom::QueryParameters::QuerySource DriveFsHost::PerformSearch(
    mojom::QueryParametersPtr query,
    mojom::SearchQuery::GetNextPageCallback callback) {
  if (!mount_state_ || !mount_state_->is_mounted()) {
    std::move(callback).Run(drive::FileError::FILE_ERROR_SERVICE_UNAVAILABLE,
                            {});
    return mojom::QueryParameters::QuerySource::kLocalOnly;
  }
  return mount_state_->SearchDriveFs(std::move(query), std::move(callback));
}

std::string DriveFsHost::GetDefaultMountDirName() const {
  return base::StrCat({"drivefs-", delegate_->GetObfuscatedAccountId()});
}

DriveFsHost::Observer::~Observer() {
  Reset();
}

void DriveFsHost::Observer::Observe(DriveFsHost* const host) {
  if (host != host_) {
    Reset();

    if (host) {
      host->observers_.AddObserver(this);
      host_ = host;
    }
  }
}

void DriveFsHost::Observer::Reset() {
  if (host_) {
    host_->observers_.RemoveObserver(this);
    host_ = nullptr;
  }

  DCHECK(!IsInObserverList());
}

}  // namespace drivefs