blob: 381b94fd490de949194f485661b71c1a82ed2280 [file] [log] [blame]
Andreea Costinase45d54b2020-03-10 09:21:14 +01001// Copyright 2020 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "system-proxy/proxy_connect_job.h"
6
7#include <algorithm>
8#include <utility>
9#include <vector>
10
Andreea Costinase45d54b2020-03-10 09:21:14 +010011#include <curl/easy.h>
12
Andreea Costinase45d54b2020-03-10 09:21:14 +010013#include <base/base64.h>
14#include <base/bind.h>
15#include <base/bind_helpers.h>
16#include <base/callback_helpers.h>
Qijiang Fan713061e2021-03-08 15:45:12 +090017#include <base/check.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010018#include <base/files/file_util.h>
19#include <base/strings/stringprintf.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010020#include <base/strings/string_util.h>
21#include <base/time/time.h>
Andreea Costinas08a5d182020-04-29 22:12:47 +020022#include <base/threading/thread.h>
23#include <base/threading/thread_task_runner_handle.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010024#include <brillo/http/http_transport.h>
Garrick Evanscd8c2972020-04-14 14:35:52 +090025#include <chromeos/patchpanel/net_util.h>
26#include <chromeos/patchpanel/socket.h>
27#include <chromeos/patchpanel/socket_forwarder.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010028
29#include "system-proxy/curl_socket.h"
Andreea Costinas90b71642020-06-12 10:18:25 +020030#include "system-proxy/http_util.h"
Andreea Costinase45d54b2020-03-10 09:21:14 +010031
Garrick Evans2d5e7c92020-06-08 14:14:28 +090032// The libpatchpanel-util library overloads << for socket data structures.
Andreea Costinase45d54b2020-03-10 09:21:14 +010033// By C++'s argument-dependent lookup rules, operators defined in a
34// different namespace are not visible. We need the using directive to make
35// the overload available this namespace.
Garrick Evans3388a032020-03-24 11:25:55 +090036using patchpanel::operator<<;
Andreea Costinase45d54b2020-03-10 09:21:14 +010037
38namespace {
39// There's no RFC recomandation for the max size of http request headers but
40// popular http server implementations (Apache, IIS, Tomcat) set the lower limit
41// to 8000.
42constexpr int kMaxHttpRequestHeadersSize = 8000;
Andreea Costinas350e4aa2020-07-20 20:29:46 +020043constexpr base::TimeDelta kCurlConnectTimeout =
44 base::TimeDelta::FromSeconds(30);
Andreea Costinas08a5d182020-04-29 22:12:47 +020045constexpr base::TimeDelta kWaitClientConnectTimeout =
Andreea Costinas435851b2020-05-25 14:18:41 +020046 base::TimeDelta::FromSeconds(2);
Andreea Costinased9e6122020-08-12 12:06:19 +020047// Time to wait for proxy authentication credentials to be fetched from the
48// browser. The credentials are retrieved either from the Network Service or, if
49// the Network Service doesn't have them, directly from the user via a login
50// dialogue.
51constexpr base::TimeDelta kCredentialsRequestTimeout =
52 base::TimeDelta::FromMinutes(1);
Andreea Costinase45d54b2020-03-10 09:21:14 +010053
Andreea Costinasf90a4c02020-06-12 22:30:51 +020054constexpr int64_t kHttpCodeProxyAuthRequired = 407;
55
Andreea Costinase45d54b2020-03-10 09:21:14 +010056// HTTP error codes and messages with origin information for debugging (RFC723,
57// section 6.1).
58const std::string_view kHttpBadRequest =
59 "HTTP/1.1 400 Bad Request - Origin: local proxy\r\n\r\n";
Andreea Costinas08a5d182020-04-29 22:12:47 +020060const std::string_view kHttpConnectionTimeout =
61 "HTTP/1.1 408 Request Timeout - Origin: local proxy\r\n\r\n";
Andreea Costinase45d54b2020-03-10 09:21:14 +010062const std::string_view kHttpInternalServerError =
63 "HTTP/1.1 500 Internal Server Error - Origin: local proxy\r\n\r\n";
64const std::string_view kHttpBadGateway =
65 "HTTP/1.1 502 Bad Gateway - Origin: local proxy\r\n\r\n";
Andreea Costinasf90a4c02020-06-12 22:30:51 +020066const std::string_view kHttpProxyAuthRequired =
67 "HTTP/1.1 407 Credentials required - Origin: local proxy\r\n\r\n";
68constexpr char kHttpErrorTunnelFailed[] =
69 "HTTP/1.1 %s Error creating tunnel - Origin: local proxy\r\n\r\n";
Andreea Costinas90b71642020-06-12 10:18:25 +020070} // namespace
Andreea Costinasa2246592020-04-12 23:24:01 +020071
Andreea Costinas90b71642020-06-12 10:18:25 +020072namespace system_proxy {
Andreea Costinasa2246592020-04-12 23:24:01 +020073// CURLOPT_HEADERFUNCTION callback implementation that only returns the headers
74// from the last response sent by the sever. This is to make sure that we
75// send back valid HTTP replies and auhentication data from the HTTP messages is
76// not being leaked to the client. |userdata| is set on the libcurl CURL handle
77// used to configure the request, using the the CURLOPT_HEADERDATA option. Note,
78// from the libcurl documentation: This callback is being called for all the
79// responses received from the proxy server after intiating the connection
80// request. Multiple responses can be received in an authentication sequence.
81// Only the last response's headers should be forwarded to the System-proxy
82// client. The header callback will be called once for each header and only
83// complete header lines are passed on to the callback.
84static size_t WriteHeadersCallback(char* contents,
85 size_t size,
86 size_t nmemb,
87 void* userdata) {
88 std::vector<char>* vec = (std::vector<char>*)userdata;
89
90 // Check if we are receiving a new HTTP message (after the last one was
91 // terminated with an empty line).
Andreea Costinas90b71642020-06-12 10:18:25 +020092 if (IsEndingWithHttpEmptyLine(base::StringPiece(vec->data(), vec->size()))) {
Andreea Costinasa2246592020-04-12 23:24:01 +020093 VLOG(1) << "Removing the http reply headers from the server "
94 << base::StringPiece(vec->data(), vec->size());
95 vec->clear();
Andreea Costinase45d54b2020-03-10 09:21:14 +010096 }
Andreea Costinasa2246592020-04-12 23:24:01 +020097 vec->insert(vec->end(), contents, contents + (nmemb * size));
Andreea Costinase45d54b2020-03-10 09:21:14 +010098 return size * nmemb;
99}
100
Andreea Costinasa2246592020-04-12 23:24:01 +0200101// CONNECT requests may have a reply body. This method will capture the reply
102// and save it in |userdata|. |userdata| is set on the libcurl CURL handle
103// used to configure the request, using the the CURLOPT_WRITEDATA option.
104static size_t WriteCallback(char* contents,
105 size_t size,
106 size_t nmemb,
107 void* userdata) {
108 std::vector<char>* vec = (std::vector<char>*)userdata;
109 vec->insert(vec->end(), contents, contents + (nmemb * size));
110 return size * nmemb;
111}
112
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200113// This callback receives debug information from curl, as specified in the
114// `type` argument (e.g. incoming or outgoing HTTP headers, SSL data).
115static size_t WriteDebugInfoCallback(CURL* handle,
116 curl_infotype type,
117 char* contents,
118 size_t size,
119 void* userdata) {
120 // We're only interested in outgoing headers for testing.
121 if (type != CURLINFO_HEADER_OUT)
122 return 0;
123 std::string* headers = (std::string*)userdata;
124 *headers = std::string(contents, size);
125 return 0;
126}
127
Andreea Costinase45d54b2020-03-10 09:21:14 +0100128ProxyConnectJob::ProxyConnectJob(
Garrick Evans3388a032020-03-24 11:25:55 +0900129 std::unique_ptr<patchpanel::Socket> socket,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100130 const std::string& credentials,
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200131 int64_t curl_auth_schemes,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100132 ResolveProxyCallback resolve_proxy_callback,
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200133 AuthenticationRequiredCallback auth_required_callback,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100134 OnConnectionSetupFinishedCallback setup_finished_callback)
135 : credentials_(credentials),
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200136 curl_auth_schemes_(curl_auth_schemes),
Andreea Costinase45d54b2020-03-10 09:21:14 +0100137 resolve_proxy_callback_(std::move(resolve_proxy_callback)),
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200138 auth_required_callback_(std::move(auth_required_callback)),
Andreea Costinas08a5d182020-04-29 22:12:47 +0200139 setup_finished_callback_(std::move(setup_finished_callback)),
140 // Safe to use |base::Unretained| because the callback will be canceled
141 // when it goes out of scope.
142 client_connect_timeout_callback_(base::Bind(
Andreea Costinased9e6122020-08-12 12:06:19 +0200143 &ProxyConnectJob::OnClientConnectTimeout, base::Unretained(this))),
144 credentials_request_timeout_callback_(base::Bind(
145 &ProxyConnectJob::OnAuthenticationTimeout, base::Unretained(this))) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100146 client_socket_ = std::move(socket);
147}
148
149ProxyConnectJob::~ProxyConnectJob() = default;
150
151bool ProxyConnectJob::Start() {
152 // Make the socket non-blocking.
153 if (!base::SetNonBlocking(client_socket_->fd())) {
Andreea Costinas435851b2020-05-25 14:18:41 +0200154 PLOG(ERROR) << *this << " Failed to mark the socket as non-blocking";
Andreea Costinase45d54b2020-03-10 09:21:14 +0100155 client_socket_->SendTo(kHttpInternalServerError.data(),
156 kHttpInternalServerError.size());
157 return false;
158 }
Andreea Costinas08a5d182020-04-29 22:12:47 +0200159 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
160 FROM_HERE, client_connect_timeout_callback_.callback(),
161 kWaitClientConnectTimeout);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100162 read_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinas833eb7c2020-06-12 11:09:15 +0200163 client_socket_->fd(), base::Bind(&ProxyConnectJob::OnClientReadReady,
164 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100165 return true;
166}
167
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200168void ProxyConnectJob::StoreRequestHeadersForTesting() {
169 store_headers_for_testing_ = true;
170}
171std::string ProxyConnectJob::GetRequestHeadersForTesting() {
172 return request_headers_for_testing_;
173}
174
Andreea Costinase45d54b2020-03-10 09:21:14 +0100175void ProxyConnectJob::OnClientReadReady() {
Andreea Costinas435851b2020-05-25 14:18:41 +0200176 // The first message should be a HTTP CONNECT request.
177 std::vector<char> buf(kMaxHttpRequestHeadersSize);
178 size_t read_byte_count = 0;
179
180 read_byte_count = client_socket_->RecvFrom(buf.data(), buf.size());
181 if (read_byte_count < 0) {
182 LOG(ERROR) << *this << " Failure to read client request";
183 OnError(kHttpBadRequest);
184 return;
185 }
186 connect_data_.insert(connect_data_.end(), buf.begin(),
187 buf.begin() + read_byte_count);
188
189 std::vector<char> connect_request, payload_data;
190 if (!ExtractHTTPRequest(connect_data_, &connect_request, &payload_data)) {
191 LOG(INFO) << "Received partial HTTP request";
192 return;
193 }
194 connect_data_ = payload_data;
195 HandleClientHTTPRequest(
196 base::StringPiece(connect_request.data(), connect_request.size()));
197}
198
199void ProxyConnectJob::HandleClientHTTPRequest(
200 const base::StringPiece& http_request) {
Andreea Costinas08a5d182020-04-29 22:12:47 +0200201 if (!read_watcher_) {
202 // The connection has timed out while waiting for the client's HTTP CONNECT
203 // request. See |OnClientConnectTimeout|.
204 return;
205 }
206 client_connect_timeout_callback_.Cancel();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100207 // Stop watching.
208 read_watcher_.reset();
Andreea Costinas435851b2020-05-25 14:18:41 +0200209 target_url_ = GetUriAuthorityFromHttpHeader(http_request);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100210 if (target_url_.empty()) {
Andreea Costinas435851b2020-05-25 14:18:41 +0200211 std::string encoded;
212 base::Base64Encode(http_request, &encoded);
213 LOG(ERROR) << *this << " Failed to parse HTTP CONNECT request " << encoded;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100214 OnError(kHttpBadRequest);
215 return;
216 }
217
Andreea Costinasa89309d2020-05-08 15:51:12 +0200218 // The proxy resolution service in Chrome expects a proper URL, formatted as
219 // scheme://host:port. It's safe to assume only https will be used for the
220 // target url.
Andreea Costinase45d54b2020-03-10 09:21:14 +0100221 std::move(resolve_proxy_callback_)
Andreea Costinasa89309d2020-05-08 15:51:12 +0200222 .Run(base::StringPrintf("https://%s", target_url_.c_str()),
223 base::Bind(&ProxyConnectJob::OnProxyResolution,
Andreea Costinas833eb7c2020-06-12 11:09:15 +0200224 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100225}
226
Andreea Costinase45d54b2020-03-10 09:21:14 +0100227void ProxyConnectJob::OnProxyResolution(
228 const std::list<std::string>& proxy_servers) {
229 proxy_servers_ = proxy_servers;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200230 DoCurlServerConnection();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100231}
232
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200233void ProxyConnectJob::AuthenticationRequired(
234 const std::vector<char>& http_response_headers) {
235 DCHECK(!proxy_servers_.empty());
236 SchemeRealmPairList scheme_realm_pairs = ParseAuthChallenge(base::StringPiece(
237 http_response_headers.data(), http_response_headers.size()));
238 if (scheme_realm_pairs.empty()) {
239 LOG(ERROR) << "Failed to parse authentication challenge";
240 OnError(kHttpBadGateway);
241 return;
242 }
243
Andreea Costinased9e6122020-08-12 12:06:19 +0200244 if (!authentication_timer_started_) {
245 authentication_timer_started_ = true;
246 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
247 FROM_HERE, credentials_request_timeout_callback_.callback(),
248 kCredentialsRequestTimeout);
249 }
250
251 auth_required_callback_.Run(
252 proxy_servers_.front(), scheme_realm_pairs.front().first,
253 scheme_realm_pairs.front().second, credentials_,
254 base::BindRepeating(&ProxyConnectJob::OnAuthCredentialsProvided,
255 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200256}
257
258void ProxyConnectJob::OnAuthCredentialsProvided(
259 const std::string& credentials) {
Andreea Costinased9e6122020-08-12 12:06:19 +0200260 // If no credentials were returned or if the same bad credentials were
261 // returned twice, quit the connection. This is to ensure that bad credentials
262 // acquired from the Network Service won't trigger an authentication loop.
263 if (credentials.empty() || credentials_ == credentials) {
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200264 SendHttpResponseToClient(/* http_response_headers= */ {},
265 /* http_response_body= */ {});
266 std::move(setup_finished_callback_).Run(nullptr, this);
267 return;
268 }
269 credentials_ = credentials;
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200270 // Covers the case for which `curl_auth_schemes_` was initialized with policy
271 // set schemes which are not supported by the remote remote server.
272 curl_auth_schemes_ = CURLAUTH_ANY;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200273 VLOG(1) << "Connecting to the remote server with provided credentials";
274 DoCurlServerConnection();
275}
276
277bool ProxyConnectJob::AreAuthCredentialsRequired(CURL* easyhandle) {
278 if (http_response_code_ != kHttpCodeProxyAuthRequired) {
279 return false;
280 }
281
282 CURLcode res;
283 int64_t server_proxy_auth_scheme = 0;
284 res = curl_easy_getinfo(easyhandle, CURLINFO_PROXYAUTH_AVAIL,
285 &server_proxy_auth_scheme);
286 if (res != CURLE_OK || !server_proxy_auth_scheme) {
287 return false;
288 }
289
290 // If kerberos is enabled, then we need to wait for the user to request a
291 // kerberos ticket from Chrome.
292 return !(server_proxy_auth_scheme & CURLAUTH_NEGOTIATE);
293}
294
295void ProxyConnectJob::DoCurlServerConnection() {
296 DCHECK(!proxy_servers_.empty());
Andreea Costinase45d54b2020-03-10 09:21:14 +0100297 CURL* easyhandle = curl_easy_init();
298 CURLcode res;
Andreea Costinasa2246592020-04-12 23:24:01 +0200299 curl_socket_t newSocket = -1;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100300
301 if (!easyhandle) {
302 // Unfortunately it's not possible to get the failure reason.
303 LOG(ERROR) << *this << " Failure to create curl handle.";
304 curl_easy_cleanup(easyhandle);
305 OnError(kHttpInternalServerError);
306 return;
307 }
308 curl_easy_setopt(easyhandle, CURLOPT_URL, target_url_.c_str());
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200309 std::vector<char> http_response_headers;
310 std::vector<char> http_response_body;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200311
312 if (proxy_servers_.front().c_str() != brillo::http::kDirectProxy) {
313 curl_easy_setopt(easyhandle, CURLOPT_PROXY, proxy_servers_.front().c_str());
Andreea Costinase45d54b2020-03-10 09:21:14 +0100314 curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, 1L);
315 curl_easy_setopt(easyhandle, CURLOPT_CONNECT_ONLY, 1);
316 // Allow libcurl to pick authentication method. Curl will use the most
317 // secure one the remote site claims to support.
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200318 curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, curl_auth_schemes_);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100319 curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, credentials_.c_str());
320 }
321 curl_easy_setopt(easyhandle, CURLOPT_CONNECTTIMEOUT_MS,
322 kCurlConnectTimeout.InMilliseconds());
Andreea Costinasa2246592020-04-12 23:24:01 +0200323 curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, WriteHeadersCallback);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200324 curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &http_response_headers);
Andreea Costinasa2246592020-04-12 23:24:01 +0200325 curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, WriteCallback);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200326 curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &http_response_body);
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200327 if (store_headers_for_testing_) {
328 curl_easy_setopt(easyhandle, CURLOPT_DEBUGFUNCTION, WriteDebugInfoCallback);
329 curl_easy_setopt(easyhandle, CURLOPT_DEBUGDATA,
330 &request_headers_for_testing_);
331 // The DEBUGFUNCTION has no effect until we enable VERBOSE.
332 curl_easy_setopt(easyhandle, CURLOPT_VERBOSE, 1L);
333 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100334 res = curl_easy_perform(easyhandle);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200335 curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE,
336 &http_response_code_);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100337
338 if (res != CURLE_OK) {
Andreea Costinas90b71642020-06-12 10:18:25 +0200339 LOG(ERROR) << *this << " curl_easy_perform() failed with error: "
340 << curl_easy_strerror(res);
Andreea Costinased9e6122020-08-12 12:06:19 +0200341 if (AreAuthCredentialsRequired(easyhandle)) {
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200342 AuthenticationRequired(http_response_headers);
343 curl_easy_cleanup(easyhandle);
344 return;
345 }
Andreea Costinased9e6122020-08-12 12:06:19 +0200346 credentials_request_timeout_callback_.Cancel();
347
Andreea Costinase45d54b2020-03-10 09:21:14 +0100348 curl_easy_cleanup(easyhandle);
Andreea Costinasa2246592020-04-12 23:24:01 +0200349
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200350 SendHttpResponseToClient(/* http_response_headers= */ {},
351 /* http_response_body= */ {});
352 std::move(setup_finished_callback_).Run(nullptr, this);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100353 return;
354 }
Andreea Costinased9e6122020-08-12 12:06:19 +0200355 credentials_request_timeout_callback_.Cancel();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100356 // Extract the socket from the curl handle.
357 res = curl_easy_getinfo(easyhandle, CURLINFO_ACTIVESOCKET, &newSocket);
358 if (res != CURLE_OK) {
359 LOG(ERROR) << *this << " Failed to get socket from curl with error: "
360 << curl_easy_strerror(res);
361 curl_easy_cleanup(easyhandle);
362 OnError(kHttpBadGateway);
363 return;
364 }
365
366 ScopedCurlEasyhandle scoped_handle(easyhandle, FreeCurlEasyhandle());
367 auto server_conn = std::make_unique<CurlSocket>(base::ScopedFD(newSocket),
368 std::move(scoped_handle));
369
370 // Send the server reply to the client. If the connection is successful, the
Andreea Costinasa2246592020-04-12 23:24:01 +0200371 // reply headers should be "HTTP/1.1 200 Connection Established".
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200372 if (!SendHttpResponseToClient(http_response_headers, http_response_body)) {
373 std::move(setup_finished_callback_).Run(nullptr, this);
Andreea Costinasa2246592020-04-12 23:24:01 +0200374 return;
375 }
Andreea Costinas435851b2020-05-25 14:18:41 +0200376 // Send the buffered playload data to the remote server.
377 if (!connect_data_.empty()) {
378 server_conn->SendTo(connect_data_.data(), connect_data_.size());
379 connect_data_.clear();
380 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100381
Andreea-Elena Costinasfae5c152020-09-28 18:18:31 +0000382 auto fwd = std::make_unique<patchpanel::SocketForwarder>(
383 base::StringPrintf("%d-%d", client_socket_->fd(), server_conn->fd()),
384 std::move(client_socket_), std::move(server_conn));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100385 // Start forwarding data between sockets.
386 fwd->Start();
387 std::move(setup_finished_callback_).Run(std::move(fwd), this);
388}
389
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200390bool ProxyConnectJob::SendHttpResponseToClient(
391 const std::vector<char>& http_response_headers,
392 const std::vector<char>& http_response_body) {
393 if (http_response_code_ == 0) {
394 // No HTTP CONNECT response code is available.
395 return client_socket_->SendTo(kHttpInternalServerError.data(),
396 kHttpInternalServerError.size());
397 }
398
399 if (http_response_code_ == kHttpCodeProxyAuthRequired) {
400 // This will be a hint for the user to authenticate via the Browser or
401 // acquire a Kerberos ticket.
402 return client_socket_->SendTo(kHttpProxyAuthRequired.data(),
403 kHttpProxyAuthRequired.size());
404 }
405
406 if (http_response_code_ >= 400) {
407 VLOG(1) << "Failed to set up HTTP tunnel with code " << http_response_code_;
408 std::string http_error = base::StringPrintf(
409 kHttpErrorTunnelFailed, std::to_string(http_response_code_).c_str());
410 return client_socket_->SendTo(http_error.c_str(), http_error.size());
411 }
412
413 if (http_response_headers.empty()) {
414 return client_socket_->SendTo(kHttpInternalServerError.data(),
415 kHttpInternalServerError.size());
416 }
417
418 VLOG(1) << "Sending server reply to client";
419 if (!client_socket_->SendTo(http_response_headers.data(),
420 http_response_headers.size())) {
421 PLOG(ERROR) << "Failed to send HTTP server response headers to client";
422 return false;
423 }
424 if (!http_response_body.empty()) {
425 if (!client_socket_->SendTo(http_response_body.data(),
426 http_response_body.size())) {
427 PLOG(ERROR) << "Failed to send HTTP server response payload to client";
428 return false;
429 }
430 }
431 return true;
432}
433
Andreea Costinase45d54b2020-03-10 09:21:14 +0100434void ProxyConnectJob::OnError(const std::string_view& http_error_message) {
435 client_socket_->SendTo(http_error_message.data(), http_error_message.size());
436 std::move(setup_finished_callback_).Run(nullptr, this);
437}
438
Andreea Costinas08a5d182020-04-29 22:12:47 +0200439void ProxyConnectJob::OnClientConnectTimeout() {
440 // Stop listening for client connect requests.
441 read_watcher_.reset();
442 LOG(ERROR) << *this
443 << " Connection timed out while waiting for the client to send a "
Andreea Costinas435851b2020-05-25 14:18:41 +0200444 "connect request";
Andreea Costinas08a5d182020-04-29 22:12:47 +0200445 OnError(kHttpConnectionTimeout);
446}
447
Andreea Costinased9e6122020-08-12 12:06:19 +0200448void ProxyConnectJob::OnAuthenticationTimeout() {
449 LOG(ERROR)
450 << *this
451 << "The connect job timed out while waiting for proxy authentication "
452 "credentials";
453 OnError(kHttpProxyAuthRequired);
454}
455
Andreea Costinase45d54b2020-03-10 09:21:14 +0100456std::ostream& operator<<(std::ostream& stream, const ProxyConnectJob& job) {
457 stream << "{fd: " << job.client_socket_->fd();
458 if (!job.target_url_.empty()) {
459 stream << ", url: " << job.target_url_;
460 }
461 stream << "}";
462 return stream;
463}
464
465} // namespace system_proxy