File: fallback_copy_in_foreign_file.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 (437 lines) | stat: -rw-r--r-- 15,597 bytes parent folder | download | duplicates (5)
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
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "chrome/browser/ash/fileapi/fallback_copy_in_foreign_file.h"

#include <tuple>

#include "base/files/file_error_or.h"
#include "base/files/safe_base_name.h"
#include "base/memory/raw_ref.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/strcat.h"
#include "base/unguessable_token.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "storage/browser/file_system/file_stream_writer.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_operation_runner.h"
#include "storage/browser/file_system/file_system_url.h"
#include "storage/common/file_system/file_system_util.h"

namespace ash {

namespace {

constexpr size_t kBufferSize = 65536;  // 64 KiB.

storage::FileSystemURL CreateTempURL(const storage::FileSystemURL& dest_url) {
  static const char kTempPrefix[] = ".chromium_temp_";

  std::string token = base::UnguessableToken::Create().ToString();
  return dest_url.CreateSibling(*base::SafeBaseName::Create(
      base::FilePath::FromASCII(base::StrCat({kTempPrefix, token}))));
}

// Duplicates a FileSystemOperationContext, returning something (a unique_ptr)
// with independent ownership.
std::unique_ptr<storage::FileSystemOperationContext>
DuplicateFileSystemOperationContext(
    storage::FileSystemOperationContext& original) {
  return std::make_unique<storage::FileSystemOperationContext>(
      original.file_system_context(), original.task_runner());
}

struct FileAndInt {
  base::File file;
  int n;

  FileAndInt(base::File file_arg, int n_arg)
      : file(std::move(file_arg)), n(n_arg) {}
};

// Helps implement FallbackCopyInForeignFile.
//
// It holds the state as the original FallbackCopyInForeignFile call is
// implemented by hopping between TaskRunners as part of Chrome storage's async
// C++ API.
//
// Those callbacks also hop between the original TaskRunner (typically "the IO
// thread" which, despite its name, doesn't allow blocking I/O) and the
// FileSystemOperationContext::task_runner(), which may block.
//
// ----
//
// "Copy in a foreign file (a 'real' kernel-visible file, identified by a
// base::FilePath named src_file_path) to a virtual-file-location (identified
// by a storage::FileSystemURL named dest_url)" is implemented in stages,
// writing the bytes to a temp_url before moving temp_url over dest_url.
//
// temp_url is a sibling (in the FileSystemURL::CreateSibling sense) of the
// dest_url. Its base name joins kTempPrefix and a base::UnguessableToken (a
// 128 bit randomly generated number) in string form.
//
// The stages are:
//
//   1. A new, temporary, virtual file is created at temp_url.
//   2. The src_file_path is opened for reading (as a base::File) and the
//      temp_url is opened for writing (as a storage::FileStreamWriter).
//   3. Repeatedly Read from the source and Write to the temp_url. The loop
//      ends when Read hits EOF (End Of File).
//   4. Flush (if necessary) the FileStreamWriter.
//   5. Rename temp_url to dest_url.
//
// If a stage encounters an error then the remaining stages are not performed.
// Nonetheless, Copier::Finish will be called regardless of failure (early
// exit) or success. Copier::Finish will remove the temp_url virtual file if
// necessary and then run the original callback that was passed to
// FallbackCopyInForeignFile.
//
// ----
//
// The FileStreamWriter is created for temp_url instead of dest_url. The
// indirection minimizes the amount of time that the dest_url virtual file is
// in a partially-written state. Step 3 (the read-write copy loop) can be
// time-consuming and relatively unreliable, if the virtual file system is
// backed by the cloud instead of local disk.
class Copier {
 public:
  Copier(storage::AsyncFileUtil& async_file_util,
         std::unique_ptr<storage::FileSystemOperationContext> context,
         const base::FilePath& src_file_path,
         const storage::FileSystemURL& dest_url);
  ~Copier() = default;

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

  void Start(storage::AsyncFileUtil::StatusCallback callback);

 private:
  void OnEnsureFileExists(base::File::Error result, bool created);

  void OnOpen(base::File file);
  void CallRead();
  void OnRead(base::FileErrorOr<FileAndInt> result);
  void CallWrite(scoped_refptr<net::DrainableIOBuffer> drainable_buffer);
  void OnWrite(scoped_refptr<net::DrainableIOBuffer> drainable_buffer,
               int result);
  void CallFlushIfNecesssary();
  void OnFlush(int result);
  void OnGetFileInfo(base::File::Error result,
                     const base::File::Info& file_info);
  void OnMoveTempToDest(base::File::Error result);

  void Finish(base::File::Error result);

  // Per the async_file_util.h comments, the async_file_util_ reference stays
  // alive as long as the context_ is alive.
  const raw_ref<storage::AsyncFileUtil> async_file_util_;

  // This is the FileSystemOperationContext originally passed to
  // FallbackCopyInForeignFile.
  std::unique_ptr<storage::FileSystemOperationContext> context_;

  const base::FilePath src_file_path_;
  const storage::FileSystemURL dest_url_;
  const storage::FileSystemURL temp_url_;
  storage::AsyncFileUtil::StatusCallback callback_;

  bool temp_url_needs_deleting_;

  scoped_refptr<net::IOBuffer> io_buffer_ GUARDED_BY_CONTEXT(sequence_checker_);

  std::unique_ptr<storage::FileStreamWriter> fs_writer_
      GUARDED_BY_CONTEXT(sequence_checker_);
  base::File file_ GUARDED_BY_CONTEXT(sequence_checker_);

  SEQUENCE_CHECKER(sequence_checker_);
};

Copier::Copier(storage::AsyncFileUtil& async_file_util,
               std::unique_ptr<storage::FileSystemOperationContext> context,
               const base::FilePath& src_file_path,
               const storage::FileSystemURL& dest_url)
    : async_file_util_(async_file_util),
      context_(std::move(context)),
      src_file_path_(src_file_path),
      dest_url_(dest_url),
      temp_url_(CreateTempURL(dest_url)),
      temp_url_needs_deleting_(false),
      io_buffer_(base::MakeRefCounted<net::IOBufferWithSize>(kBufferSize)),
      fs_writer_(nullptr),
      file_(base::File::FILE_ERROR_FAILED) {}

void Copier::Start(storage::AsyncFileUtil::StatusCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (src_file_path_.empty() || !dest_url_.is_valid() ||
      !temp_url_.is_valid()) {
    std::move(callback).Run(base::File::Error::FILE_ERROR_FAILED);
    return;
  }

  callback_ = std::move(callback);

  async_file_util_->EnsureFileExists(
      DuplicateFileSystemOperationContext(*context_), temp_url_,
      base::BindOnce(&Copier::OnEnsureFileExists,
                     // base::Unretained is safe as callback_ owns this.
                     base::Unretained(this)));
}

void Copier::OnEnsureFileExists(base::File::Error result, bool created) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (result != base::File::Error::FILE_OK) {
    Finish(result);
    return;
  }

  temp_url_needs_deleting_ = true;
  fs_writer_ =
      context_->file_system_context()->CreateFileStreamWriter(temp_url_, 0);

  static constexpr auto open_file_off_the_io_thread =
      [](const base::FilePath src_file_path) {
        return base::File(src_file_path,
                          base::File::FLAG_OPEN | base::File::FLAG_READ);
      };

  context_->task_runner()->PostTaskAndReplyWithResult(
      FROM_HERE, base::BindOnce(open_file_off_the_io_thread, src_file_path_),
      base::BindOnce(&Copier::OnOpen,
                     // base::Unretained is safe as callback_ owns this.
                     base::Unretained(this)));
}

void Copier::OnOpen(base::File file) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!file.IsValid()) {
    Finish(base::File::Error::FILE_ERROR_NOT_FOUND);
    return;
  }

  file_ = std::move(file);
  CallRead();
}

void Copier::CallRead() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  static constexpr auto read_file_off_the_io_thread =
      [](scoped_refptr<net::IOBuffer> buffer,
         base::File file) -> base::FileErrorOr<FileAndInt> {
    std::optional<size_t> num_bytes_read =
        file.ReadAtCurrentPosNoBestEffort(buffer->first(kBufferSize));
    if (!num_bytes_read.has_value()) {
      return base::unexpected(base::File::GetLastFileError());
    }
    return FileAndInt(std::move(file),
                      base::checked_cast<int>(num_bytes_read.value()));
  };

  scoped_refptr<net::IOBuffer> buffer = io_buffer_;
  base::File file = std::move(file_);

  context_->task_runner()->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(read_file_off_the_io_thread, std::move(buffer),
                     std::move(file)),
      base::BindOnce(&Copier::OnRead,
                     // base::Unretained is safe as callback_ owns this.
                     base::Unretained(this)));
}

void Copier::OnRead(base::FileErrorOr<FileAndInt> result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!result.has_value()) {
    Finish(result.error());
    return;
  }

  file_ = std::move(result->file);

  if (int num_bytes_read = result->n; num_bytes_read > 0) {
    scoped_refptr<net::DrainableIOBuffer> drainable_buffer =
        base::MakeRefCounted<net::DrainableIOBuffer>(io_buffer_.get(),
                                                     num_bytes_read);
    CallWrite(std::move(drainable_buffer));
  } else {
    CallFlushIfNecesssary();
  }
}

void Copier::CallWrite(scoped_refptr<net::DrainableIOBuffer> drainable_buffer) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  auto pair = base::SplitOnceCallback(
      base::BindOnce(&Copier::OnWrite,
                     // base::Unretained is safe as callback_ owns this.
                     base::Unretained(this), drainable_buffer));

  int write_result = fs_writer_->Write(drainable_buffer.get(),
                                       drainable_buffer->BytesRemaining(),
                                       std::move(pair.first));
  if (write_result != net::ERR_IO_PENDING) {  // The write was synchronous.
    std::move(pair.second).Run(write_result);
  }
}

void Copier::OnWrite(scoped_refptr<net::DrainableIOBuffer> drainable_buffer,
                     int result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (result < 0) {
    Finish(storage::NetErrorToFileError(result));
    return;
  } else if (result > drainable_buffer->BytesRemaining()) {
    NOTREACHED();
  }

  drainable_buffer->DidConsume(result);
  if (drainable_buffer->BytesRemaining() > 0) {
    CallWrite(std::move(drainable_buffer));
    return;
  }

  CallRead();
}

void Copier::CallFlushIfNecesssary() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (temp_url_.mount_option().flush_policy() ==
      storage::FlushPolicy::NO_FLUSH_ON_COMPLETION) {
    OnFlush(net::OK);
    return;
  }

  auto pair = base::SplitOnceCallback(
      base::BindOnce(&Copier::OnFlush,
                     // base::Unretained is safe as callback_ owns this.
                     base::Unretained(this)));

  int flush_result =
      fs_writer_->Flush(storage::FlushMode::kEndOfFile, std::move(pair.first));
  if (flush_result != net::ERR_IO_PENDING) {  // The flush was synchronous.
    std::move(pair.second).Run(flush_result);
  }
}

void Copier::OnFlush(int result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (result < 0) {
    Finish(storage::NetErrorToFileError(result));
    return;
  }

  // Destroying this storage::FileStreamWriter closes the temp_url file. We're
  // about to rename (or delete, on failure) that file, having finished writing
  // and flushing its contents, but some AsyncFileUtil implementations disallow
  // that on files that are still open.
  fs_writer_.reset();

  async_file_util_->GetFileInfo(
      DuplicateFileSystemOperationContext(*context_), dest_url_,
      {storage::FileSystemOperation::GetMetadataField::kIsDirectory},
      base::BindOnce(&Copier::OnGetFileInfo,
                     // base::Unretained is safe as callback_ owns this.
                     base::Unretained(this)));
}

void Copier::OnGetFileInfo(base::File::Error result,
                           const base::File::Info& file_info) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (result == base::File::FILE_ERROR_NOT_FOUND) {
    // No-op. It's OK if the dest_url_ didn't already exist.
  } else if (result != base::File::FILE_OK) {
    Finish(result);
    return;
  } else if (file_info.is_directory) {
    Finish(base::File::FILE_ERROR_NOT_A_FILE);
    return;
  }

  async_file_util_->MoveFileLocal(
      DuplicateFileSystemOperationContext(*context_), temp_url_, dest_url_,
      storage::FileSystemOperation::CopyOrMoveOptionSet(),
      base::BindOnce(&Copier::OnMoveTempToDest,
                     // base::Unretained is safe as callback_ owns this.
                     base::Unretained(this)));
}

void Copier::OnMoveTempToDest(base::File::Error result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  temp_url_needs_deleting_ = (result != base::File::Error::FILE_OK);
  Finish(result);
}

void Copier::Finish(base::File::Error result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!temp_url_needs_deleting_) {
    std::move(callback_).Run(result);
    return;
  }

  // Normally, the storage::FileStreamWriter is created in OnEnsureFileExists
  // and destroyed in OnFlush. However, Finish is still called if an error
  // occurs in between. Just like the fs_writer_.reset() call in OnFlush, we
  // have to call the storage::FileStreamWriter destructor to close the
  // temp_url file before we try to delete that file.
  //
  // If we failed before OnEnsureFileExists or after OnFlush, reset is
  // idempotent. A second reset is harmless.
  fs_writer_.reset();

  async_file_util_->DeleteFile(
      DuplicateFileSystemOperationContext(*context_), temp_url_,
      base::BindOnce(
          [](storage::AsyncFileUtil::StatusCallback callback,
             base::File::Error finish_result,
             base::File::Error delete_file_result) {
            // Ignore delete_file_result. It's like the "-f" in "rm -f". Just
            // run the callback originally passed to FallbackCopyInForeignFile.
            std::move(callback).Run(finish_result);
          },
          std::move(callback_), result));
}

}  // namespace

void FallbackCopyInForeignFile(
    storage::AsyncFileUtil& async_file_util,
    std::unique_ptr<storage::FileSystemOperationContext> context,
    const base::FilePath& src_file_path,
    const storage::FileSystemURL& dest_url,
    storage::AsyncFileUtil::StatusCallback callback) {
  CHECK(context);
  CHECK(callback);

  std::unique_ptr<Copier> copier = std::make_unique<Copier>(
      async_file_util, std::move(context), src_file_path, dest_url);

  // Allows the unique pointer to be bound to the lambda below so the Copier
  // stays alive until the operation completes.
  Copier* raw_copier = copier.get();

  raw_copier->Start(base::BindOnce(
      [](std::unique_ptr<Copier> copier,
         storage::AsyncFileUtil::StatusCallback callback,
         base::File::Error result) { std::move(callback).Run(result); },
      std::move(copier), std::move(callback)));
}

}  // namespace ash