File: smbfs_share.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 (347 lines) | stat: -rw-r--r-- 12,081 bytes parent folder | download | duplicates (3)
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
// Copyright 2019 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/smb_client/smbfs_share.h"

#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/unguessable_token.h"
#include "chrome/browser/ash/file_manager/volume_manager.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/ash/smb_client/smb_service_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/ash/smb_shares/smb_credentials_dialog.h"
#include "crypto/hash.h"
#include "storage/browser/file_system/external_mount_points.h"

namespace ash::smb_client {

namespace {

constexpr char kMountDirPrefix[] = "smbfs-";
constexpr char kMountIdHashSeparator[] = "#";
constexpr base::TimeDelta kAllowCredentialsTimeout = base::Seconds(5);

SmbMountResult MountErrorToMountResult(smbfs::mojom::MountError mount_error) {
  switch (mount_error) {
    case smbfs::mojom::MountError::kOk:
      return SmbMountResult::kSuccess;
    case smbfs::mojom::MountError::kTimeout:
      return SmbMountResult::kAborted;
    case smbfs::mojom::MountError::kInvalidUrl:
      return SmbMountResult::kInvalidUrl;
    case smbfs::mojom::MountError::kInvalidOptions:
      return SmbMountResult::kInvalidOperation;
    case smbfs::mojom::MountError::kNotFound:
      return SmbMountResult::kNotFound;
    case smbfs::mojom::MountError::kAccessDenied:
      return SmbMountResult::kAuthenticationFailed;
    case smbfs::mojom::MountError::kInvalidProtocol:
      return SmbMountResult::kUnsupportedDevice;
    case smbfs::mojom::MountError::kUnknown:
    default:
      return SmbMountResult::kUnknownFailure;
  }
}

}  // namespace

SmbFsShare::SmbFsShare(Profile* profile,
                       const SmbUrl& share_url,
                       const std::string& display_name,
                       const MountOptions& options)
    : profile_(profile),
      share_url_(share_url),
      display_name_(display_name),
      options_(options),
      mount_id_(GenerateStableMountId()) {
  DCHECK(share_url_.IsValid());
}

SmbFsShare::~SmbFsShare() {
  Unmount(base::DoNothing());
}

void SmbFsShare::Mount(SmbFsShare::MountCallback callback) {
  DCHECK(!mounter_);
  DCHECK(!host_);

  if (unmount_pending_) {
    LOG(WARNING) << "Cannot mount a shared that is being unmounted";
    std::move(callback).Run(SmbMountResult::kMountExists);
    return;
  }

  // TODO(amistry): Come up with a scheme for consistent mount paths between
  // sessions.
  const std::string mount_dir = base::StrCat({kMountDirPrefix, mount_id_});
  if (mounter_creation_callback_for_test_) {
    mounter_ = mounter_creation_callback_for_test_.Run(
        share_url_.ToString(), mount_dir, options_, this);
  } else {
    mounter_ = std::make_unique<smbfs::SmbFsMounter>(
        share_url_.ToString(), mount_dir, options_, this,
        disks::DiskMountManager::GetInstance());
  }
  mounter_->Mount(base::BindOnce(&SmbFsShare::OnMountDone,
                                 base::Unretained(this), std::move(callback)));
}

void SmbFsShare::Remount(const MountOptions& options,
                         SmbFsShare::MountCallback callback) {
  if (IsMounted() || unmount_pending_) {
    std::move(callback).Run(SmbMountResult::kMountExists);
    return;
  }

  options_ = options;

  Mount(std::move(callback));
}

void SmbFsShare::DeleteRecursively(
    const base::FilePath& path,
    SmbFsShare::DeleteRecursivelyCallback callback) {
  if (!host_) {
    std::move(callback).Run(base::File::FILE_ERROR_FAILED);
    return;
  }

  // Only one recursive delete operation can be outstanding at any time.
  if (delete_recursively_callback_) {
    LOG(WARNING) << "A recursive delete operation is already in progress";
    std::move(callback).Run(base::File::FILE_ERROR_FAILED);
    return;
  }

  // smbfs should have no visibility into the full path of the file (which
  // includes the FUSE mount point): it sees a filesystem rooted at the base of
  // the mount point path.
  base::FilePath transformed_path("/");
  bool success = mount_path().AppendRelativePath(path, &transformed_path);
  if (!success) {
    LOG(ERROR)
        << "Could not construct absolute path for recursive delete operation";
    std::move(callback).Run(base::File::FILE_ERROR_FAILED);
    return;
  }

  delete_recursively_callback_ = std::move(callback);
  host_->DeleteRecursively(std::move(transformed_path),
                           base::BindOnce(&SmbFsShare::OnDeleteRecursivelyDone,
                                          base::Unretained(this)));
}

void SmbFsShare::OnDeleteRecursivelyDone(base::File::Error error) {
  DCHECK(delete_recursively_callback_);
  std::move(delete_recursively_callback_).Run(error);
}

void SmbFsShare::Unmount(SmbFsShare::UnmountCallback callback) {
  if (unmount_pending_) {
    LOG(WARNING) << "Cannot unmount a shared that is being unmounted";
    std::move(callback).Run(MountError::kInternalError);
    return;
  }

  unmount_pending_ = true;

  // Cancel any pending mount request.
  mounter_.reset();

  if (!host_) {
    LOG(WARNING) << "Cannot unmount as the share is already unmounted";
    std::move(callback).Run(MountError::kPathNotMounted);
    return;
  }

  // Remove volume from VolumeManager. It's critical this is done before
  // revoking the filesystem from ExternalMountPoints as some observers
  // (ie. Crostini) need to create a cracked FileSystemURL (which
  // requires the mount to still be registered with ExternalMountPoints)
  // during the unmount process.
  file_manager::VolumeManager::Get(profile_)->RemoveSmbFsVolume(
      host_->mount_path());

  storage::ExternalMountPoints* const mount_points =
      storage::ExternalMountPoints::GetSystemInstance();
  DCHECK(mount_points);
  bool success = mount_points->RevokeFileSystem(mount_id_);
  CHECK(success);

  // Get cros-disks to unmount cleanly. In the process it will kill smbfs which
  // may result in OnDisconnected() being called, but reentrant calls to
  // Unmount() will be aborted as unmount_pending_ == true.
  host_->Unmount(base::BindOnce(&SmbFsShare::OnUnmountDone,
                                base::Unretained(this), std::move(callback)));
}

void SmbFsShare::OnUnmountDone(SmbFsShare::UnmountCallback callback,
                               MountError result) {
  host_.reset();

  // Must do this *after* destroying SmbFsHost so that reentrant calls to
  // Unmount() exit early.
  unmount_pending_ = false;

  // Callback to SmbService::OnSuspendUnmountDone().
  std::move(callback).Run(result);
}

void SmbFsShare::OnMountDone(MountCallback callback,
                             smbfs::mojom::MountError mount_error,
                             std::unique_ptr<smbfs::SmbFsHost> smbfs_host) {
  // Don't need the mounter any more.
  mounter_.reset();

  if (mount_error != smbfs::mojom::MountError::kOk) {
    std::move(callback).Run(MountErrorToMountResult(mount_error));
    return;
  }

  DCHECK(smbfs_host);
  host_ = std::move(smbfs_host);

  storage::ExternalMountPoints* const mount_points =
      storage::ExternalMountPoints::GetSystemInstance();
  DCHECK(mount_points);
  bool success = mount_points->RegisterFileSystem(
      mount_id_, storage::kFileSystemTypeSmbFs,
      storage::FileSystemMountOption(), host_->mount_path());
  CHECK(success);

  file_manager::VolumeManager::Get(profile_)->AddSmbFsVolume(
      host_->mount_path(), display_name_);
  std::move(callback).Run(SmbMountResult::kSuccess);
}

void SmbFsShare::OnDisconnected() {
  Unmount(base::DoNothing());

  // At this point, we won't receive any more callbacks from the Mojo host, so
  // run any pending callbacks.
  if (remove_credentials_callback_) {
    LOG(WARNING) << "Mojo disconnected while removing credentials";
    std::move(remove_credentials_callback_).Run(false /* success */);
  }

  if (delete_recursively_callback_) {
    LOG(WARNING)
        << "Mojo disconnected while recursively deleting a path on the share";
    std::move(delete_recursively_callback_).Run(base::File::FILE_ERROR_FAILED);
  }
}

void SmbFsShare::AllowCredentialsRequest() {
  allow_credential_request_ = true;
  allow_credential_request_expiry_ =
      base::TimeTicks::Now() + kAllowCredentialsTimeout;
}

void SmbFsShare::RequestCredentials(RequestCredentialsCallback callback) {
  if (allow_credential_request_expiry_ < base::TimeTicks::Now()) {
    allow_credential_request_ = false;
  }

  if (!allow_credential_request_) {
    std::move(callback).Run(true /* cancel */, "" /* username */,
                            "" /* workgroup */, "" /* password */);
    return;
  }

  smb_dialog::SmbCredentialsDialog::Show(
      mount_id_, share_url_.ToString(),
      base::BindOnce(&SmbFsShare::OnSmbCredentialsDialogShowDone,
                     weak_factory_.GetWeakPtr(), std::move(callback)));
  // Reset the allow dialog state to prevent showing another dialog to the user
  // immediately after they've dismissed one.
  allow_credential_request_ = false;
}

void SmbFsShare::OnSmbCredentialsDialogShowDone(
    RequestCredentialsCallback callback,
    bool canceled,
    const std::string& username,
    const std::string& password) {
  if (canceled) {
    std::move(callback).Run(true /* cancel */, "" /* username */,
                            "" /* workgroup */, "" /* password */);
    return;
  }

  std::string parsed_username = username;
  std::string workgroup;
  ParseUserName(username, &parsed_username, &workgroup);

  // Save updated credentials for future suspend/resume.
  options_.username = parsed_username;
  options_.workgroup = workgroup;
  options_.password = password;

  std::move(callback).Run(false /* cancel */, parsed_username, workgroup,
                          password);
}

void SmbFsShare::RemoveSavedCredentials(RemoveCredentialsCallback callback) {
  DCHECK(!remove_credentials_callback_);

  if (!host_) {
    std::move(callback).Run(false /* success */);
    return;
  }

  remove_credentials_callback_ = std::move(callback);
  host_->RemoveSavedCredentials(base::BindOnce(
      &SmbFsShare::OnRemoveSavedCredentialsDone, base::Unretained(this)));
}

void SmbFsShare::OnRemoveSavedCredentialsDone(bool success) {
  DCHECK(remove_credentials_callback_);
  std::move(remove_credentials_callback_).Run(success);
}

void SmbFsShare::SetMounterCreationCallbackForTest(
    MounterCreationCallback callback) {
  mounter_creation_callback_for_test_ = std::move(callback);
}

std::string SmbFsShare::GenerateStableMountId() const {
  const auto input = GenerateStableMountIdInput();
  return base::ToLowerASCII(base::HexEncode(crypto::hash::Sha256(input)));
}

std::string SmbFsShare::GenerateStableMountIdInput() const {
  std::vector<std::string> mount_id_hash_components;

  // Shares are unique based on the user the profile is owned by.
  mount_id_hash_components.push_back(
      ProfileHelper::Get()->GetUserIdHashFromProfile(profile_));

  // The hostname in the URL should be that entered by the user or
  // specified in the preconfigured share policy. It should not have
  // been resolved to an IP address if a hostname was specified.
  //
  // This property is true implicitly due to the call path for
  // SmbFsShare creation.
  mount_id_hash_components.push_back(share_url_.ToString());

  // Distinguish between Kerberos and user-supplied credentials.
  mount_id_hash_components.push_back(
      base::NumberToString(options_.kerberos_options ? 1 : 0));

  // Distinguish between domains / workgroups (may be empty for guest or
  // Kerberos).
  mount_id_hash_components.push_back(options_.workgroup);

  // Distinguish between usernames (may be empty for guest or Kerberos).
  mount_id_hash_components.push_back(options_.username);

  return base::JoinString(mount_id_hash_components, kMountIdHashSeparator);
}

}  // namespace ash::smb_client