File: app_net_worker.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 (294 lines) | stat: -rw-r--r-- 11,317 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
// Copyright 2024 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/updater/app/app_net_worker.h"

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

#include "base/command_line.h"
#include "base/containers/flat_map.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/task/bind_post_task.h"
#include "base/threading/sequence_bound.h"
#include "base/threading/thread.h"
#include "chrome/updater/app/app.h"
#include "chrome/updater/constants.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 "components/update_client/network.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.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"

namespace updater {

namespace {

// Creates a `PostRequestObserver` remote with the given callback and put it
// into a thin wrapper for ref-counting.
class PostRequestObserverWrapper
    : public base::RefCountedThreadSafe<PostRequestObserverWrapper> {
 public:
  explicit PostRequestObserverWrapper(
      mojom::FetchService::PostRequestCallback callback) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    std::move(callback).Run(observer_.BindNewPipeAndPassReceiver());
  }

  void OnResponseStarted(int32_t http_status_code, int64_t content_length) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    observer_->OnResponseStarted(http_status_code, content_length);
  }

  void OnProgress(int64_t current) { observer_->OnProgress(current); }

  void OnRequestComplete(std::optional<std::string> response_body,
                         int32_t 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) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    observer_->OnRequestComplete(*response_body, net_error, header_etag,
                                 header_x_cup_server_proof, header_set_cookie,
                                 xheader_retry_after_sec);
  }

 private:
  friend class base::RefCountedThreadSafe<PostRequestObserverWrapper>;

  virtual ~PostRequestObserverWrapper() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  }

  SEQUENCE_CHECKER(sequence_checker_);
  mojo::Remote<mojom::PostRequestObserver> observer_;
};

// Creates a `FileDownloadObserver` remote with the given callback and put it
// into a thin wrapper for ref-counting.
class FileDownloadObserverWrapper
    : public base::RefCountedThreadSafe<FileDownloadObserverWrapper> {
 public:
  explicit FileDownloadObserverWrapper(
      mojom::FetchService::DownloadToFileCallback callback) {
    std::move(callback).Run(observer_.BindNewPipeAndPassReceiver());
  }

  void OnResponseStarted(int32_t http_status_code, int64_t content_length) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    observer_->OnResponseStarted(http_status_code, content_length);
  }

  void OnProgress(int64_t current) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    observer_->OnProgress(current);
  }

  void OnDownloadComplete(int32_t net_error, int64_t content_length) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    observer_->OnDownloadComplete(net_error, content_length);
  }

 private:
  friend class base::RefCountedThreadSafe<FileDownloadObserverWrapper>;

  virtual ~FileDownloadObserverWrapper() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  }

  SEQUENCE_CHECKER(sequence_checker_);
  mojo::Remote<mojom::FileDownloadObserver> observer_;
};

// The stub class that translates and forwards the Mojo requests to the
// underlying fetcher. It also keeps a reference to the remote receiver and
// sends the result back when fetch is done.
class FetchServiceImpl : public mojom::FetchService {
 public:
  FetchServiceImpl(mojo::PendingReceiver<mojom::FetchService> pending_receiver,
                   base::OnceCallback<void(int)> on_complete_callback);
  ~FetchServiceImpl() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  }

  // Overrides for mojom::FetchService.
  void PostRequest(const ::GURL& url,
                   const std::string& post_data,
                   const std::string& content_type,
                   std::vector<mojom::HttpHeaderPtr> additional_headers,
                   mojom::FetchService::PostRequestCallback callback) override;

  void DownloadToFile(
      const ::GURL& url,
      ::base::File output_file,
      mojom::FetchService::DownloadToFileCallback callback) override;

 private:
  SEQUENCE_CHECKER(sequence_checker_);

  mojo::Receiver<mojom::FetchService> receiver_;
  base::OnceCallback<void(int)> on_complete_callback_;

  // Network fetcher for POST request.
  std::unique_ptr<update_client::NetworkFetcher> fetcher_;

  // For file download, `update_client::NetworkFetcher` interface takes
  // a `base::FilePath` as the output, and the Mojo interface takes a
  // `base::File` object. This customized fetcher is used to support
  // the Mojo interface.
  std::unique_ptr<NetworkFileFetcher> file_fetcher_;
};

FetchServiceImpl::FetchServiceImpl(
    mojo::PendingReceiver<mojom::FetchService> pending_receiver,
    base::OnceCallback<void(int)> on_complete_callback)
    : receiver_(this, std::move(pending_receiver)),
      on_complete_callback_(std::move(on_complete_callback)) {}

void FetchServiceImpl::PostRequest(
    const ::GURL& url,
    const std::string& post_data,
    const std::string& content_type,
    std::vector<mojom::HttpHeaderPtr> additional_headers,
    mojom::FetchService::PostRequestCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto wrapper =
      base::MakeRefCounted<PostRequestObserverWrapper>(std::move(callback));
  if (fetcher_ || file_fetcher_) {
    LOG(ERROR) << "Each service instance can do only one fetch request.";
    wrapper->OnRequestComplete(nullptr, kErrorMojoRequestRejected, {}, {}, {},
                               -1);
    std::move(on_complete_callback_).Run(kErrorMojoRequestRejected);
    return;
  }
  base::flat_map<std::string, std::string> headers;
  for (const auto& header : additional_headers) {
    headers.emplace(header->name, header->value);
  }
  // Creates a network fetcher without any proxy configuration (let the system
  // handle the proxy settings) to fetch data. Network events are logged by the
  // parent process.
  fetcher_ = base::MakeRefCounted<NetworkFetcherFactory>(
                 /*policy_service_proxy_configuration=*/std::nullopt,
                 /*event_logger=*/nullptr)
                 ->Create();
  fetcher_->PostRequest(
      url, post_data, content_type, headers,
      base::BindRepeating(&PostRequestObserverWrapper::OnResponseStarted,
                          wrapper),
      base::BindRepeating(&PostRequestObserverWrapper::OnProgress, wrapper),
      base::BindOnce(
          [](scoped_refptr<PostRequestObserverWrapper> wrapper,
             base::OnceCallback<void(int)> callback,
             std::optional<std::string> response_body, int32_t 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) {
            wrapper->OnRequestComplete(std::move(response_body), net_error,
                                       header_etag, header_x_cup_server_proof,
                                       header_set_cookie,
                                       xheader_retry_after_sec);
            std::move(callback).Run(net_error);
          },
          wrapper, std::move(on_complete_callback_)));
}

void FetchServiceImpl::DownloadToFile(
    const ::GURL& url,
    ::base::File output_file,
    mojom::FetchService::DownloadToFileCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto wrapper =
      base::MakeRefCounted<FileDownloadObserverWrapper>(std::move(callback));
  if (fetcher_ || file_fetcher_) {
    LOG(ERROR) << "Each service instance can do only one fetch request.";
    wrapper->OnDownloadComplete(kErrorMojoRequestRejected, -1);
    std::move(on_complete_callback_).Run(kErrorMojoRequestRejected);
    return;
  }
  file_fetcher_ = std::make_unique<NetworkFileFetcher>();
  file_fetcher_->Download(
      url, std::move(output_file),
      base::BindRepeating(&FileDownloadObserverWrapper::OnResponseStarted,
                          wrapper),
      base::BindRepeating(&FileDownloadObserverWrapper::OnProgress, wrapper),
      base::BindOnce(
          [](scoped_refptr<FileDownloadObserverWrapper> wrapper,
             base::OnceCallback<void(int)> callback, int32_t net_error,
             int64_t content_length) {
            wrapper->OnDownloadComplete(net_error, content_length);
            std::move(callback).Run(net_error);
          },
          wrapper, std::move(on_complete_callback_)));
}

// AppNetWorker runs networking tasks in a dedicated process.
class AppNetWorker : public App {
 public:
  AppNetWorker() {
    net_thread_.StartWithOptions({base::MessagePumpType::IO, 0});
  }

 private:
  ~AppNetWorker() override = default;

  void FirstTaskRun() override {
    // This process must be started with the command line switch
    /// `--mojo-platform-channel-handle=N`. In other words, the command line
    // must be prepared by
    // `mojo::PlatformChannel::PrepareToPassRemoteEndpoint()`.
    mojo::PlatformChannelEndpoint endpoint =
        mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(
            *base::CommandLine::ForCurrentProcess());
    if (!endpoint.is_valid()) {
      Shutdown(kErrorMojoConnectionFailure);
      return;
    }

    mojo::ScopedMessagePipeHandle pipe =
        mojo::IncomingInvitation::AcceptIsolated(std::move(endpoint));
    if (!pipe->is_valid()) {
      Shutdown(kErrorMojoConnectionFailure);
      return;
    }

    fetcher_stub_ = base::SequenceBound<FetchServiceImpl>(
        net_thread_.task_runner(),
        mojo::PendingReceiver<mojom::FetchService>(std::move(pipe)),
        base::BindPostTaskToCurrentDefault(base::BindOnce(
            &AppNetWorker::Shutdown, weak_ptr_factory_.GetWeakPtr())));

    // TODO(crbug.com/353751917): Add a timer that shutdown this process if
    // no incoming network requests in time.
  }

  base::Thread net_thread_{"Network"};
  base::SequenceBound<FetchServiceImpl> fetcher_stub_;
  base::WeakPtrFactory<AppNetWorker> weak_ptr_factory_{this};
};

}  // namespace

scoped_refptr<App> MakeAppNetWorker() {
  return base::MakeRefCounted<AppNetWorker>();
}

}  // namespace updater