File: crostini_sshfs.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 (250 lines) | stat: -rw-r--r-- 9,844 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
// Copyright 2021 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/crostini/crostini_sshfs.h"

#include <inttypes.h>

#include <memory>
#include <utility>

#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/scoped_observation.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chrome/browser/ash/crostini/crostini_manager.h"
#include "chrome/browser/ash/crostini/crostini_manager_factory.h"
#include "chrome/browser/ash/crostini/crostini_util.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/ash/file_manager/volume_manager.h"
#include "chrome/browser/ash/guest_os/guest_os_session_tracker.h"
#include "chrome/browser/ash/guest_os/guest_os_session_tracker_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chromeos/ash/components/dbus/cros_disks/cros_disks_client.h"
#include "content/public/browser/browser_thread.h"
#include "storage/browser/file_system/external_mount_points.h"

namespace crostini {

CrostiniSshfs::CrostiniSshfs(Profile* profile) : profile_(profile) {}

CrostiniSshfs::~CrostiniSshfs() = default;

void CrostiniSshfs::OnContainerShutdown(const guest_os::GuestId& container_id) {
  container_shutdown_observer_.Reset();
  SetSshfsMounted(container_id, false);
}

bool CrostiniSshfs::IsSshfsMounted(const guest_os::GuestId& container) {
  return (sshfs_mounted_.count(container));
}

void CrostiniSshfs::SetSshfsMounted(const guest_os::GuestId& container,
                                    bool mounted) {
  if (mounted) {
    sshfs_mounted_.emplace(container);
  } else {
    sshfs_mounted_.erase(container);
  }
}

void CrostiniSshfs::UnmountCrostiniFiles(const guest_os::GuestId& container_id,
                                         MountCrostiniFilesCallback callback) {
  // TODO(crbug.com/40760488): Unmounting should cancel an in-progress mount.
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  auto* vmgr = file_manager::VolumeManager::Get(profile_);
  if (vmgr) {
    // vmgr is NULL in unit tests if not overridden.
    vmgr->RemoveSshfsCrostiniVolume(
        file_manager::util::GetCrostiniMountDirectory(profile_),
        base::BindOnce(&CrostiniSshfs::OnRemoveSshfsCrostiniVolume,
                       weak_ptr_factory_.GetWeakPtr(), container_id,
                       std::move(callback), base::Time::Now()));
  } else {
    OnRemoveSshfsCrostiniVolume(container_id, std::move(callback),
                                base::Time::Now(), true);
  }
}

void CrostiniSshfs::OnRemoveSshfsCrostiniVolume(
    const guest_os::GuestId& container_id,
    MountCrostiniFilesCallback callback,
    base::Time started,
    bool success) {
  container_shutdown_observer_.Reset();
  SetSshfsMounted(container_id, false);
  base::UmaHistogramTimes("Crostini.Sshfs.Unmount.TimeTaken",
                          base::Time::Now() - started);
  base::UmaHistogramBoolean("Crostini.Sshfs.Unmount.Result", success);
  std::move(callback).Run(success);
}

void CrostiniSshfs::MountCrostiniFiles(const guest_os::GuestId& container_id,
                                       MountCrostiniFilesCallback callback,
                                       bool background) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (in_progress_mount_) {
    // A run is already in progress, wait until it finishes.
    pending_requests_.emplace(container_id, std::move(callback), background);
    return;
  }
  in_progress_mount_ = std::make_unique<InProgressMount>(
      container_id, std::move(callback), background);

  if (IsSshfsMounted(container_id)) {
    // Already mounted so skip straight to reporting success.
    Finish(CrostiniSshfsResult::kSuccess);
    return;
  }

  if (container_id != DefaultContainerId()) {
    LOG(ERROR) << "Unable to mount files for non-default container";
    Finish(CrostiniSshfsResult::kNotDefaultContainer);
    return;
  }

  bool running = guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_)
                     ->IsRunning(in_progress_mount_->container_id);
  if (!running) {
    LOG(ERROR) << "Unable to mount files for a container that's not running";
    Finish(CrostiniSshfsResult::kContainerNotRunning);
    return;
  }

  auto info =
      guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_)->GetInfo(
          in_progress_mount_->container_id);
  if (!info) {
    LOG(ERROR) << "Got ssh keys for a container that's not running. Aborting.";
    Finish(CrostiniSshfsResult::kGetContainerInfoFailed);
    return;
  }

  // Add ourselves as an observer so we can continue once the path is mounted.
  auto* dmgr = ash::disks::DiskMountManager::GetInstance();

  if (info->sftp_vsock_port != 0) {
    in_progress_mount_->source_path = base::StringPrintf(
        "sftp://%" PRId64 ":%u", info->cid, info->sftp_vsock_port);
  } else {
    LOG(ERROR) << "Container has no sftp vsock port";
    Finish(CrostiniSshfsResult::kGetContainerInfoFailed);
    return;
  }
  in_progress_mount_->container_homedir = info->homedir;

  dmgr->MountPath(in_progress_mount_->source_path, "",
                  file_manager::util::GetCrostiniMountPointName(profile_), {},
                  ash::MountType::kNetworkStorage,
                  ash::MountAccessMode::kReadWrite,
                  base::BindOnce(&CrostiniSshfs::OnMountEvent,
                                 weak_ptr_factory_.GetWeakPtr()));
}

void CrostiniSshfs::OnMountEvent(
    ash::MountError error_code,
    const ash::disks::DiskMountManager::MountPoint& mount_info) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (error_code != ash::MountError::kSuccess) {
    LOG(ERROR) << "Error mounting crostini container: error_code=" << error_code
               << ", source_path=" << mount_info.source_path
               << ", mount_path=" << mount_info.mount_path
               << ", mount_type=" << mount_info.mount_type
               << ", mount_error=" << mount_info.mount_error;
    switch (error_code) {
      case ash::MountError::kInternalError:
        Finish(CrostiniSshfsResult::kMountErrorInternal);
        return;
      case ash::MountError::kMountProgramFailed:
        Finish(CrostiniSshfsResult::kMountErrorProgramFailed);
        return;
      default:
        Finish(CrostiniSshfsResult::kMountErrorOther);
        return;
    }
  }

  base::FilePath mount_path = base::FilePath(mount_info.mount_path);
  if (!storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
          file_manager::util::GetCrostiniMountPointName(profile_),
          storage::kFileSystemTypeLocal, storage::FileSystemMountOption(),
          mount_path)) {
    // We don't revoke the filesystem on unmount and this call fails if a
    // filesystem of the same name already exists, so ignore errors.
    // TODO(crbug.com/40760488): Should we revoke? Keeping it this way for now
    // since that's how it's been for years and it's not come up as an issue
    // before. Since the most common reason for unmounting is to work around an
    // issue with suspend/resume where we promptly remount it's probably good
    // this way.
  }

  auto* vmgr = file_manager::VolumeManager::Get(profile_);
  if (vmgr) {
    // vmgr is NULL in unit tests if not overridden.
    vmgr->AddSshfsCrostiniVolume(mount_path,
                                 in_progress_mount_->container_homedir);
  }

  auto* manager = CrostiniManagerFactory::GetForProfile(profile_);
  container_shutdown_observer_.Observe(manager);
  SetSshfsMounted(in_progress_mount_->container_id, true);
  Finish(CrostiniSshfsResult::kSuccess);
}

void CrostiniSshfs::Finish(CrostiniSshfsResult result) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(in_progress_mount_);
  auto callback = std::move(in_progress_mount_->callback);
  base::UmaHistogramTimes("Crostini.Sshfs.Mount.TimeTaken",
                          base::Time::Now() - in_progress_mount_->started);
  if (in_progress_mount_->background) {
    base::UmaHistogramEnumeration("Crostini.Sshfs.Mount.Result.Background",
                                  result);
  } else {
    base::UmaHistogramEnumeration("Crostini.Sshfs.Mount.Result.UserVisible",
                                  result);
  }

  std::move(callback).Run(result == CrostiniSshfsResult::kSuccess);
  in_progress_mount_.reset();
  if (!pending_requests_.empty()) {
    auto next = std::move(pending_requests_.front());
    pending_requests_.pop();
    MountCrostiniFiles(next.container_id, std::move(next.callback),
                       next.background);
  }
}

CrostiniSshfs::InProgressMount::InProgressMount(
    const guest_os::GuestId& container,
    MountCrostiniFilesCallback callback,
    bool background)
    : container_id(container),
      callback(std::move(callback)),
      started(base::Time::Now()),
      background(background) {}
CrostiniSshfs::InProgressMount::InProgressMount(
    InProgressMount&& other) noexcept = default;
CrostiniSshfs::InProgressMount& CrostiniSshfs::InProgressMount::operator=(
    CrostiniSshfs::InProgressMount&& other) noexcept = default;
CrostiniSshfs::InProgressMount::~InProgressMount() = default;

CrostiniSshfs::PendingRequest::PendingRequest(
    const guest_os::GuestId& container_id,
    MountCrostiniFilesCallback callback,
    bool background)
    : container_id(container_id),
      callback(std::move(callback)),
      background(background) {}
CrostiniSshfs::PendingRequest::PendingRequest(PendingRequest&& other) noexcept =
    default;
CrostiniSshfs::PendingRequest& CrostiniSshfs::PendingRequest::operator=(
    CrostiniSshfs::PendingRequest&& other) noexcept = default;
CrostiniSshfs::PendingRequest::~PendingRequest() = default;

}  // namespace crostini