-
Notifications
You must be signed in to change notification settings - Fork 887
/
brave_proxying_web_socket.cc
421 lines (359 loc) · 13.8 KB
/
brave_proxying_web_socket.cc
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
/* Copyright (c) 2019 The Brave Authors. All rights reserved.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at https://mozilla.org/MPL/2.0/. */
#include "brave/browser/net/brave_proxying_web_socket.h"
#include <optional>
#include <utility>
#include "base/containers/flat_set.h"
#include "base/functional/bind.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "brave/browser/net/brave_request_handler.h"
#include "brave/components/constants/network_constants.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "net/cookies/site_for_cookies.h"
BraveProxyingWebSocket::BraveProxyingWebSocket(
WebSocketFactory factory,
const network::ResourceRequest& request,
mojo::PendingRemote<network::mojom::WebSocketHandshakeClient>
handshake_client,
int process_id,
content::FrameTreeNodeId frame_tree_node_id,
content::BrowserContext* browser_context,
scoped_refptr<RequestIDGenerator> request_id_generator,
BraveRequestHandler& handler,
DisconnectCallback on_disconnect)
: request_handler_(handler),
process_id_(process_id),
frame_tree_node_id_(frame_tree_node_id),
factory_(std::move(factory)),
browser_context_(browser_context),
request_id_generator_(std::move(request_id_generator)),
forwarding_handshake_client_(std::move(handshake_client)),
receiver_as_handshake_client_(this),
receiver_as_auth_handler_(this),
receiver_as_header_client_(this),
request_(request),
on_disconnect_(std::move(on_disconnect)) {}
BraveProxyingWebSocket::~BraveProxyingWebSocket() {
if (ctx_) {
request_handler_->OnURLRequestDestroyed(ctx_);
}
if (on_before_send_headers_callback_) {
std::move(on_before_send_headers_callback_)
.Run(net::ERR_ABORTED, std::nullopt);
}
if (on_headers_received_callback_) {
std::move(on_headers_received_callback_)
.Run(net::ERR_ABORTED, std::nullopt, std::nullopt);
}
}
// static
BraveProxyingWebSocket* BraveProxyingWebSocket::ProxyWebSocket(
content::RenderFrameHost* frame,
content::ContentBrowserClient::WebSocketFactory factory,
const GURL& url,
const net::SiteForCookies& site_for_cookies,
const std::optional<std::string>& user_agent,
mojo::PendingRemote<network::mojom::WebSocketHandshakeClient>
handshake_client) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
return ResourceContextData::StartProxyingWebSocket(
std::move(factory), url, site_for_cookies, user_agent,
std::move(handshake_client), frame->GetProcess()->GetBrowserContext(),
frame->GetProcess()->GetID(), frame->GetRoutingID(),
frame->GetFrameTreeNodeId(), frame->GetLastCommittedOrigin());
}
void BraveProxyingWebSocket::Start() {
request_id_ = request_id_generator_->Generate();
// If the header client will be used, we start the request immediately, and
// OnBeforeSendHeaders and OnSendHeaders will be handled there. Otherwise,
// send these events before the request starts.
base::RepeatingCallback<void(int)> continuation;
if (proxy_has_extra_headers()) {
continuation = base::BindRepeating(
&BraveProxyingWebSocket::ContinueToStartRequest,
weak_factory_.GetWeakPtr());
} else {
continuation = base::BindRepeating(
&BraveProxyingWebSocket::OnBeforeRequestComplete,
weak_factory_.GetWeakPtr());
}
ctx_ = brave::BraveRequestInfo::MakeCTX(request_, process_id_,
frame_tree_node_id_, request_id_,
browser_context_, ctx_);
int result = request_handler_->OnBeforeURLRequest(
ctx_, continuation, &redirect_url_);
// TODO(bridiver) - need to handle general case for redirect_url
if (result == net::ERR_BLOCKED_BY_CLIENT ||
// handle adblock kEmptyDataURI
redirect_url_ == kEmptyDataURI) {
OnError(result);
return;
}
if (result == net::ERR_IO_PENDING) {
return;
}
DCHECK_EQ(net::OK, result);
continuation.Run(net::OK);
}
content::ContentBrowserClient::WebSocketFactory
BraveProxyingWebSocket::web_socket_factory() {
return base::BindOnce(&BraveProxyingWebSocket::WebSocketFactoryRun,
base::Unretained(this));
}
mojo::Remote<network::mojom::WebSocketHandshakeClient>
BraveProxyingWebSocket::handshake_client() {
return std::move(forwarding_handshake_client_);
}
bool BraveProxyingWebSocket::proxy_has_extra_headers() {
return proxy_trusted_header_client_.is_bound();
}
void BraveProxyingWebSocket::WebSocketFactoryRun(
const GURL& url,
std::vector<network::mojom::HttpHeaderPtr> additional_headers,
mojo::PendingRemote<network::mojom::WebSocketHandshakeClient>
handshake_client,
mojo::PendingRemote<network::mojom::WebSocketAuthenticationHandler>
auth_handler,
mojo::PendingRemote<network::mojom::TrustedHeaderClient>
trusted_header_client) {
DCHECK(!forwarding_handshake_client_);
proxy_url_ = url;
forwarding_handshake_client_.Bind(std::move(handshake_client));
proxy_auth_handler_.Bind(std::move(auth_handler));
if (trusted_header_client)
proxy_trusted_header_client_.Bind(std::move(trusted_header_client));
if (!proxy_has_extra_headers()) {
for (const auto& header : additional_headers) {
request_.headers.SetHeader(header->name, header->value);
}
}
Start();
}
void BraveProxyingWebSocket::OnOpeningHandshakeStarted(
network::mojom::WebSocketHandshakeRequestPtr request) {
DCHECK(forwarding_handshake_client_);
forwarding_handshake_client_->OnOpeningHandshakeStarted(std::move(request));
}
void BraveProxyingWebSocket::ContinueToHeadersReceived() {
auto continuation = base::BindRepeating(
&BraveProxyingWebSocket::OnHeadersReceivedComplete,
weak_factory_.GetWeakPtr());
ctx_ = brave::BraveRequestInfo::MakeCTX(request_, process_id_,
frame_tree_node_id_, request_id_,
browser_context_, ctx_);
int result = request_handler_->OnHeadersReceived(
ctx_, continuation, response_.headers.get(),
&override_headers_, &redirect_url_);
if (result == net::ERR_BLOCKED_BY_CLIENT ||
// handle adblock kEmptyDataURI
redirect_url_ == kEmptyDataURI) {
OnError(result);
return;
}
PauseIncomingMethodCallProcessing();
if (result == net::ERR_IO_PENDING)
return;
DCHECK_EQ(net::OK, result);
OnHeadersReceivedComplete(net::OK);
}
void BraveProxyingWebSocket::OnFailure(const std::string& message,
int32_t net_error,
int32_t response_code) {}
void BraveProxyingWebSocket::OnConnectionEstablished(
mojo::PendingRemote<network::mojom::WebSocket> websocket,
mojo::PendingReceiver<network::mojom::WebSocketClient> client_receiver,
network::mojom::WebSocketHandshakeResponsePtr response,
mojo::ScopedDataPipeConsumerHandle readable,
mojo::ScopedDataPipeProducerHandle writable) {
DCHECK(forwarding_handshake_client_);
DCHECK(!is_done_);
remote_endpoint_ = response->remote_endpoint;
forwarding_handshake_client_->OnConnectionEstablished(
std::move(websocket), std::move(client_receiver), std::move(response),
std::move(readable), std::move(writable));
OnError(net::ERR_FAILED);
}
void BraveProxyingWebSocket::OnAuthRequired(
const net::AuthChallengeInfo& auth_info,
const scoped_refptr<net::HttpResponseHeaders>& headers,
const net::IPEndPoint& remote_endpoint,
OnAuthRequiredCallback callback) {
proxy_auth_handler_->OnAuthRequired(
auth_info, headers, remote_endpoint, std::move(callback));
}
void BraveProxyingWebSocket::OnBeforeSendHeaders(
const net::HttpRequestHeaders& headers,
OnBeforeSendHeadersCallback callback) {
DCHECK(proxy_has_extra_headers());
request_.headers = headers;
on_before_send_headers_callback_ = std::move(callback);
OnBeforeRequestComplete(net::OK);
}
void BraveProxyingWebSocket::OnHeadersReceived(
const std::string& headers,
const ::net::IPEndPoint& remote_endpoint,
OnHeadersReceivedCallback callback) {
DCHECK(proxy_has_extra_headers());
on_headers_received_callback_ = std::move(callback);
response_.headers = base::MakeRefCounted<net::HttpResponseHeaders>(headers);
ContinueToHeadersReceived();
}
void BraveProxyingWebSocket::OnBeforeRequestComplete(int error_code) {
DCHECK(proxy_has_extra_headers() ||
!receiver_as_handshake_client_.is_bound());
DCHECK(request_.url.SchemeIsWSOrWSS());
if (error_code != net::OK) {
OnError(error_code);
return;
}
if (proxy_has_extra_headers()) {
proxy_trusted_header_client_->OnBeforeSendHeaders(
request_.headers,
base::BindOnce(
&BraveProxyingWebSocket::OnBeforeSendHeadersCompleteFromProxy,
weak_factory_.GetWeakPtr()));
} else {
OnBeforeSendHeadersCompleteFromProxy(
net::OK, request_.headers);
}
}
void BraveProxyingWebSocket::OnBeforeSendHeadersCompleteFromProxy(
int error_code,
const std::optional<net::HttpRequestHeaders>& headers) {
DCHECK(proxy_has_extra_headers() ||
!receiver_as_handshake_client_.is_bound());
if (error_code != net::OK) {
OnError(error_code);
return;
}
// update the headers from the proxy
if (headers)
request_.headers = *headers;
else
request_.headers.Clear();
auto continuation = base::BindRepeating(
&BraveProxyingWebSocket::OnBeforeSendHeadersComplete,
weak_factory_.GetWeakPtr());
ctx_ = brave::BraveRequestInfo::MakeCTX(request_, process_id_,
frame_tree_node_id_, request_id_,
browser_context_, ctx_);
int result = request_handler_->OnBeforeStartTransaction(
ctx_, continuation, &request_.headers);
if (result == net::ERR_BLOCKED_BY_CLIENT) {
OnError(result);
return;
}
if (result == net::ERR_IO_PENDING)
return;
DCHECK_EQ(net::OK, result);
continuation.Run(net::OK);
}
void BraveProxyingWebSocket::OnBeforeSendHeadersComplete(int error_code) {
DCHECK(proxy_has_extra_headers() ||
!receiver_as_handshake_client_.is_bound());
if (error_code != net::OK) {
OnError(error_code);
return;
}
if (on_before_send_headers_callback_)
std::move(on_before_send_headers_callback_)
.Run(error_code,
std::optional<net::HttpRequestHeaders>(request_.headers));
if (!proxy_has_extra_headers())
ContinueToStartRequest(error_code);
}
void BraveProxyingWebSocket::ContinueToStartRequest(int error_code) {
if (error_code != net::OK) {
OnError(error_code);
return;
}
std::vector<network::mojom::HttpHeaderPtr> additional_headers;
if (!proxy_has_extra_headers()) {
for (net::HttpRequestHeaders::Iterator it(request_.headers);
it.GetNext();) {
additional_headers.push_back(
network::mojom::HttpHeader::New(it.name(), it.value()));
}
}
mojo::PendingRemote<network::mojom::TrustedHeaderClient>
trusted_header_client = mojo::NullRemote();
if (proxy_has_extra_headers())
trusted_header_client =
receiver_as_header_client_.BindNewPipeAndPassRemote();
std::move(factory_).Run(
request_.url, std::move(additional_headers),
receiver_as_handshake_client_.BindNewPipeAndPassRemote(),
receiver_as_auth_handler_.BindNewPipeAndPassRemote(),
std::move(trusted_header_client));
// Here we detect mojo connection errors on |receiver_as_handshake_client_|.
// See also CreateWebSocket in
// //network/services/public/mojom/network_context.mojom.
receiver_as_handshake_client_.set_disconnect_with_reason_handler(
base::BindOnce(&BraveProxyingWebSocket::OnMojoConnectionError,
base::Unretained(this)));
}
void BraveProxyingWebSocket::OnHeadersReceivedCompleteFromProxy(
int error_code,
const std::optional<std::string>& headers,
const std::optional<GURL>& url) {
if (on_headers_received_callback_)
std::move(on_headers_received_callback_)
.Run(net::OK, headers, std::nullopt);
if (override_headers_) {
response_.headers = override_headers_;
override_headers_ = nullptr;
}
ResumeIncomingMethodCallProcessing();
}
void BraveProxyingWebSocket::OnHeadersReceivedComplete(int error_code) {
if (error_code != net::OK) {
OnError(error_code);
return;
}
std::string headers;
if (override_headers_)
headers = override_headers_->raw_headers();
if (proxy_has_extra_headers()) {
proxy_trusted_header_client_->OnHeadersReceived(
headers,
remote_endpoint_,
base::BindOnce(
&BraveProxyingWebSocket::OnHeadersReceivedCompleteFromProxy,
weak_factory_.GetWeakPtr()));
} else {
OnHeadersReceivedCompleteFromProxy(
error_code, std::optional<std::string>(headers), std::nullopt);
}
}
void BraveProxyingWebSocket::PauseIncomingMethodCallProcessing() {
receiver_as_handshake_client_.Pause();
if (proxy_has_extra_headers())
receiver_as_header_client_.Pause();
}
void BraveProxyingWebSocket::ResumeIncomingMethodCallProcessing() {
receiver_as_handshake_client_.Resume();
if (proxy_has_extra_headers())
receiver_as_header_client_.Resume();
}
void BraveProxyingWebSocket::OnError(int error_code) {
if (!is_done_) {
is_done_ = true;
}
// Deletes |this|.
std::move(on_disconnect_).Run(this);
}
// ResetWithReason
void BraveProxyingWebSocket::OnMojoConnectionError(
uint32_t custom_reason,
const std::string& description) {
forwarding_handshake_client_.ResetWithReason(custom_reason, description);
OnError(net::ERR_FAILED);
// Deletes |this|.
}