File: fusebox_read_writer.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 (694 lines) | stat: -rw-r--r-- 25,202 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
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
// Copyright 2022 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/fusebox/fusebox_read_writer.h"

#include <fcntl.h>
#include <unistd.h>

#include "base/files/file_util.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/stringprintf.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "chrome/browser/ash/fusebox/fusebox_copy_to_fd.h"
#include "chrome/browser/ash/fusebox/fusebox_errno.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
#include "storage/browser/file_system/file_system_operation_runner.h"

namespace fusebox {

namespace {

void RunFlushCallback(ReadWriter::FlushCallback callback,
                      int posix_error_code) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  FlushResponseProto response_proto;
  if (posix_error_code) {
    response_proto.set_posix_error_code(posix_error_code);
  }
  std::move(callback).Run(response_proto);
}

void RunRead2CallbackFailure(ReadWriter::Read2Callback callback,
                             base::File::Error error_code) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  Read2ResponseProto response_proto;
  response_proto.set_posix_error_code(FileErrorToErrno(error_code));
  std::move(callback).Run(response_proto);
}

void RunRead2CallbackTypical(ReadWriter::Read2Callback callback,
                             scoped_refptr<net::IOBuffer> buffer,
                             int length) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  Read2ResponseProto response_proto;
  if (length < 0) {
    response_proto.set_posix_error_code(NetErrorToErrno(length));
  } else {
    *response_proto.mutable_data() = std::string(buffer->data(), length);
  }
  std::move(callback).Run(response_proto);

  content::GetIOThreadTaskRunner({})->ReleaseSoon(FROM_HERE, std::move(buffer));
}

void RunWrite2CallbackFailure(ReadWriter::Write2Callback callback,
                              int posix_error_code) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  Write2ResponseProto response_proto;
  response_proto.set_posix_error_code(posix_error_code);
  std::move(callback).Run(response_proto);
}

void RunWrite2CallbackTypical(ReadWriter::Write2Callback callback, int length) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  Write2ResponseProto response_proto;
  if (length < 0) {
    response_proto.set_posix_error_code(NetErrorToErrno(length));
  }
  std::move(callback).Run(response_proto);
}

ReadWriter::WriteTempFileResult WriteTempFile(
    base::ScopedFD&& scoped_fd,
    scoped_refptr<net::StringIOBuffer> buffer,
    int64_t offset,
    int length) {
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);

  int fd = scoped_fd.get();
  char* ptr = buffer->data();
  if ((HANDLE_EINTR(lseek(fd, static_cast<off_t>(offset), SEEK_SET)) == -1) ||
      (HANDLE_EINTR(write(fd, ptr, static_cast<size_t>(length))) == -1)) {
    return std::make_pair(std::move(scoped_fd), errno);
  }
  return std::make_pair(std::move(scoped_fd), 0);
}

void SaveCallback2(base::ScopedFD scoped_fd,
                   scoped_refptr<storage::FileSystemContext> fs_context,
                   ReadWriter::Close2Callback callback,
                   base::File::Error file_error) {
  Close2ResponseProto response_proto;
  if (file_error != base::File::Error::FILE_OK) {
    response_proto.set_posix_error_code(FileErrorToErrno(file_error));
  }
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), response_proto));
}

void SaveCallback1(const std::string src_path,
                   storage::FileSystemURL fs_url,
                   base::ScopedFD scoped_fd,
                   scoped_refptr<storage::FileSystemContext> fs_context,
                   ReadWriter::Close2Callback callback,
                   base::File::Error file_error) {
  // Ignore file_error. We're essentially doing "/usr/bin/rm -f" instead
  // of a bare "/usr/bin/rm".

  fs_context->operation_runner()->CopyInForeignFile(
      base::FilePath(src_path), fs_url,
      base::BindOnce(&SaveCallback2, std::move(scoped_fd), fs_context,
                     std::move(callback)));
}

using EOFFlushFsWriterCallback = base::OnceCallback<void(
    std::unique_ptr<storage::FileStreamWriter> fs_writer,
    int posix_error_code)>;

// Calls fs_writer->Flush(kEndOfFile), running the callback afterwards, if
// needs_eof_flushing is true. If false, it just runs the callback immediately.
//
// The fs_writer and write_offset are passed through to the callback.
void EOFFlushFsWriterIfNecessary(
    std::unique_ptr<storage::FileStreamWriter> fs_writer,
    int64_t write_offset,
    bool needs_eof_flushing,
    EOFFlushFsWriterCallback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  if (!fs_writer || !needs_eof_flushing) {
    std::move(callback).Run(std::move(fs_writer), 0);
    return;
  }

  // Save the pointer before we std::move fs_writer into a base::OnceCallback.
  // The std::move keeps the underlying storage::FileStreamWriter alive while
  // any network I/O is pending. Without the std::move, the underlying
  // storage::FileStreamWriter would get destroyed at the end of this function.
  storage::FileStreamWriter* fs_writer_ptr = fs_writer.get();

  auto pair = base::SplitOnceCallback(base::BindOnce(
      [](std::unique_ptr<storage::FileStreamWriter> fs_writer,
         int64_t write_offset, EOFFlushFsWriterCallback callback, int result) {
        int posix_error_code = (result < 0) ? NetErrorToErrno(result) : 0;
        std::move(callback).Run(std::move(fs_writer), posix_error_code);
      },
      std::move(fs_writer), write_offset, std::move(callback)));

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

}  // namespace

ReadWriter::ReadWriter(const storage::FileSystemURL& fs_url,
                       const std::string& profile_path,
                       bool use_temp_file,
                       bool temp_file_starts_with_copy)
    : fs_url_(fs_url),
      profile_path_(profile_path),
      use_temp_file_(use_temp_file),
      temp_file_starts_with_copy_(temp_file_starts_with_copy) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
}

ReadWriter::~ReadWriter() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
}

// Some functions (marked with a §) below, take an fs_context argument that
// looks unused, but we need to keep the storage::FileSystemContext reference
// alive until the callbacks are run.

void ReadWriter::Close(scoped_refptr<storage::FileSystemContext> fs_context,
                       Close2Callback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  if (closed_) {
    Close2ResponseProto response_proto;
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }
  closed_ = true;

  EOFFlushFsWriterIfNecessary(
      std::move(fs_writer_), std::exchange(write_offset_, -1),
      std::exchange(fs_writer_needs_eof_flushing_, false),
      base::BindOnce(&ReadWriter::OnEOFFlushBeforeActualClose,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(fs_context)));
}

// static
void ReadWriter::OnEOFFlushBeforeActualClose(
    base::WeakPtr<ReadWriter> weak_ptr,
    Close2Callback callback,
    scoped_refptr<storage::FileSystemContext> fs_context,
    std::unique_ptr<storage::FileStreamWriter> fs_writer,
    int flush_posix_error_code) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!self) {
    flush_posix_error_code = EBUSY;
  }
  if (flush_posix_error_code) {
    Close2ResponseProto response_proto;
    response_proto.set_posix_error_code(flush_posix_error_code);
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }

  if (!self->use_temp_file_) {
    Close2ResponseProto response_proto;
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }

  self->close2_fs_context_ = std::move(fs_context);
  self->close2_callback_ = std::move(callback);
  if (!self->is_loaning_temp_file_scoped_fd_) {
    self->Save();
  }
}

void ReadWriter::Save() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  DCHECK(close2_fs_context_);
  DCHECK(close2_callback_);
  DCHECK(!is_loaning_temp_file_scoped_fd_);
  DCHECK(use_temp_file_);

  if (write_posix_error_code_ != 0) {
    Close2ResponseProto response_proto;
    response_proto.set_posix_error_code(write_posix_error_code_);
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(close2_callback_), response_proto));
    return;
  }

  std::string src_path =
      created_temp_file_
          ? base::StringPrintf("/proc/self/fd/%d", temp_file_.get())
          : "/dev/null";

  // Delete the file if it already it exists, or a no-op if it doesn't. Either
  // way, SaveCallback1 will then copy from src_path to fs_url_, before
  // SaveCallback2 runs the close2_callback_.
  close2_fs_context_->operation_runner()->RemoveFile(
      fs_url_,
      base::BindOnce(&SaveCallback1, src_path, fs_url_, std::move(temp_file_),
                     close2_fs_context_, std::move(close2_callback_)));
}

void ReadWriter::Flush(scoped_refptr<storage::FileSystemContext> fs_context,
                       FlushCallback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  DCHECK(!is_in_flight_);
  is_in_flight_ = true;

  if (closed_) {
    is_in_flight_ = false;
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE,
        base::BindOnce(&RunFlushCallback, std::move(callback), EFAULT));
    return;
  }

  if (use_temp_file_ || !fs_writer_) {
    is_in_flight_ = false;
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(&RunFlushCallback, std::move(callback), 0));
    return;
  }

  auto pair = base::SplitOnceCallback(base::BindOnce(
      &ReadWriter::OnDefaultFlush, weak_ptr_factory_.GetWeakPtr(),
      std::move(callback), fs_context));

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

void ReadWriter::Read(scoped_refptr<storage::FileSystemContext> fs_context,
                      int64_t offset,
                      int64_t length,
                      Read2Callback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  DCHECK(!is_in_flight_);
  is_in_flight_ = true;

  if (closed_) {
    is_in_flight_ = false;
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(&RunRead2CallbackFailure, std::move(callback),
                                  base::File::Error::FILE_ERROR_FAILED));
    return;
  }

  // See if we can re-use the previous storage::FileStreamReader.
  std::unique_ptr<storage::FileStreamReader> fs_reader;
  if (fs_reader_ && (read_offset_ == offset)) {
    fs_reader = std::move(fs_reader_);
    read_offset_ = -1;
  } else {
    fs_reader = fs_context->CreateFileStreamReader(fs_url_, offset, INT64_MAX,
                                                   base::Time());
    if (!fs_reader) {
      is_in_flight_ = false;
      content::GetUIThreadTaskRunner({})->PostTask(
          FROM_HERE,
          base::BindOnce(&RunRead2CallbackFailure, std::move(callback),
                         base::File::Error::FILE_ERROR_INVALID_URL));
      return;
    }
  }

  constexpr int64_t min_length = 256;
  constexpr int64_t max_length = 262144;  // 256 KiB.
  auto buffer = base::MakeRefCounted<net::IOBufferWithSize>(
      std::max(min_length, std::min(max_length, length)));

  // Save the pointer before we std::move fs_reader into a base::OnceCallback.
  // The std::move keeps the underlying storage::FileStreamReader alive while
  // any network I/O is pending. Without the std::move, the underlying
  // storage::FileStreamReader would get destroyed at the end of this function.
  auto* saved_fs_reader = fs_reader.get();

  auto pair = base::SplitOnceCallback(base::BindOnce(
      &ReadWriter::OnRead, weak_ptr_factory_.GetWeakPtr(), std::move(callback),
      fs_context, std::move(fs_reader), buffer, offset));

  int result =
      saved_fs_reader->Read(buffer.get(), length, std::move(pair.first));
  if (result != net::ERR_IO_PENDING) {  // The read was synchronous.
    std::move(pair.second).Run(result);
  }
}

// static
void ReadWriter::OnRead(
    base::WeakPtr<ReadWriter> weak_ptr,
    Read2Callback callback,
    scoped_refptr<storage::FileSystemContext> fs_context,  // See § above.
    std::unique_ptr<storage::FileStreamReader> fs_reader,
    scoped_refptr<net::IOBuffer> buffer,
    int64_t offset,
    int length) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!self) {
    Read2ResponseProto response_proto;
    response_proto.set_posix_error_code(EBUSY);
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }

  DCHECK(self->is_in_flight_);
  self->is_in_flight_ = false;

  if (length >= 0) {
    self->fs_reader_ = std::move(fs_reader);
    self->read_offset_ = offset + length;
  } else {
    self->fs_reader_.reset();
    self->read_offset_ = -1;
  }

  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&RunRead2CallbackTypical, std::move(callback),
                                std::move(buffer), length));
}

void ReadWriter::Write(scoped_refptr<storage::FileSystemContext> fs_context,
                       scoped_refptr<net::StringIOBuffer> buffer,
                       int64_t offset,
                       int length,
                       Write2Callback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  DCHECK(!is_in_flight_);
  is_in_flight_ = true;

  if (closed_ || (write_posix_error_code_ != 0)) {
    is_in_flight_ = false;
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE,
        base::BindOnce(&RunWrite2CallbackFailure, std::move(callback),
                       closed_ ? EFAULT : write_posix_error_code_));
    return;
  }

  if (use_temp_file_) {
    if (!temp_file_.is_valid()) {
      // Create the temporary file via open and O_TMPFILE, instead of
      // base::CreateTemporaryFile, to simplify clean-up. With the latter,
      // there is a garbage collection problem of when to delete no-longer-used
      // files (as base::File::DeleteOnClose is Windows only). That problem can
      // be tricky if Chrome crashes before we're done with the temporary file.
      // With O_TMPFILE, the kernel deletes the file automatically when the
      // file descriptor is closed, whether via base::ScopedFD destructor or,
      // for crashes, at process exit.
      temp_file_.reset(open(profile_path_.c_str(),
                            O_CLOEXEC | O_EXCL | O_TMPFILE | O_RDWR, 0600));
      if (!temp_file_.is_valid()) {
        PLOG(WARNING) << "could not create O_TMPFILE file";
        is_in_flight_ = false;
        content::GetUIThreadTaskRunner({})->PostTask(
            FROM_HERE, base::BindOnce(&RunWrite2CallbackFailure,
                                      std::move(callback), ENOSPC));
        return;
      }
      created_temp_file_ = true;
      if (temp_file_starts_with_copy_) {
        auto outer_callback = base::BindOnce(
            OnTempFileInitialized, weak_ptr_factory_.GetWeakPtr(),
            std::move(buffer), offset, length, std::move(callback));
        is_loaning_temp_file_scoped_fd_ = true;
        CopyToFileDescriptor(fs_context, fs_url_, std::move(temp_file_),
                             std::move(outer_callback));
        return;
      }
    }

    CallWriteTempFile(weak_ptr_factory_.GetWeakPtr(), std::move(buffer), offset,
                      length, std::move(callback));
    return;
  }

  // See if we can re-use the previous storage::FileStreamWriter.
  //
  // If so, go on to CallWriteDirect immediately. Otherwise, go on to
  // EOFFlushFsWriterIfNecessary, OnEOFFlushBeforeCallWriteDirect and then
  // CallWriteDirect.
  if (fs_writer_ && (write_offset_ == offset)) {
    CallWriteDirect(std::move(callback), std::move(fs_context),
                    std::move(fs_writer_), std::move(buffer),
                    std::exchange(write_offset_, -1), length);
    return;
  }

  // We will need a new storage::FileStreamWriter, so destroy the previous one
  // saved to fs_writer_, if it is non-null. However, we might need to Flush it
  // (with FlushMode::kEndOfFile) before destroying it.
  //
  // Calling EOFFlushFsWriterIfNecessary, with std::move(fs_writer_) and with
  // OnEOFFlushBeforeCallWriteDirect, will Flush (if needed) and destroy that
  // FileStreamWriter (positioned at write_offset_), if it is non-null.
  //
  // Afterwards, OnEOFFlushBeforeCallWriteDirect creates a new FileStreamWriter
  // (positioned at offset) and passes that on to CallWriteDirect.
  EOFFlushFsWriterIfNecessary(
      std::move(fs_writer_), std::exchange(write_offset_, -1),
      std::exchange(fs_writer_needs_eof_flushing_, false),
      base::BindOnce(&ReadWriter::OnEOFFlushBeforeCallWriteDirect,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(fs_context), std::move(buffer), offset, length));
}

// static
void ReadWriter::OnTempFileInitialized(
    base::WeakPtr<ReadWriter> weak_ptr,
    scoped_refptr<net::StringIOBuffer> buffer,
    int64_t offset,
    int length,
    Write2Callback callback,
    base::expected<base::ScopedFD, int> result) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!result.has_value() || !self) {
    if (self) {
      self->is_in_flight_ = false;
    }
    Write2ResponseProto response_proto;
    response_proto.set_posix_error_code(result.error_or(EBUSY));
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }

  self->is_loaning_temp_file_scoped_fd_ = false;
  self->temp_file_ = std::move(result.value());
  CallWriteTempFile(std::move(weak_ptr), std::move(buffer), offset, length,
                    std::move(callback));
}

// static
void ReadWriter::CallWriteTempFile(base::WeakPtr<ReadWriter> weak_ptr,
                                   scoped_refptr<net::StringIOBuffer> buffer,
                                   int64_t offset,
                                   int length,
                                   Write2Callback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!self) {
    Write2ResponseProto response_proto;
    response_proto.set_posix_error_code(EBUSY);
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }

  self->is_loaning_temp_file_scoped_fd_ = true;
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock()},
      base::BindOnce(&WriteTempFile, std::move(self->temp_file_),
                     std::move(buffer), offset, length),
      base::BindOnce(&OnWriteTempFile, std::move(weak_ptr),
                     std::move(callback)));
}

// static
void ReadWriter::OnWriteTempFile(base::WeakPtr<ReadWriter> weak_ptr,
                                 Write2Callback callback,
                                 WriteTempFileResult result) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!self) {
    Write2ResponseProto response_proto;
    response_proto.set_posix_error_code(EBUSY);
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }

  DCHECK(self->is_in_flight_);
  self->is_in_flight_ = false;
  self->is_loaning_temp_file_scoped_fd_ = false;

  self->temp_file_ = std::move(result.first);

  Write2ResponseProto response_proto;
  if (result.second) {
    response_proto.set_posix_error_code(result.second);
    self->write_posix_error_code_ = result.second;
  }
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), response_proto));

  if (self->close2_callback_) {
    self->Save();
  }
}

// static
void ReadWriter::OnDefaultFlush(
    base::WeakPtr<ReadWriter> weak_ptr,
    FlushCallback callback,
    scoped_refptr<storage::FileSystemContext> fs_context,  // See § above.
    int flush_posix_error_code) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!self) {
    flush_posix_error_code = EBUSY;
  } else {
    self->is_in_flight_ = false;
  }
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&RunFlushCallback, std::move(callback),
                                flush_posix_error_code));
}

// static
void ReadWriter::OnEOFFlushBeforeCallWriteDirect(
    base::WeakPtr<ReadWriter> weak_ptr,
    Write2Callback callback,
    scoped_refptr<storage::FileSystemContext> fs_context,  // See § above.
    scoped_refptr<net::IOBuffer> buffer,
    int64_t offset,
    int length,
    std::unique_ptr<storage::FileStreamWriter> fs_writer,
    int flush_posix_error_code) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!self) {
    flush_posix_error_code = EBUSY;
  }
  if (flush_posix_error_code) {
    if (self) {
      self->is_in_flight_ = false;
    }
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(&RunWrite2CallbackFailure,
                                  std::move(callback), flush_posix_error_code));
    return;
  }

  fs_writer = fs_context->CreateFileStreamWriter(self->fs_url_, offset);
  if (!fs_writer) {
    self->is_in_flight_ = false;
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE,
        base::BindOnce(&RunWrite2CallbackFailure, std::move(callback), EINVAL));
    return;
  }

  self->CallWriteDirect(std::move(callback), std::move(fs_context),
                        std::move(fs_writer), std::move(buffer), offset,
                        length);
}

void ReadWriter::CallWriteDirect(
    Write2Callback callback,
    scoped_refptr<storage::FileSystemContext> fs_context,  // See § above.
    std::unique_ptr<storage::FileStreamWriter> fs_writer,
    scoped_refptr<net::IOBuffer> buffer,
    int64_t offset,
    int length) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  // Save the pointer before we std::move fs_writer into a base::OnceCallback.
  // The std::move keeps the underlying storage::FileStreamWriter alive while
  // any network I/O is pending. Without the std::move, the underlying
  // storage::FileStreamWriter would get destroyed at the end of this function.
  auto* saved_fs_writer = fs_writer.get();

  auto pair = base::SplitOnceCallback(base::BindOnce(
      &ReadWriter::OnWriteDirect, weak_ptr_factory_.GetWeakPtr(),
      std::move(callback), fs_context, std::move(fs_writer), buffer, offset));

  int result =
      saved_fs_writer->Write(buffer.get(), length, std::move(pair.first));
  if (result != net::ERR_IO_PENDING) {  // The write was synchronous.
    std::move(pair.second).Run(result);
  }
}

// static
void ReadWriter::OnWriteDirect(
    base::WeakPtr<ReadWriter> weak_ptr,
    Write2Callback callback,
    scoped_refptr<storage::FileSystemContext> fs_context,  // See § above.
    std::unique_ptr<storage::FileStreamWriter> fs_writer,
    scoped_refptr<net::IOBuffer> buffer,
    int64_t offset,
    int length) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  ReadWriter* self = weak_ptr.get();
  if (!self) {
    Write2ResponseProto response_proto;
    response_proto.set_posix_error_code(EBUSY);
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), response_proto));
    return;
  }

  DCHECK(self->is_in_flight_);
  self->is_in_flight_ = false;

  if (length >= 0) {
    self->fs_writer_ = std::move(fs_writer);
    self->write_offset_ = offset + length;
    self->fs_writer_needs_eof_flushing_ =
        self->fs_writer_needs_eof_flushing_ ||
        (self->fs_url_.mount_option().flush_policy() ==
         storage::FlushPolicy::FLUSH_ON_COMPLETION);
  } else {
    self->fs_writer_.reset();
    self->write_offset_ = -1;
    self->write_posix_error_code_ = NetErrorToErrno(length);
  }

  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(&RunWrite2CallbackTypical, std::move(callback), length));
}

}  // namespace fusebox