File: network_fetcher_mac.mm

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 (921 lines) | stat: -rw-r--r-- 36,839 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
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
// 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.

#import <Foundation/Foundation.h>

#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <utility>

#import "base/apple/foundation_util.h"
#include "base/containers/flat_map.h"
#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/process/process.h"
#include "base/sequence_checker.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/task/bind_post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "chrome/updater/constants.h"
#include "chrome/updater/event_logger.h"
#include "chrome/updater/net/fallback_net_fetcher.h"
#include "chrome/updater/net/fetcher_callback_adapter.h"
#include "chrome/updater/net/mac/mojom/updater_fetcher.mojom.h"
#include "chrome/updater/net/network.h"
#include "chrome/updater/net/network_file_fetcher.h"
#include "chrome/updater/policy/service.h"
#include "chrome/updater/protos/omaha_usage_stats_event.pb.h"
#include "chrome/updater/util/util.h"
#include "components/update_client/network.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/system/invitation.h"
#include "mojo/public/cpp/system/message_pipe.h"
#import "net/base/apple/url_conversions.h"
#include "url/gurl.h"

using ResponseStartedCallback =
    ::update_client::NetworkFetcher::ResponseStartedCallback;
using ProgressCallback = ::update_client::NetworkFetcher::ProgressCallback;
using PostRequestCompleteCallback =
    ::update_client::NetworkFetcher::PostRequestCompleteCallback;
using DownloadToFileCompleteCallback =
    ::update_client::NetworkFetcher::DownloadToFileCompleteCallback;

@interface CRUUpdaterNetworkController : NSObject <NSURLSessionDelegate>
- (instancetype)initWithResponseStartedCallback:
                    (ResponseStartedCallback)responseStartedCallback
                               progressCallback:
                                   (ProgressCallback)progressCallback;
@end

@implementation CRUUpdaterNetworkController {
 @protected
  ResponseStartedCallback _responseStartedCallback;
  ProgressCallback _progressCallback;
  scoped_refptr<base::SequencedTaskRunner> _callbackRunner;
}

- (instancetype)initWithResponseStartedCallback:
                    (ResponseStartedCallback)responseStartedCallback
                               progressCallback:
                                   (ProgressCallback)progressCallback {
  if (self = [super init]) {
    _responseStartedCallback = std::move(responseStartedCallback);
    _progressCallback = progressCallback;
    _callbackRunner = base::SequencedTaskRunner::GetCurrentDefault();
  }
  return self;
}

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession*)session
                    task:(NSURLSessionTask*)task
    didCompleteWithError:(NSError*)error {
  if (error) {
    DLOG(ERROR) << "NSURLSession error: " << error
                << ". NSURLSession: " << session
                << ". NSURLSessionTask: " << task;
  }
}
@end

@interface CRUUpdaterNetworkDataDelegate
    : CRUUpdaterNetworkController <NSURLSessionDataDelegate>
- (instancetype)
    initWithResponseStartedCallback:
        (ResponseStartedCallback)responseStartedCallback
                   progressCallback:(ProgressCallback)progressCallback
        postRequestCompleteCallback:
            (PostRequestCompleteCallback)postRequestCompleteCallback;
@end

@implementation CRUUpdaterNetworkDataDelegate {
  PostRequestCompleteCallback _postRequestCompleteCallback;
  NSMutableData* __strong _downloadedData;
}

- (instancetype)
    initWithResponseStartedCallback:
        (ResponseStartedCallback)responseStartedCallback
                   progressCallback:(ProgressCallback)progressCallback
        postRequestCompleteCallback:
            (PostRequestCompleteCallback)postRequestCompleteCallback {
  if (self = [super
          initWithResponseStartedCallback:std::move(responseStartedCallback)
                         progressCallback:progressCallback]) {
    _postRequestCompleteCallback = std::move(postRequestCompleteCallback);
    _downloadedData = [[NSMutableData alloc] init];
  }
  return self;
}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession*)session
          dataTask:(NSURLSessionDataTask*)dataTask
    didReceiveData:(NSData*)data {
  [_downloadedData appendData:data];
  _callbackRunner->PostTask(
      FROM_HERE,
      base::BindOnce(_progressCallback, dataTask.countOfBytesReceived));
  [dataTask resume];
}

// Tells the delegate that the data task received the initial reply (headers)
// from the server.
- (void)URLSession:(NSURLSession*)session
              dataTask:(NSURLSessionDataTask*)dataTask
    didReceiveResponse:(NSURLResponse*)response
     completionHandler:
         (void (^)(NSURLSessionResponseDisposition))completionHandler {
  _callbackRunner->PostTask(
      FROM_HERE, base::BindOnce(std::move(_responseStartedCallback),
                                [(NSHTTPURLResponse*)response statusCode],
                                dataTask.countOfBytesExpectedToReceive));
  if (completionHandler) {
    completionHandler(NSURLSessionResponseAllow);
  }
  [dataTask resume];
}

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession*)session
                    task:(NSURLSessionTask*)task
    didCompleteWithError:(NSError*)error {
  [super URLSession:session task:task didCompleteWithError:error];

  NSHTTPURLResponse* response = (NSHTTPURLResponse*)task.response;
  NSDictionary* headers = response.allHeaderFields;

  NSString* headerEtag =
      base::SysUTF8ToNSString(update_client::NetworkFetcher::kHeaderEtag);
  NSString* etag = @"";
  if ([headers objectForKey:headerEtag]) {
    etag = [headers objectForKey:headerEtag];
  }
  NSString* headerXCupServerProof = base::SysUTF8ToNSString(
      update_client::NetworkFetcher::kHeaderXCupServerProof);
  NSString* cupServerProof = @"";
  if ([headers objectForKey:headerXCupServerProof]) {
    cupServerProof = [headers objectForKey:headerXCupServerProof];
  }
  NSString* headerSetCookie =
      base::SysUTF8ToNSString(update_client::NetworkFetcher::kHeaderSetCookie);
  NSString* setCookie = @"";
  if ([headers objectForKey:headerSetCookie]) {
    setCookie = [headers objectForKey:headerSetCookie];
  }

  int64_t retryAfterResult = -1;
  NSString* xRetryAfter = [headers
      objectForKey:base::SysUTF8ToNSString(
                       update_client::NetworkFetcher::kHeaderXRetryAfter)];
  if (xRetryAfter) {
    retryAfterResult = [xRetryAfter intValue];
  }

  _callbackRunner->PostTask(
      FROM_HERE,
      base::BindOnce(
          std::move(_postRequestCompleteCallback),
          std::string(reinterpret_cast<const char*>([_downloadedData bytes]),
                      [_downloadedData length]),
          error.code, base::SysNSStringToUTF8(etag),
          base::SysNSStringToUTF8(cupServerProof),
          base::SysNSStringToUTF8(setCookie), retryAfterResult));
}

@end

@interface CRUUpdaterNetworkDownloadDelegate
    : CRUUpdaterNetworkController <NSURLSessionDownloadDelegate>
- (instancetype)
    initWithResponseStartedCallback:
        (ResponseStartedCallback)responseStartedCallback
                   progressCallback:(ProgressCallback)progressCallback
                           filePath:(const base::FilePath&)filePath
     downloadToFileCompleteCallback:
         (DownloadToFileCompleteCallback)downloadToFileCompleteCallback;
@end

@implementation CRUUpdaterNetworkDownloadDelegate {
  base::FilePath _filePath;
  bool _moveTempFileSuccessful;
  DownloadToFileCompleteCallback _downloadToFileCompleteCallback;
}

- (instancetype)
    initWithResponseStartedCallback:
        (ResponseStartedCallback)responseStartedCallback
                   progressCallback:(ProgressCallback)progressCallback
                           filePath:(const base::FilePath&)filePath
     downloadToFileCompleteCallback:
         (DownloadToFileCompleteCallback)downloadToFileCompleteCallback {
  if (self = [super
          initWithResponseStartedCallback:std::move(responseStartedCallback)
                         progressCallback:progressCallback]) {
    _filePath = filePath;
    _moveTempFileSuccessful = false;
    _downloadToFileCompleteCallback = std::move(downloadToFileCompleteCallback);
  }
  return self;
}

#pragma mark - NSURLSessionDownloadDelegate

- (void)URLSession:(NSURLSession*)session
             dataTask:(NSURLSessionDataTask*)dataTask
    willCacheResponse:(NSCachedURLResponse*)proposedResponse
    completionHandler:
        (void (^)(NSCachedURLResponse* _Nullable))completionHandler {
  completionHandler(nullptr);
}

- (void)URLSession:(NSURLSession*)session
                 downloadTask:(NSURLSessionDownloadTask*)downloadTask
    didFinishDownloadingToURL:(NSURL*)location {
  if (!location) {
    return;
  }

  const base::FilePath tempPath =
      base::apple::NSStringToFilePath([location path]);
  _moveTempFileSuccessful = base::Move(tempPath, _filePath);
  if (!_moveTempFileSuccessful) {
    DPLOG(ERROR)
        << "Failed to move the downloaded file from the temporary location: "
        << tempPath << " to: " << _filePath;
  }
}

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession*)session
                    task:(NSURLSessionTask*)task
    didCompleteWithError:(NSError*)error {
  [super URLSession:session task:task didCompleteWithError:error];

  NSInteger result;

  if (error) {
    result = [error code];
    DLOG(ERROR) << "NSError code: " << result << ". NSErrorDomain: "
                << base::SysNSStringToUTF8([error domain])
                << ". NSError description: "
                << base::SysNSStringToUTF8([error description]);
  } else {
    NSHTTPURLResponse* response = (NSHTTPURLResponse*)task.response;
    result = response.statusCode == 200 ? 0 : response.statusCode;

    if (!result && !_moveTempFileSuccessful) {
      DLOG(ERROR) << "File downloaded successfully. Moving temp file failed.";
      result = updater::kErrorFailedToMoveDownloadedFile;
    }
  }

  _callbackRunner->PostTask(
      FROM_HERE, base::BindOnce(std::move(_downloadToFileCompleteCallback),
                                result, [task countOfBytesReceived]));
}

@end

@interface CRUUpdaterNetworkDownloadDataDelegate
    : CRUUpdaterNetworkController <NSURLSessionDataDelegate>
- (instancetype)
    initWithResponseStartedCallback:
        (ResponseStartedCallback)responseStartedCallback
                   progressCallback:(ProgressCallback)progressCallback
                             output:(base::File)output
     downloadToFileCompleteCallback:
         (DownloadToFileCompleteCallback)downloadToFileCompleteCallback;
@end

@implementation CRUUpdaterNetworkDownloadDataDelegate {
  base::File _output;
  DownloadToFileCompleteCallback _downloadToFileCompleteCallback;
}

- (instancetype)
    initWithResponseStartedCallback:
        (ResponseStartedCallback)responseStartedCallback
                   progressCallback:(ProgressCallback)progressCallback
                             output:(base::File)output
     downloadToFileCompleteCallback:
         (DownloadToFileCompleteCallback)downloadToFileCompleteCallback {
  if (self = [super
          initWithResponseStartedCallback:std::move(responseStartedCallback)
                         progressCallback:progressCallback]) {
    _output = std::move(output);
    _downloadToFileCompleteCallback = std::move(downloadToFileCompleteCallback);
  }
  return self;
}

#pragma mark - NSURLSessionDataDelegate

// Write the downloaded contents to the file. Cancels the download if there's
// write error. It's up to the caller to handle the partially written file.
- (void)URLSession:(NSURLSession*)session
          dataTask:(NSURLSessionDataTask*)dataTask
    didReceiveData:(NSData*)data {
  if (_output.WriteAtCurrentPosAndCheck(base::apple::NSDataToSpan(data))) {
    _callbackRunner->PostTask(
        FROM_HERE, base::BindOnce(_progressCallback, _output.GetLength()));
    [dataTask resume];
  } else {
    VLOG(1) << __func__ << ": File write error, download job cancelled.";
    if (_downloadToFileCompleteCallback) {
      _callbackRunner->PostTask(
          FROM_HERE, base::BindOnce(std::move(_downloadToFileCompleteCallback),
                                    updater::kErrorFailedToWriteFile, -1));
    }
    [dataTask cancel];
  }
}

// Tells the delegate that the data task received the initial reply from the
// server.
- (void)URLSession:(NSURLSession*)session
              dataTask:(NSURLSessionDataTask*)dataTask
    didReceiveResponse:(NSURLResponse*)response
     completionHandler:
         (void (^)(NSURLSessionResponseDisposition))completionHandler {
  _callbackRunner->PostTask(
      FROM_HERE, base::BindOnce(std::move(_responseStartedCallback),
                                [(NSHTTPURLResponse*)response statusCode],
                                dataTask.countOfBytesExpectedToReceive));
  if (completionHandler) {
    completionHandler(NSURLSessionResponseAllow);
  }
  [dataTask resume];
}

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession*)session
                    task:(NSURLSessionTask*)task
    didCompleteWithError:(NSError*)error {
  [super URLSession:session task:task didCompleteWithError:error];

  NSInteger result;
  if (error) {
    result = error.code;
    DLOG(ERROR) << "NSError code: " << result
                << ". NSErrorDomain: " << base::SysNSStringToUTF8(error.domain)
                << ". NSError description: "
                << base::SysNSStringToUTF8(error.description);
  } else {
    NSHTTPURLResponse* response = (NSHTTPURLResponse*)task.response;
    result = response.statusCode == 200 ? 0 : response.statusCode;
  }
  if (_downloadToFileCompleteCallback) {
    _callbackRunner->PostTask(
        FROM_HERE, base::BindOnce(std::move(_downloadToFileCompleteCallback),
                                  result, [task countOfBytesReceived]));
  }
}

@end

namespace updater {
namespace {

// Wraps a callback pair for PostRequest to log a network event.
std::pair<ResponseStartedCallback, PostRequestCompleteCallback>
WrapPostRequestCallbacksWithEventLogging(
    ResponseStartedCallback response_started_callback,
    PostRequestCompleteCallback post_request_complete_callback,
    const GURL& url,
    scoped_refptr<UpdaterEventLogger> event_logger) {
  if (!event_logger) {
    return std::make_pair(response_started_callback,
                          std::move(post_request_complete_callback));
  }

  std::unique_ptr<int> response_code = std::make_unique<int>(0);
  return std::make_pair(
      base::BindRepeating(
          [](int* out_response_code, ResponseStartedCallback callback,
             int response_code, int64_t content_length) {
            *out_response_code = response_code;
            callback.Run(response_code, content_length);
          },
          response_code.get(), response_started_callback),
      base::BindOnce(
          [](scoped_refptr<UpdaterEventLogger> event_logger,
             base::Time request_start_time, std::unique_ptr<int> response_code,
             const GURL& url, PostRequestCompleteCallback callback,
             std::optional<std::string> response_body, int net_error,
             const std::string& header_etag,
             const std::string& header_x_cup_server_proof,
             const std::string& header_set_cookie,
             int64_t xheader_retry_after_sec) {
            proto::NetworkEvent event;
            event.set_stack(proto::NetworkEvent::DIRECT);
            event.set_url(url.spec());
            event.set_bytes_received(response_body ? response_body->size() : 0);
            event.set_elapsed_time_ms(
                (base::Time::Now() - request_start_time).InMilliseconds());
            if (net_error > 0) {
              event.set_error_code(net_error);
            } else if (*response_code < 200 && *response_code > 299) {
              event.set_error_code(*response_code);
            }
            proto::Omaha4Metric metric;
            *metric.mutable_network_event() = std::move(event);
            event_logger->Log(std::move(metric));
            std::move(callback).Run(response_body, net_error, header_etag,
                                    header_x_cup_server_proof,
                                    header_set_cookie, xheader_retry_after_sec);
          },
          event_logger, base::Time::Now(), std::move(response_code), url,
          std::move(post_request_complete_callback)));
}

std::pair<ResponseStartedCallback, DownloadToFileCompleteCallback>
WrapDownloadToFileCallbacksWithEventLogging(
    ResponseStartedCallback response_started_callback,
    DownloadToFileCompleteCallback download_to_file_complete_callback,
    const GURL& url,
    scoped_refptr<UpdaterEventLogger> event_logger) {
  if (!event_logger) {
    return std::make_pair(response_started_callback,
                          std::move(download_to_file_complete_callback));
  }

  std::unique_ptr<int> response_code = std::make_unique<int>(0);
  return std::make_pair(
      base::BindRepeating(
          [](int* out_response_code, ResponseStartedCallback callback,
             int response_code, int64_t content_length) {
            *out_response_code = response_code;
            callback.Run(response_code, content_length);
          },
          response_code.get(), response_started_callback),
      base::BindOnce(
          [](scoped_refptr<UpdaterEventLogger> event_logger,
             base::Time request_start_time, std::unique_ptr<int> response_code,
             const GURL& url, DownloadToFileCompleteCallback callback,
             int net_error, int64_t content_size) {
            proto::NetworkEvent event;
            event.set_stack(proto::NetworkEvent::DIRECT);
            event.set_url(url.spec());
            event.set_bytes_received(content_size);
            event.set_elapsed_time_ms(
                (base::Time::Now() - request_start_time).InMilliseconds());
            if (net_error > 0) {
              event.set_error_code(net_error);
            } else if (*response_code < 200 && *response_code > 299) {
              event.set_error_code(*response_code);
            }
            proto::Omaha4Metric metric;
            *metric.mutable_network_event() = std::move(event);
            event_logger->Log(std::move(metric));
            std::move(callback).Run(net_error, content_size);
          },
          event_logger, base::Time::Now(), std::move(response_code), url,
          std::move(download_to_file_complete_callback)));
}

class NetworkFetcher : public update_client::NetworkFetcher {
 public:
  explicit NetworkFetcher(scoped_refptr<UpdaterEventLogger> event_logger);
  NetworkFetcher& operator=(const NetworkFetcher&) = delete;
  NetworkFetcher(const NetworkFetcher&) = delete;
  ~NetworkFetcher() override;

  // NetworkFetcher overrides.
  void PostRequest(
      const GURL& url,
      const std::string& post_data,
      const std::string& content_type,
      const base::flat_map<std::string, std::string>& post_additional_headers,
      update_client::NetworkFetcher::ResponseStartedCallback
          response_started_callback,
      update_client::NetworkFetcher::ProgressCallback progress_callback,
      update_client::NetworkFetcher::PostRequestCompleteCallback
          post_request_complete_callback) override;

  base::OnceClosure DownloadToFile(
      const GURL& url,
      const base::FilePath& file_path,
      update_client::NetworkFetcher::ResponseStartedCallback
          response_started_callback,
      update_client::NetworkFetcher::ProgressCallback progress_callback,
      update_client::NetworkFetcher::DownloadToFileCompleteCallback
          download_to_file_complete_callback) override;

 private:
  SEQUENCE_CHECKER(sequence_checker_);
  scoped_refptr<UpdaterEventLogger> event_logger_;
};

NetworkFetcher::NetworkFetcher(scoped_refptr<UpdaterEventLogger> event_logger)
    : event_logger_(event_logger) {}

NetworkFetcher::~NetworkFetcher() = default;

void NetworkFetcher::PostRequest(
    const GURL& url,
    const std::string& post_data,
    const std::string& content_type,
    const base::flat_map<std::string, std::string>& post_additional_headers,
    ResponseStartedCallback response_started_callback,
    ProgressCallback progress_callback,
    PostRequestCompleteCallback post_request_complete_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  auto [wrapped_response_started_callback,
        wrapped_post_request_complete_callback] =
      WrapPostRequestCallbacksWithEventLogging(
          response_started_callback, std::move(post_request_complete_callback),
          url, event_logger_);

  CRUUpdaterNetworkDataDelegate* delegate =
      [[CRUUpdaterNetworkDataDelegate alloc]
          initWithResponseStartedCallback:wrapped_response_started_callback
                         progressCallback:progress_callback
              postRequestCompleteCallback:
                  std::move(wrapped_post_request_complete_callback)];

  NSURLSession* session =
      [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration
                                                 .defaultSessionConfiguration
                                    delegate:delegate
                               delegateQueue:nil];

  NSMutableURLRequest* urlRequest =
      [[NSMutableURLRequest alloc] initWithURL:net::NSURLWithGURL(url)];
  urlRequest.HTTPMethod = @"POST";
  urlRequest.HTTPBody = [[NSData alloc] initWithBytes:post_data.c_str()
                                               length:post_data.size()];
  [urlRequest setValue:base::SysUTF8ToNSString(GetUpdaterUserAgent())
      forHTTPHeaderField:@"User-Agent"];
  [urlRequest addValue:base::SysUTF8ToNSString(content_type)
      forHTTPHeaderField:@"Content-Type"];

  // Post additional headers could overwrite existing headers with the same key,
  // such as "Content-Type" above.
  for (const auto& [name, value] : post_additional_headers) {
    [urlRequest setValue:base::SysUTF8ToNSString(value)
        forHTTPHeaderField:base::SysUTF8ToNSString(name)];
  }
  VLOG(1) << "Posting data: " << post_data.c_str();

  NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:urlRequest];
  [dataTask resume];
}

base::OnceClosure NetworkFetcher::DownloadToFile(
    const GURL& url,
    const base::FilePath& file_path,
    ResponseStartedCallback response_started_callback,
    ProgressCallback progress_callback,
    DownloadToFileCompleteCallback download_to_file_complete_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  auto [wrapped_response_started_callback,
        wrapped_download_to_file_complete_callback] =
      WrapDownloadToFileCallbacksWithEventLogging(
          response_started_callback,
          std::move(download_to_file_complete_callback), url, event_logger_);

  CRUUpdaterNetworkDownloadDelegate* delegate =
      [[CRUUpdaterNetworkDownloadDelegate alloc]
          initWithResponseStartedCallback:wrapped_response_started_callback
                         progressCallback:progress_callback
                                 filePath:file_path
           downloadToFileCompleteCallback:
               std::move(wrapped_download_to_file_complete_callback)];

  NSURLSession* session =
      [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration
                                                 .defaultSessionConfiguration
                                    delegate:delegate
                               delegateQueue:nil];

  NSMutableURLRequest* urlRequest =
      [[NSMutableURLRequest alloc] initWithURL:net::NSURLWithGURL(url)];
  [urlRequest setValue:base::SysUTF8ToNSString(GetUpdaterUserAgent())
      forHTTPHeaderField:@"User-Agent"];

  NSURLSessionDownloadTask* downloadTask =
      [session downloadTaskWithRequest:urlRequest];
  [downloadTask resume];
  return base::DoNothing();
}

// The out-of-process fetcher creates a child worker process in the login
// context and delegates the network fetches to it. The idea is that the process
// the login context may have different access to the keychain or other
// resources for network transactions. This usually runs as a fallback solution
// after network failure in the startup context.
class OutOfProcessNetworkFetcher : public update_client::NetworkFetcher {
 public:
  explicit OutOfProcessNetworkFetcher(
      scoped_refptr<UpdaterEventLogger> event_logger);
  OutOfProcessNetworkFetcher& operator=(const OutOfProcessNetworkFetcher&) =
      delete;
  OutOfProcessNetworkFetcher(const NetworkFetcher&) = delete;

  // NetworkFetcher overrides.
  void PostRequest(
      const GURL& url,
      const std::string& post_data,
      const std::string& content_type,
      const base::flat_map<std::string, std::string>& post_additional_headers,
      update_client::NetworkFetcher::ResponseStartedCallback
          response_started_callback,
      update_client::NetworkFetcher::ProgressCallback progress_callback,
      update_client::NetworkFetcher::PostRequestCompleteCallback
          post_request_complete_callback) override;

  base::OnceClosure DownloadToFile(
      const GURL& url,
      const base::FilePath& file_path,
      update_client::NetworkFetcher::ResponseStartedCallback
          response_started_callback,
      update_client::NetworkFetcher::ProgressCallback progress_callback,
      update_client::NetworkFetcher::DownloadToFileCompleteCallback
          download_to_file_complete_callback) override;

 private:
  // Launches a Mojo net worker process and connects to it. Returns the
  // connection result.
  int DialFetchService();

  void DoDownloadFile(
      const GURL& url,
      update_client::NetworkFetcher::ResponseStartedCallback
          response_started_callback,
      update_client::NetworkFetcher::ProgressCallback progress_callback,
      update_client::NetworkFetcher::DownloadToFileCompleteCallback
          download_complete_callback,
      base::File output);

  SEQUENCE_CHECKER(sequence_checker_);
  scoped_refptr<UpdaterEventLogger> event_logger_;
  mojo::Remote<mojom::FetchService> remote_;
};

OutOfProcessNetworkFetcher::OutOfProcessNetworkFetcher(
    scoped_refptr<UpdaterEventLogger> event_logger)
    : event_logger_(event_logger) {}

int OutOfProcessNetworkFetcher::DialFetchService() {
  VLOG(2) << __func__;
  CHECK(!remote_.is_bound()) << "Fetcher cannot be reused.";

  // Gets the uid of the console user.
  std::optional<uid_t> user_id = []() -> std::optional<uid_t> {
    static constexpr char kConsoleFile[] = "/dev/console";
    struct stat stat = {};
    const int result = lstat(kConsoleFile, &stat);
    if (result != 0) {
      LOG(ERROR) << "Failed to stat " << kConsoleFile << ": " << result;
      return std::nullopt;
    }
    VLOG(2) << "Console user UID:" << stat.st_uid;
    return stat.st_uid;
  }();
  if (!user_id) {
    LOG(ERROR) << "No console user ID is found. The out of process fetcher "
               << "is not launched.";
    return kErrorNoConsoleUser;
  }

  // Gets updater binary path to run as the out-of-process fetcher.
  const base::FilePath updater_path = [] {
    base::FilePath updater_path;
    base::PathService::Get(base::FILE_EXE, &updater_path);
    return updater_path;
  }();

  // Creates a command line in the format of:
  //     /bin/launchctl asuser <uid> <updater> --net-worker \
  //          --mojo-platform-channel-handle=N
  // Note that base::CommandLine moves the switches ahead of arguments which
  // makes /bin/launchctl unhappy. Calls `PrependWrapper()` instead of
  // `AppendArg()` to make sure the arguments are in the required order.
  base::CommandLine launch_command(updater_path);
  launch_command.AppendSwitch(kNetWorkerSwitch);
  // Delegating to Mojo to "prepare" the command line appends the
  // `--mojo-platform-channel-handle=N` command line argument, so that the
  // network service knows which file descriptor name to recover, in order to
  // establish the primordial connection with this process.
  base::LaunchOptions options;
  mojo::PlatformChannel channel;
  channel.PrepareToPassRemoteEndpoint(&options, &launch_command);
  launch_command.PrependWrapper(base::StringPrintf("%d", *user_id));
  launch_command.PrependWrapper("asuser");
  launch_command.PrependWrapper("/bin/launchctl");
  VLOG(2) << "Starting net-worker: " << launch_command.GetCommandLineString();
  base::Process child_process = base::LaunchProcess(launch_command, options);
  if (!child_process.IsValid()) {
    LOG(ERROR) << "Failed to launch out-of-process fetcher process.";
    return kErrorProcessLaunchFailed;
  }
  channel.RemoteProcessLaunchAttempted();
  mojo::ScopedMessagePipeHandle pipe = mojo::OutgoingInvitation::SendIsolated(
      channel.TakeLocalEndpoint(), {}, child_process.Handle());
  if (!pipe) {
    LOG(ERROR) << "Failed to send Mojo invitation to the fetcher process.";
    return kErrorMojoConnectionFailure;
  }
  mojo::PendingRemote<mojom::FetchService> pending_remote(
      std::move(pipe), mojom::FetchService::Version_);
  if (!pending_remote) {
    LOG(ERROR) << "Failed to establish IPC with the net-worker process.";
    return kErrorMojoConnectionFailure;
  }
  remote_ = mojo::Remote<mojom::FetchService>(std::move(pending_remote));
  return remote_.is_bound() ? kErrorOk : kErrorIpcDisconnect;
}

void OutOfProcessNetworkFetcher::PostRequest(
    const GURL& url,
    const std::string& post_data,
    const std::string& content_type,
    const base::flat_map<std::string, std::string>& post_additional_headers,
    ResponseStartedCallback response_started_callback,
    ProgressCallback progress_callback,
    PostRequestCompleteCallback post_request_complete_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto [wrapped_response_started_callback,
        wrapped_post_request_complete_callback] =
      WrapPostRequestCallbacksWithEventLogging(
          response_started_callback, std::move(post_request_complete_callback),
          url, event_logger_);

  VLOG(1) << __func__;
  if (const int dial_result = DialFetchService(); dial_result != kErrorOk) {
    LOG(ERROR) << "Failed to dial the fetch service: " << dial_result;
    std::move(post_request_complete_callback)
        .Run(nullptr, dial_result, {}, {}, {}, -1);
    return;
  }

  VLOG(2) << "OutOfProcessNetworkFetcher invoking PostRequest() on remote.";
  std::vector<mojom::HttpHeaderPtr> headers;
  for (const auto& [name, value] : post_additional_headers) {
    headers.push_back(mojom::HttpHeader::New(name, value));
  }

  remote_->PostRequest(
      url, post_data, content_type, std::move(headers),
      MakePostRequestObserver(
          response_started_callback, progress_callback,
          mojo::WrapCallbackWithDefaultInvokeIfNotRun(
              std::move(wrapped_post_request_complete_callback), std::nullopt,
              kErrorIpcDisconnect, "", "", "", -1)));
}

base::OnceClosure OutOfProcessNetworkFetcher::DownloadToFile(
    const GURL& url,
    const base::FilePath& file_path,
    update_client::NetworkFetcher::ResponseStartedCallback
        response_started_callback,
    update_client::NetworkFetcher::ProgressCallback progress_callback,
    update_client::NetworkFetcher::DownloadToFileCompleteCallback
        download_to_file_complete_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  VLOG(1) << __func__;
  auto [wrapped_response_started_callback,
        wrapped_download_to_file_complete_callback] =
      WrapDownloadToFileCallbacksWithEventLogging(
          response_started_callback,
          std::move(download_to_file_complete_callback), url, event_logger_);

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock()},
      base::BindOnce(
          [](const base::FilePath& file_path) {
            return base::File(file_path, base::File::FLAG_OPEN_ALWAYS |
                                             base::File::FLAG_WRITE);
          },
          file_path),
      base::BindOnce(&OutOfProcessNetworkFetcher::DoDownloadFile,
                     base::Unretained(this), url,
                     wrapped_response_started_callback, progress_callback,
                     std::move(wrapped_download_to_file_complete_callback)));
  return base::DoNothing();
}

void OutOfProcessNetworkFetcher::DoDownloadFile(
    const GURL& url,
    update_client::NetworkFetcher::ResponseStartedCallback
        response_started_callback,
    update_client::NetworkFetcher::ProgressCallback progress_callback,
    update_client::NetworkFetcher::DownloadToFileCompleteCallback
        download_complete_callback,
    base::File output) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  VLOG(1) << __func__;
  if (!output.IsValid()) {
    LOG(ERROR) << "Failed to open the file to download.";
    std::move(download_complete_callback).Run(kErrorFailedToWriteFile, -1);
    return;
  }

  if (const int dial_result = DialFetchService(); dial_result != kErrorOk) {
    LOG(ERROR) << "Failed to dial the fetch service: " << dial_result;
    std::move(download_complete_callback).Run(dial_result, -1);
    return;
  }

  VLOG(2) << "OutOfProcessNetworkFetcher invoking DownloadToFile() on remote.";
  remote_->DownloadToFile(
      url, std::move(output),
      MakeFileDownloadObserver(
          response_started_callback, progress_callback,
          mojo::WrapCallbackWithDefaultInvokeIfNotRun(
              std::move(download_complete_callback), kErrorIpcDisconnect, -1)));
}

}  // namespace

base::OnceClosure NetworkFileFetcher::Download(
    const GURL& url,
    base::File output,
    update_client::NetworkFetcher::ResponseStartedCallback
        response_started_callback,
    update_client::NetworkFetcher::ProgressCallback progress_callback,
    update_client::NetworkFetcher::DownloadToFileCompleteCallback
        download_to_file_complete_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  CRUUpdaterNetworkDownloadDataDelegate* delegate =
      [[CRUUpdaterNetworkDownloadDataDelegate alloc]
          initWithResponseStartedCallback:std::move(response_started_callback)
                         progressCallback:progress_callback
                                   output:std::move(output)
           downloadToFileCompleteCallback:
               std::move(download_to_file_complete_callback)];

  NSURLSession* session =
      [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration
                                                 .defaultSessionConfiguration
                                    delegate:delegate
                               delegateQueue:nil];

  NSMutableURLRequest* urlRequest =
      [[NSMutableURLRequest alloc] initWithURL:net::NSURLWithGURL(url)];
  [urlRequest setValue:base::SysUTF8ToNSString(GetUpdaterUserAgent())
      forHTTPHeaderField:@"User-Agent"];

  NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:urlRequest];
  [dataTask resume];
  return base::DoNothing();
}

class NetworkFetcherFactory::Impl {
 public:
  explicit Impl(scoped_refptr<UpdaterEventLogger> event_logger)
      : event_logger_(event_logger) {}

  scoped_refptr<UpdaterEventLogger> event_logger() { return event_logger_; }

 private:
  scoped_refptr<UpdaterEventLogger> event_logger_;
};

NetworkFetcherFactory::NetworkFetcherFactory(
    std::optional<PolicyServiceProxyConfiguration>,
    scoped_refptr<UpdaterEventLogger> event_logger)
    : impl_(std::make_unique<Impl>(event_logger)) {}
NetworkFetcherFactory::~NetworkFetcherFactory() = default;

std::unique_ptr<update_client::NetworkFetcher> NetworkFetcherFactory::Create()
    const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return std::make_unique<FallbackNetFetcher>(
      std::make_unique<NetworkFetcher>(impl_->event_logger()),
      base::CommandLine::ForCurrentProcess()->HasSwitch(kNetWorkerSwitch)
          ? nullptr  // Already a networker, should not fallback further.
          : std::make_unique<OutOfProcessNetworkFetcher>(
                impl_->event_logger()));
}

}  // namespace updater