blob: e75846d8ec9b84527d97ac781d9ffe2444d079a2 [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>
Andreea Costinase45d54b2020-03-10 09:21:14 +010015#include <base/callback_helpers.h>
Qijiang Fan713061e2021-03-08 15:45:12 +090016#include <base/check.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010017#include <base/files/file_util.h>
18#include <base/strings/stringprintf.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010019#include <base/strings/string_util.h>
20#include <base/time/time.h>
Andreea Costinas08a5d182020-04-29 22:12:47 +020021#include <base/threading/thread.h>
22#include <base/threading/thread_task_runner_handle.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010023#include <brillo/http/http_transport.h>
Garrick Evanscd8c2972020-04-14 14:35:52 +090024#include <chromeos/patchpanel/net_util.h>
25#include <chromeos/patchpanel/socket.h>
26#include <chromeos/patchpanel/socket_forwarder.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010027
28#include "system-proxy/curl_socket.h"
Andreea Costinas90b71642020-06-12 10:18:25 +020029#include "system-proxy/http_util.h"
Andreea Costinase45d54b2020-03-10 09:21:14 +010030
Garrick Evans2d5e7c92020-06-08 14:14:28 +090031// The libpatchpanel-util library overloads << for socket data structures.
Andreea Costinase45d54b2020-03-10 09:21:14 +010032// By C++'s argument-dependent lookup rules, operators defined in a
33// different namespace are not visible. We need the using directive to make
34// the overload available this namespace.
Garrick Evans3388a032020-03-24 11:25:55 +090035using patchpanel::operator<<;
Andreea Costinase45d54b2020-03-10 09:21:14 +010036
37namespace {
38// There's no RFC recomandation for the max size of http request headers but
39// popular http server implementations (Apache, IIS, Tomcat) set the lower limit
40// to 8000.
41constexpr int kMaxHttpRequestHeadersSize = 8000;
Andreea Costinas350e4aa2020-07-20 20:29:46 +020042constexpr base::TimeDelta kCurlConnectTimeout =
43 base::TimeDelta::FromSeconds(30);
Andreea Costinas08a5d182020-04-29 22:12:47 +020044constexpr base::TimeDelta kWaitClientConnectTimeout =
Andreea Costinas435851b2020-05-25 14:18:41 +020045 base::TimeDelta::FromSeconds(2);
Andreea Costinased9e6122020-08-12 12:06:19 +020046// Time to wait for proxy authentication credentials to be fetched from the
47// browser. The credentials are retrieved either from the Network Service or, if
48// the Network Service doesn't have them, directly from the user via a login
49// dialogue.
50constexpr base::TimeDelta kCredentialsRequestTimeout =
51 base::TimeDelta::FromMinutes(1);
Andreea Costinase45d54b2020-03-10 09:21:14 +010052
Andreea Costinasf90a4c02020-06-12 22:30:51 +020053constexpr int64_t kHttpCodeProxyAuthRequired = 407;
54
Andreea Costinase45d54b2020-03-10 09:21:14 +010055// HTTP error codes and messages with origin information for debugging (RFC723,
56// section 6.1).
57const std::string_view kHttpBadRequest =
58 "HTTP/1.1 400 Bad Request - Origin: local proxy\r\n\r\n";
Andreea Costinas08a5d182020-04-29 22:12:47 +020059const std::string_view kHttpConnectionTimeout =
60 "HTTP/1.1 408 Request Timeout - Origin: local proxy\r\n\r\n";
Andreea Costinase45d54b2020-03-10 09:21:14 +010061const std::string_view kHttpInternalServerError =
62 "HTTP/1.1 500 Internal Server Error - Origin: local proxy\r\n\r\n";
63const std::string_view kHttpBadGateway =
64 "HTTP/1.1 502 Bad Gateway - Origin: local proxy\r\n\r\n";
Andreea Costinasf90a4c02020-06-12 22:30:51 +020065const std::string_view kHttpProxyAuthRequired =
66 "HTTP/1.1 407 Credentials required - Origin: local proxy\r\n\r\n";
67constexpr char kHttpErrorTunnelFailed[] =
68 "HTTP/1.1 %s Error creating tunnel - Origin: local proxy\r\n\r\n";
Andreea Costinas90b71642020-06-12 10:18:25 +020069} // namespace
Andreea Costinasa2246592020-04-12 23:24:01 +020070
Andreea Costinas90b71642020-06-12 10:18:25 +020071namespace system_proxy {
Andreea Costinasa2246592020-04-12 23:24:01 +020072// CURLOPT_HEADERFUNCTION callback implementation that only returns the headers
73// from the last response sent by the sever. This is to make sure that we
74// send back valid HTTP replies and auhentication data from the HTTP messages is
75// not being leaked to the client. |userdata| is set on the libcurl CURL handle
76// used to configure the request, using the the CURLOPT_HEADERDATA option. Note,
77// from the libcurl documentation: This callback is being called for all the
78// responses received from the proxy server after intiating the connection
79// request. Multiple responses can be received in an authentication sequence.
80// Only the last response's headers should be forwarded to the System-proxy
81// client. The header callback will be called once for each header and only
82// complete header lines are passed on to the callback.
83static size_t WriteHeadersCallback(char* contents,
84 size_t size,
85 size_t nmemb,
86 void* userdata) {
87 std::vector<char>* vec = (std::vector<char>*)userdata;
88
89 // Check if we are receiving a new HTTP message (after the last one was
90 // terminated with an empty line).
Andreea Costinas90b71642020-06-12 10:18:25 +020091 if (IsEndingWithHttpEmptyLine(base::StringPiece(vec->data(), vec->size()))) {
Andreea Costinasa2246592020-04-12 23:24:01 +020092 VLOG(1) << "Removing the http reply headers from the server "
93 << base::StringPiece(vec->data(), vec->size());
94 vec->clear();
Andreea Costinase45d54b2020-03-10 09:21:14 +010095 }
Andreea Costinasa2246592020-04-12 23:24:01 +020096 vec->insert(vec->end(), contents, contents + (nmemb * size));
Andreea Costinase45d54b2020-03-10 09:21:14 +010097 return size * nmemb;
98}
99
Andreea Costinasa2246592020-04-12 23:24:01 +0200100// CONNECT requests may have a reply body. This method will capture the reply
101// and save it in |userdata|. |userdata| is set on the libcurl CURL handle
102// used to configure the request, using the the CURLOPT_WRITEDATA option.
103static size_t WriteCallback(char* contents,
104 size_t size,
105 size_t nmemb,
106 void* userdata) {
107 std::vector<char>* vec = (std::vector<char>*)userdata;
108 vec->insert(vec->end(), contents, contents + (nmemb * size));
109 return size * nmemb;
110}
111
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200112// This callback receives debug information from curl, as specified in the
113// `type` argument (e.g. incoming or outgoing HTTP headers, SSL data).
114static size_t WriteDebugInfoCallback(CURL* handle,
115 curl_infotype type,
116 char* contents,
117 size_t size,
118 void* userdata) {
119 // We're only interested in outgoing headers for testing.
120 if (type != CURLINFO_HEADER_OUT)
121 return 0;
122 std::string* headers = (std::string*)userdata;
123 *headers = std::string(contents, size);
124 return 0;
125}
126
Andreea Costinase45d54b2020-03-10 09:21:14 +0100127ProxyConnectJob::ProxyConnectJob(
Garrick Evans3388a032020-03-24 11:25:55 +0900128 std::unique_ptr<patchpanel::Socket> socket,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100129 const std::string& credentials,
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200130 int64_t curl_auth_schemes,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100131 ResolveProxyCallback resolve_proxy_callback,
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200132 AuthenticationRequiredCallback auth_required_callback,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100133 OnConnectionSetupFinishedCallback setup_finished_callback)
134 : credentials_(credentials),
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200135 curl_auth_schemes_(curl_auth_schemes),
Andreea Costinase45d54b2020-03-10 09:21:14 +0100136 resolve_proxy_callback_(std::move(resolve_proxy_callback)),
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200137 auth_required_callback_(std::move(auth_required_callback)),
Andreea Costinas08a5d182020-04-29 22:12:47 +0200138 setup_finished_callback_(std::move(setup_finished_callback)),
139 // Safe to use |base::Unretained| because the callback will be canceled
140 // when it goes out of scope.
141 client_connect_timeout_callback_(base::Bind(
Andreea Costinased9e6122020-08-12 12:06:19 +0200142 &ProxyConnectJob::OnClientConnectTimeout, base::Unretained(this))),
143 credentials_request_timeout_callback_(base::Bind(
144 &ProxyConnectJob::OnAuthenticationTimeout, base::Unretained(this))) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100145 client_socket_ = std::move(socket);
146}
147
148ProxyConnectJob::~ProxyConnectJob() = default;
149
150bool ProxyConnectJob::Start() {
151 // Make the socket non-blocking.
152 if (!base::SetNonBlocking(client_socket_->fd())) {
Andreea Costinas435851b2020-05-25 14:18:41 +0200153 PLOG(ERROR) << *this << " Failed to mark the socket as non-blocking";
Andreea Costinase45d54b2020-03-10 09:21:14 +0100154 client_socket_->SendTo(kHttpInternalServerError.data(),
155 kHttpInternalServerError.size());
156 return false;
157 }
Andreea Costinas08a5d182020-04-29 22:12:47 +0200158 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
159 FROM_HERE, client_connect_timeout_callback_.callback(),
160 kWaitClientConnectTimeout);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100161 read_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinas833eb7c2020-06-12 11:09:15 +0200162 client_socket_->fd(), base::Bind(&ProxyConnectJob::OnClientReadReady,
163 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100164 return true;
165}
166
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200167void ProxyConnectJob::StoreRequestHeadersForTesting() {
168 store_headers_for_testing_ = true;
169}
170std::string ProxyConnectJob::GetRequestHeadersForTesting() {
171 return request_headers_for_testing_;
172}
173
Andreea Costinase45d54b2020-03-10 09:21:14 +0100174void ProxyConnectJob::OnClientReadReady() {
Andreea Costinas435851b2020-05-25 14:18:41 +0200175 // The first message should be a HTTP CONNECT request.
176 std::vector<char> buf(kMaxHttpRequestHeadersSize);
177 size_t read_byte_count = 0;
178
179 read_byte_count = client_socket_->RecvFrom(buf.data(), buf.size());
180 if (read_byte_count < 0) {
181 LOG(ERROR) << *this << " Failure to read client request";
182 OnError(kHttpBadRequest);
183 return;
184 }
185 connect_data_.insert(connect_data_.end(), buf.begin(),
186 buf.begin() + read_byte_count);
187
188 std::vector<char> connect_request, payload_data;
189 if (!ExtractHTTPRequest(connect_data_, &connect_request, &payload_data)) {
190 LOG(INFO) << "Received partial HTTP request";
191 return;
192 }
193 connect_data_ = payload_data;
194 HandleClientHTTPRequest(
195 base::StringPiece(connect_request.data(), connect_request.size()));
196}
197
198void ProxyConnectJob::HandleClientHTTPRequest(
199 const base::StringPiece& http_request) {
Andreea Costinas08a5d182020-04-29 22:12:47 +0200200 if (!read_watcher_) {
201 // The connection has timed out while waiting for the client's HTTP CONNECT
202 // request. See |OnClientConnectTimeout|.
203 return;
204 }
205 client_connect_timeout_callback_.Cancel();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100206 // Stop watching.
207 read_watcher_.reset();
Andreea Costinas435851b2020-05-25 14:18:41 +0200208 target_url_ = GetUriAuthorityFromHttpHeader(http_request);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100209 if (target_url_.empty()) {
Andreea Costinas435851b2020-05-25 14:18:41 +0200210 std::string encoded;
211 base::Base64Encode(http_request, &encoded);
212 LOG(ERROR) << *this << " Failed to parse HTTP CONNECT request " << encoded;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100213 OnError(kHttpBadRequest);
214 return;
215 }
216
Andreea Costinasa89309d2020-05-08 15:51:12 +0200217 // The proxy resolution service in Chrome expects a proper URL, formatted as
218 // scheme://host:port. It's safe to assume only https will be used for the
219 // target url.
Andreea Costinase45d54b2020-03-10 09:21:14 +0100220 std::move(resolve_proxy_callback_)
Andreea Costinasa89309d2020-05-08 15:51:12 +0200221 .Run(base::StringPrintf("https://%s", target_url_.c_str()),
222 base::Bind(&ProxyConnectJob::OnProxyResolution,
Andreea Costinas833eb7c2020-06-12 11:09:15 +0200223 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100224}
225
Andreea Costinase45d54b2020-03-10 09:21:14 +0100226void ProxyConnectJob::OnProxyResolution(
227 const std::list<std::string>& proxy_servers) {
228 proxy_servers_ = proxy_servers;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200229 DoCurlServerConnection();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100230}
231
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200232void ProxyConnectJob::AuthenticationRequired(
233 const std::vector<char>& http_response_headers) {
234 DCHECK(!proxy_servers_.empty());
235 SchemeRealmPairList scheme_realm_pairs = ParseAuthChallenge(base::StringPiece(
236 http_response_headers.data(), http_response_headers.size()));
237 if (scheme_realm_pairs.empty()) {
238 LOG(ERROR) << "Failed to parse authentication challenge";
239 OnError(kHttpBadGateway);
240 return;
241 }
242
Andreea Costinased9e6122020-08-12 12:06:19 +0200243 if (!authentication_timer_started_) {
244 authentication_timer_started_ = true;
245 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
246 FROM_HERE, credentials_request_timeout_callback_.callback(),
247 kCredentialsRequestTimeout);
248 }
249
250 auth_required_callback_.Run(
251 proxy_servers_.front(), scheme_realm_pairs.front().first,
252 scheme_realm_pairs.front().second, credentials_,
253 base::BindRepeating(&ProxyConnectJob::OnAuthCredentialsProvided,
254 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200255}
256
257void ProxyConnectJob::OnAuthCredentialsProvided(
258 const std::string& credentials) {
Andreea Costinased9e6122020-08-12 12:06:19 +0200259 // If no credentials were returned or if the same bad credentials were
260 // returned twice, quit the connection. This is to ensure that bad credentials
261 // acquired from the Network Service won't trigger an authentication loop.
262 if (credentials.empty() || credentials_ == credentials) {
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200263 SendHttpResponseToClient(/* http_response_headers= */ {},
264 /* http_response_body= */ {});
265 std::move(setup_finished_callback_).Run(nullptr, this);
266 return;
267 }
268 credentials_ = credentials;
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200269 // Covers the case for which `curl_auth_schemes_` was initialized with policy
270 // set schemes which are not supported by the remote remote server.
271 curl_auth_schemes_ = CURLAUTH_ANY;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200272 VLOG(1) << "Connecting to the remote server with provided credentials";
273 DoCurlServerConnection();
274}
275
276bool ProxyConnectJob::AreAuthCredentialsRequired(CURL* easyhandle) {
277 if (http_response_code_ != kHttpCodeProxyAuthRequired) {
278 return false;
279 }
280
281 CURLcode res;
282 int64_t server_proxy_auth_scheme = 0;
283 res = curl_easy_getinfo(easyhandle, CURLINFO_PROXYAUTH_AVAIL,
284 &server_proxy_auth_scheme);
285 if (res != CURLE_OK || !server_proxy_auth_scheme) {
286 return false;
287 }
288
289 // If kerberos is enabled, then we need to wait for the user to request a
290 // kerberos ticket from Chrome.
291 return !(server_proxy_auth_scheme & CURLAUTH_NEGOTIATE);
292}
293
294void ProxyConnectJob::DoCurlServerConnection() {
295 DCHECK(!proxy_servers_.empty());
Andreea Costinase45d54b2020-03-10 09:21:14 +0100296 CURL* easyhandle = curl_easy_init();
297 CURLcode res;
Andreea Costinasa2246592020-04-12 23:24:01 +0200298 curl_socket_t newSocket = -1;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100299
300 if (!easyhandle) {
301 // Unfortunately it's not possible to get the failure reason.
302 LOG(ERROR) << *this << " Failure to create curl handle.";
303 curl_easy_cleanup(easyhandle);
304 OnError(kHttpInternalServerError);
305 return;
306 }
307 curl_easy_setopt(easyhandle, CURLOPT_URL, target_url_.c_str());
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200308 std::vector<char> http_response_headers;
309 std::vector<char> http_response_body;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200310
311 if (proxy_servers_.front().c_str() != brillo::http::kDirectProxy) {
312 curl_easy_setopt(easyhandle, CURLOPT_PROXY, proxy_servers_.front().c_str());
Andreea Costinase45d54b2020-03-10 09:21:14 +0100313 curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, 1L);
314 curl_easy_setopt(easyhandle, CURLOPT_CONNECT_ONLY, 1);
315 // Allow libcurl to pick authentication method. Curl will use the most
316 // secure one the remote site claims to support.
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200317 curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, curl_auth_schemes_);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100318 curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, credentials_.c_str());
319 }
320 curl_easy_setopt(easyhandle, CURLOPT_CONNECTTIMEOUT_MS,
321 kCurlConnectTimeout.InMilliseconds());
Andreea Costinasa2246592020-04-12 23:24:01 +0200322 curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, WriteHeadersCallback);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200323 curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &http_response_headers);
Andreea Costinasa2246592020-04-12 23:24:01 +0200324 curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, WriteCallback);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200325 curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &http_response_body);
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200326 if (store_headers_for_testing_) {
327 curl_easy_setopt(easyhandle, CURLOPT_DEBUGFUNCTION, WriteDebugInfoCallback);
328 curl_easy_setopt(easyhandle, CURLOPT_DEBUGDATA,
329 &request_headers_for_testing_);
330 // The DEBUGFUNCTION has no effect until we enable VERBOSE.
331 curl_easy_setopt(easyhandle, CURLOPT_VERBOSE, 1L);
332 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100333 res = curl_easy_perform(easyhandle);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200334 curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE,
335 &http_response_code_);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100336
337 if (res != CURLE_OK) {
Andreea Costinas90b71642020-06-12 10:18:25 +0200338 LOG(ERROR) << *this << " curl_easy_perform() failed with error: "
339 << curl_easy_strerror(res);
Andreea Costinased9e6122020-08-12 12:06:19 +0200340 if (AreAuthCredentialsRequired(easyhandle)) {
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200341 AuthenticationRequired(http_response_headers);
342 curl_easy_cleanup(easyhandle);
343 return;
344 }
Andreea Costinased9e6122020-08-12 12:06:19 +0200345 credentials_request_timeout_callback_.Cancel();
346
Andreea Costinase45d54b2020-03-10 09:21:14 +0100347 curl_easy_cleanup(easyhandle);
Andreea Costinasa2246592020-04-12 23:24:01 +0200348
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200349 SendHttpResponseToClient(/* http_response_headers= */ {},
350 /* http_response_body= */ {});
351 std::move(setup_finished_callback_).Run(nullptr, this);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100352 return;
353 }
Andreea Costinased9e6122020-08-12 12:06:19 +0200354 credentials_request_timeout_callback_.Cancel();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100355 // Extract the socket from the curl handle.
356 res = curl_easy_getinfo(easyhandle, CURLINFO_ACTIVESOCKET, &newSocket);
357 if (res != CURLE_OK) {
358 LOG(ERROR) << *this << " Failed to get socket from curl with error: "
359 << curl_easy_strerror(res);
360 curl_easy_cleanup(easyhandle);
361 OnError(kHttpBadGateway);
362 return;
363 }
364
365 ScopedCurlEasyhandle scoped_handle(easyhandle, FreeCurlEasyhandle());
366 auto server_conn = std::make_unique<CurlSocket>(base::ScopedFD(newSocket),
367 std::move(scoped_handle));
368
369 // Send the server reply to the client. If the connection is successful, the
Andreea Costinasa2246592020-04-12 23:24:01 +0200370 // reply headers should be "HTTP/1.1 200 Connection Established".
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200371 if (!SendHttpResponseToClient(http_response_headers, http_response_body)) {
372 std::move(setup_finished_callback_).Run(nullptr, this);
Andreea Costinasa2246592020-04-12 23:24:01 +0200373 return;
374 }
Andreea Costinas435851b2020-05-25 14:18:41 +0200375 // Send the buffered playload data to the remote server.
376 if (!connect_data_.empty()) {
377 server_conn->SendTo(connect_data_.data(), connect_data_.size());
378 connect_data_.clear();
379 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100380
Andreea-Elena Costinasfae5c152020-09-28 18:18:31 +0000381 auto fwd = std::make_unique<patchpanel::SocketForwarder>(
382 base::StringPrintf("%d-%d", client_socket_->fd(), server_conn->fd()),
383 std::move(client_socket_), std::move(server_conn));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100384 // Start forwarding data between sockets.
385 fwd->Start();
386 std::move(setup_finished_callback_).Run(std::move(fwd), this);
387}
388
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200389bool ProxyConnectJob::SendHttpResponseToClient(
390 const std::vector<char>& http_response_headers,
391 const std::vector<char>& http_response_body) {
392 if (http_response_code_ == 0) {
393 // No HTTP CONNECT response code is available.
394 return client_socket_->SendTo(kHttpInternalServerError.data(),
395 kHttpInternalServerError.size());
396 }
397
398 if (http_response_code_ == kHttpCodeProxyAuthRequired) {
399 // This will be a hint for the user to authenticate via the Browser or
400 // acquire a Kerberos ticket.
401 return client_socket_->SendTo(kHttpProxyAuthRequired.data(),
402 kHttpProxyAuthRequired.size());
403 }
404
405 if (http_response_code_ >= 400) {
406 VLOG(1) << "Failed to set up HTTP tunnel with code " << http_response_code_;
407 std::string http_error = base::StringPrintf(
408 kHttpErrorTunnelFailed, std::to_string(http_response_code_).c_str());
409 return client_socket_->SendTo(http_error.c_str(), http_error.size());
410 }
411
412 if (http_response_headers.empty()) {
413 return client_socket_->SendTo(kHttpInternalServerError.data(),
414 kHttpInternalServerError.size());
415 }
416
417 VLOG(1) << "Sending server reply to client";
418 if (!client_socket_->SendTo(http_response_headers.data(),
419 http_response_headers.size())) {
420 PLOG(ERROR) << "Failed to send HTTP server response headers to client";
421 return false;
422 }
423 if (!http_response_body.empty()) {
424 if (!client_socket_->SendTo(http_response_body.data(),
425 http_response_body.size())) {
426 PLOG(ERROR) << "Failed to send HTTP server response payload to client";
427 return false;
428 }
429 }
430 return true;
431}
432
Andreea Costinase45d54b2020-03-10 09:21:14 +0100433void ProxyConnectJob::OnError(const std::string_view& http_error_message) {
434 client_socket_->SendTo(http_error_message.data(), http_error_message.size());
435 std::move(setup_finished_callback_).Run(nullptr, this);
436}
437
Andreea Costinas08a5d182020-04-29 22:12:47 +0200438void ProxyConnectJob::OnClientConnectTimeout() {
439 // Stop listening for client connect requests.
440 read_watcher_.reset();
441 LOG(ERROR) << *this
442 << " Connection timed out while waiting for the client to send a "
Andreea Costinas435851b2020-05-25 14:18:41 +0200443 "connect request";
Andreea Costinas08a5d182020-04-29 22:12:47 +0200444 OnError(kHttpConnectionTimeout);
445}
446
Andreea Costinased9e6122020-08-12 12:06:19 +0200447void ProxyConnectJob::OnAuthenticationTimeout() {
448 LOG(ERROR)
449 << *this
450 << "The connect job timed out while waiting for proxy authentication "
451 "credentials";
452 OnError(kHttpProxyAuthRequired);
453}
454
Andreea Costinase45d54b2020-03-10 09:21:14 +0100455std::ostream& operator<<(std::ostream& stream, const ProxyConnectJob& job) {
456 stream << "{fd: " << job.client_socket_->fd();
457 if (!job.target_url_.empty()) {
458 stream << ", url: " << job.target_url_;
459 }
460 stream << "}";
461 return stream;
462}
463
464} // namespace system_proxy