http_proxy_connect_job.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. // Copyright 2019 The Chromium 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. #include "net/http/http_proxy_connect_job.h"
  5. #include <memory>
  6. #include <utility>
  7. #include "base/bind.h"
  8. #include "base/callback.h"
  9. #include "base/cxx17_backports.h"
  10. #include "base/metrics/field_trial.h"
  11. #include "base/metrics/field_trial_params.h"
  12. #include "base/metrics/histogram_functions.h"
  13. #include "base/strings/string_number_conversions.h"
  14. #include "base/strings/string_util.h"
  15. #include "base/threading/thread_task_runner_handle.h"
  16. #include "base/values.h"
  17. #include "build/build_config.h"
  18. #include "http_proxy_client_socket.h"
  19. #include "net/base/host_port_pair.h"
  20. #include "net/base/http_user_agent_settings.h"
  21. #include "net/base/net_errors.h"
  22. #include "net/log/net_log_source_type.h"
  23. #include "net/log/net_log_with_source.h"
  24. #include "net/nqe/network_quality_estimator.h"
  25. #include "net/quic/quic_http_utils.h"
  26. #include "net/quic/quic_proxy_client_socket.h"
  27. #include "net/quic/quic_stream_factory.h"
  28. #include "net/socket/client_socket_handle.h"
  29. #include "net/socket/next_proto.h"
  30. #include "net/socket/ssl_client_socket.h"
  31. #include "net/socket/ssl_connect_job.h"
  32. #include "net/socket/transport_client_socket_pool.h"
  33. #include "net/socket/transport_connect_job.h"
  34. #include "net/spdy/spdy_proxy_client_socket.h"
  35. #include "net/spdy/spdy_session.h"
  36. #include "net/spdy/spdy_session_pool.h"
  37. #include "net/spdy/spdy_stream.h"
  38. #include "net/ssl/ssl_cert_request_info.h"
  39. #include "third_party/abseil-cpp/absl/types/optional.h"
  40. #include "third_party/abseil-cpp/absl/types/variant.h"
  41. #include "url/gurl.h"
  42. #include "url/scheme_host_port.h"
  43. namespace net {
  44. namespace {
  45. // HttpProxyConnectJobs will time out after this many seconds. Note this is in
  46. // addition to the timeout for the transport socket.
  47. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
  48. constexpr base::TimeDelta kHttpProxyConnectJobTunnelTimeout = base::Seconds(10);
  49. #else
  50. constexpr base::TimeDelta kHttpProxyConnectJobTunnelTimeout = base::Seconds(30);
  51. #endif
  52. class HttpProxyTimeoutExperiments {
  53. public:
  54. HttpProxyTimeoutExperiments() { Init(); }
  55. ~HttpProxyTimeoutExperiments() = default;
  56. void Init() {
  57. min_proxy_connection_timeout_ =
  58. base::Seconds(GetInt32Param("min_proxy_connection_timeout_seconds", 8));
  59. max_proxy_connection_timeout_ = base::Seconds(
  60. GetInt32Param("max_proxy_connection_timeout_seconds", 30));
  61. ssl_http_rtt_multiplier_ = GetInt32Param("ssl_http_rtt_multiplier", 10);
  62. non_ssl_http_rtt_multiplier_ =
  63. GetInt32Param("non_ssl_http_rtt_multiplier", 5);
  64. DCHECK_LT(0, ssl_http_rtt_multiplier_);
  65. DCHECK_LT(0, non_ssl_http_rtt_multiplier_);
  66. DCHECK_LE(base::TimeDelta(), min_proxy_connection_timeout_);
  67. DCHECK_LE(base::TimeDelta(), max_proxy_connection_timeout_);
  68. DCHECK_LE(min_proxy_connection_timeout_, max_proxy_connection_timeout_);
  69. }
  70. base::TimeDelta min_proxy_connection_timeout() const {
  71. return min_proxy_connection_timeout_;
  72. }
  73. base::TimeDelta max_proxy_connection_timeout() const {
  74. return max_proxy_connection_timeout_;
  75. }
  76. int32_t ssl_http_rtt_multiplier() const { return ssl_http_rtt_multiplier_; }
  77. int32_t non_ssl_http_rtt_multiplier() const {
  78. return non_ssl_http_rtt_multiplier_;
  79. }
  80. private:
  81. // Returns the value of the parameter |param_name| for the field trial
  82. // "NetAdaptiveProxyConnectionTimeout". If the value of the parameter is
  83. // unavailable, then |default_value| is available.
  84. static int32_t GetInt32Param(const std::string& param_name,
  85. int32_t default_value) {
  86. int32_t param;
  87. if (!base::StringToInt(base::GetFieldTrialParamValue(
  88. "NetAdaptiveProxyConnectionTimeout", param_name),
  89. &param)) {
  90. return default_value;
  91. }
  92. return param;
  93. }
  94. // For secure proxies, the connection timeout is set to
  95. // |ssl_http_rtt_multiplier_| times the HTTP RTT estimate. For insecure
  96. // proxies, the connection timeout is set to |non_ssl_http_rtt_multiplier_|
  97. // times the HTTP RTT estimate. In either case, the connection timeout
  98. // is clamped to be between |min_proxy_connection_timeout_| and
  99. // |max_proxy_connection_timeout_|.
  100. base::TimeDelta min_proxy_connection_timeout_;
  101. base::TimeDelta max_proxy_connection_timeout_;
  102. int32_t ssl_http_rtt_multiplier_;
  103. int32_t non_ssl_http_rtt_multiplier_;
  104. };
  105. HttpProxyTimeoutExperiments* GetProxyTimeoutExperiments() {
  106. static HttpProxyTimeoutExperiments proxy_timeout_experiments;
  107. return &proxy_timeout_experiments;
  108. }
  109. } // namespace
  110. HttpProxySocketParams::HttpProxySocketParams(
  111. scoped_refptr<TransportSocketParams> transport_params,
  112. scoped_refptr<SSLSocketParams> ssl_params,
  113. bool is_quic,
  114. const HostPortPair& endpoint,
  115. bool tunnel,
  116. const NetworkTrafficAnnotationTag traffic_annotation,
  117. const NetworkIsolationKey& network_isolation_key)
  118. : transport_params_(std::move(transport_params)),
  119. ssl_params_(std::move(ssl_params)),
  120. is_quic_(is_quic),
  121. endpoint_(endpoint),
  122. tunnel_(tunnel),
  123. network_isolation_key_(network_isolation_key),
  124. traffic_annotation_(traffic_annotation) {
  125. // This is either a connection to an HTTP proxy or an SSL/QUIC proxy.
  126. DCHECK(transport_params_ || ssl_params_);
  127. DCHECK(!transport_params_ || !ssl_params_);
  128. // If connecting to a QUIC proxy, and |ssl_params_| must be valid. This also
  129. // implies |transport_params_| is null, per the above DCHECKs.
  130. if (is_quic_)
  131. DCHECK(ssl_params_);
  132. // Only supports proxy endpoints without scheme for now.
  133. // TODO(crbug.com/1206799): Handle scheme.
  134. if (transport_params_) {
  135. DCHECK(absl::holds_alternative<HostPortPair>(
  136. transport_params_->destination()));
  137. } else {
  138. DCHECK(absl::holds_alternative<HostPortPair>(
  139. ssl_params_->GetDirectConnectionParams()->destination()));
  140. }
  141. }
  142. HttpProxySocketParams::~HttpProxySocketParams() = default;
  143. std::unique_ptr<HttpProxyConnectJob> HttpProxyConnectJob::Factory::Create(
  144. RequestPriority priority,
  145. const SocketTag& socket_tag,
  146. const CommonConnectJobParams* common_connect_job_params,
  147. scoped_refptr<HttpProxySocketParams> params,
  148. ConnectJob::Delegate* delegate,
  149. const NetLogWithSource* net_log) {
  150. return std::make_unique<HttpProxyConnectJob>(
  151. priority, socket_tag, common_connect_job_params, std::move(params),
  152. delegate, net_log);
  153. }
  154. HttpProxyConnectJob::HttpProxyConnectJob(
  155. RequestPriority priority,
  156. const SocketTag& socket_tag,
  157. const CommonConnectJobParams* common_connect_job_params,
  158. scoped_refptr<HttpProxySocketParams> params,
  159. ConnectJob::Delegate* delegate,
  160. const NetLogWithSource* net_log)
  161. : ConnectJob(priority,
  162. socket_tag,
  163. base::TimeDelta() /* The socket takes care of timeouts */,
  164. common_connect_job_params,
  165. delegate,
  166. net_log,
  167. NetLogSourceType::HTTP_PROXY_CONNECT_JOB,
  168. NetLogEventType::HTTP_PROXY_CONNECT_JOB_CONNECT),
  169. params_(std::move(params)),
  170. http_auth_controller_(
  171. params_->tunnel()
  172. ? base::MakeRefCounted<HttpAuthController>(
  173. HttpAuth::AUTH_PROXY,
  174. GURL((params_->ssl_params() ? "https://" : "http://") +
  175. GetDestination().ToString()),
  176. params_->network_isolation_key(),
  177. common_connect_job_params->http_auth_cache,
  178. common_connect_job_params->http_auth_handler_factory,
  179. host_resolver())
  180. : nullptr) {}
  181. HttpProxyConnectJob::~HttpProxyConnectJob() = default;
  182. const RequestPriority HttpProxyConnectJob::kH2QuicTunnelPriority =
  183. DEFAULT_PRIORITY;
  184. LoadState HttpProxyConnectJob::GetLoadState() const {
  185. switch (next_state_) {
  186. case STATE_TRANSPORT_CONNECT_COMPLETE:
  187. return nested_connect_job_->GetLoadState();
  188. case STATE_HTTP_PROXY_CONNECT:
  189. case STATE_HTTP_PROXY_CONNECT_COMPLETE:
  190. case STATE_SPDY_PROXY_CREATE_STREAM:
  191. case STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE:
  192. case STATE_QUIC_PROXY_CREATE_SESSION:
  193. case STATE_QUIC_PROXY_CREATE_STREAM:
  194. case STATE_QUIC_PROXY_CREATE_STREAM_COMPLETE:
  195. case STATE_RESTART_WITH_AUTH:
  196. case STATE_RESTART_WITH_AUTH_COMPLETE:
  197. return LOAD_STATE_ESTABLISHING_PROXY_TUNNEL;
  198. // This state shouldn't be possible to be called in.
  199. case STATE_TRANSPORT_CONNECT:
  200. NOTREACHED();
  201. [[fallthrough]];
  202. case STATE_BEGIN_CONNECT:
  203. case STATE_NONE:
  204. // May be possible for this method to be called after an error, shouldn't
  205. // be called after a successful connect.
  206. break;
  207. }
  208. return LOAD_STATE_IDLE;
  209. }
  210. bool HttpProxyConnectJob::HasEstablishedConnection() const {
  211. if (has_established_connection_)
  212. return true;
  213. // It's possible the nested connect job has established a connection, but
  214. // hasn't completed yet (For example, an SSLConnectJob may be negotiating
  215. // SSL).
  216. if (nested_connect_job_)
  217. return nested_connect_job_->HasEstablishedConnection();
  218. return false;
  219. }
  220. ResolveErrorInfo HttpProxyConnectJob::GetResolveErrorInfo() const {
  221. return resolve_error_info_;
  222. }
  223. bool HttpProxyConnectJob::IsSSLError() const {
  224. return ssl_cert_request_info_ != nullptr;
  225. }
  226. scoped_refptr<SSLCertRequestInfo> HttpProxyConnectJob::GetCertRequestInfo() {
  227. return ssl_cert_request_info_;
  228. }
  229. void HttpProxyConnectJob::OnConnectJobComplete(int result, ConnectJob* job) {
  230. DCHECK_EQ(nested_connect_job_.get(), job);
  231. DCHECK_EQ(next_state_, STATE_TRANSPORT_CONNECT_COMPLETE);
  232. OnIOComplete(result);
  233. }
  234. void HttpProxyConnectJob::OnNeedsProxyAuth(
  235. const HttpResponseInfo& response,
  236. HttpAuthController* auth_controller,
  237. base::OnceClosure restart_with_auth_callback,
  238. ConnectJob* job) {
  239. // None of the nested ConnectJob used by this class can encounter auth
  240. // challenges. Instead, the challenges are returned by the ProxyClientSocket
  241. // implementations after nested_connect_job_ has already established a
  242. // connection.
  243. NOTREACHED();
  244. }
  245. base::TimeDelta HttpProxyConnectJob::AlternateNestedConnectionTimeout(
  246. const HttpProxySocketParams& params,
  247. const NetworkQualityEstimator* network_quality_estimator) {
  248. base::TimeDelta default_alternate_timeout;
  249. // On Android and iOS, a default proxy connection timeout is used instead of
  250. // the actual TCP/SSL timeouts of nested jobs.
  251. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
  252. default_alternate_timeout = kHttpProxyConnectJobTunnelTimeout;
  253. #endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  254. bool is_https = params.ssl_params() != nullptr;
  255. // HTTP proxy connections can't be on top of proxy connections.
  256. DCHECK(!is_https ||
  257. params.ssl_params()->GetConnectionType() == SSLSocketParams::DIRECT);
  258. if (!network_quality_estimator)
  259. return default_alternate_timeout;
  260. absl::optional<base::TimeDelta> http_rtt_estimate =
  261. network_quality_estimator->GetHttpRTT();
  262. if (!http_rtt_estimate)
  263. return default_alternate_timeout;
  264. int32_t multiplier =
  265. is_https ? GetProxyTimeoutExperiments()->ssl_http_rtt_multiplier()
  266. : GetProxyTimeoutExperiments()->non_ssl_http_rtt_multiplier();
  267. base::TimeDelta timeout = multiplier * http_rtt_estimate.value();
  268. // Ensure that connection timeout is between
  269. // |min_proxy_connection_timeout_| and |max_proxy_connection_timeout_|.
  270. return base::clamp(
  271. timeout, GetProxyTimeoutExperiments()->min_proxy_connection_timeout(),
  272. GetProxyTimeoutExperiments()->max_proxy_connection_timeout());
  273. }
  274. base::TimeDelta HttpProxyConnectJob::TunnelTimeoutForTesting() {
  275. return kHttpProxyConnectJobTunnelTimeout;
  276. }
  277. void HttpProxyConnectJob::UpdateFieldTrialParametersForTesting() {
  278. GetProxyTimeoutExperiments()->Init();
  279. }
  280. int HttpProxyConnectJob::ConnectInternal() {
  281. DCHECK_EQ(next_state_, STATE_NONE);
  282. next_state_ = STATE_BEGIN_CONNECT;
  283. return DoLoop(OK);
  284. }
  285. ProxyServer::Scheme HttpProxyConnectJob::GetProxyServerScheme() const {
  286. if (params_->is_quic())
  287. return ProxyServer::SCHEME_QUIC;
  288. if (params_->transport_params())
  289. return ProxyServer::SCHEME_HTTP;
  290. return ProxyServer::SCHEME_HTTPS;
  291. }
  292. void HttpProxyConnectJob::OnIOComplete(int result) {
  293. int rv = DoLoop(result);
  294. if (rv != ERR_IO_PENDING) {
  295. // May delete |this|.
  296. NotifyDelegateOfCompletion(rv);
  297. }
  298. }
  299. void HttpProxyConnectJob::RestartWithAuthCredentials() {
  300. DCHECK(transport_socket_);
  301. DCHECK_EQ(STATE_NONE, next_state_);
  302. // Always do this asynchronously, to avoid re-entrancy.
  303. next_state_ = STATE_RESTART_WITH_AUTH;
  304. base::ThreadTaskRunnerHandle::Get()->PostTask(
  305. FROM_HERE, base::BindOnce(&HttpProxyConnectJob::OnIOComplete,
  306. weak_ptr_factory_.GetWeakPtr(), net::OK));
  307. }
  308. int HttpProxyConnectJob::DoLoop(int result) {
  309. DCHECK_NE(next_state_, STATE_NONE);
  310. int rv = result;
  311. do {
  312. State state = next_state_;
  313. next_state_ = STATE_NONE;
  314. switch (state) {
  315. case STATE_BEGIN_CONNECT:
  316. DCHECK_EQ(OK, rv);
  317. rv = DoBeginConnect();
  318. break;
  319. case STATE_TRANSPORT_CONNECT:
  320. DCHECK_EQ(OK, rv);
  321. rv = DoTransportConnect();
  322. break;
  323. case STATE_TRANSPORT_CONNECT_COMPLETE:
  324. rv = DoTransportConnectComplete(rv);
  325. break;
  326. case STATE_HTTP_PROXY_CONNECT:
  327. DCHECK_EQ(OK, rv);
  328. rv = DoHttpProxyConnect();
  329. break;
  330. case STATE_HTTP_PROXY_CONNECT_COMPLETE:
  331. rv = DoHttpProxyConnectComplete(rv);
  332. break;
  333. case STATE_SPDY_PROXY_CREATE_STREAM:
  334. DCHECK_EQ(OK, rv);
  335. rv = DoSpdyProxyCreateStream();
  336. break;
  337. case STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE:
  338. rv = DoSpdyProxyCreateStreamComplete(rv);
  339. break;
  340. case STATE_QUIC_PROXY_CREATE_SESSION:
  341. DCHECK_EQ(OK, rv);
  342. rv = DoQuicProxyCreateSession();
  343. break;
  344. case STATE_QUIC_PROXY_CREATE_STREAM:
  345. rv = DoQuicProxyCreateStream(rv);
  346. break;
  347. case STATE_QUIC_PROXY_CREATE_STREAM_COMPLETE:
  348. rv = DoQuicProxyCreateStreamComplete(rv);
  349. break;
  350. case STATE_RESTART_WITH_AUTH:
  351. DCHECK_EQ(OK, rv);
  352. rv = DoRestartWithAuth();
  353. break;
  354. case STATE_RESTART_WITH_AUTH_COMPLETE:
  355. rv = DoRestartWithAuthComplete(rv);
  356. break;
  357. default:
  358. NOTREACHED() << "bad state";
  359. rv = ERR_FAILED;
  360. break;
  361. }
  362. } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
  363. return rv;
  364. }
  365. int HttpProxyConnectJob::DoBeginConnect() {
  366. connect_start_time_ = base::TimeTicks::Now();
  367. ResetTimer(
  368. AlternateNestedConnectionTimeout(*params_, network_quality_estimator()));
  369. switch (GetProxyServerScheme()) {
  370. case ProxyServer::SCHEME_QUIC:
  371. next_state_ = STATE_QUIC_PROXY_CREATE_SESSION;
  372. // QUIC connections are always considered to have been established.
  373. // |has_established_connection_| is only used to start retries if a
  374. // connection hasn't been established yet, and QUIC has its own connection
  375. // establishment logic.
  376. has_established_connection_ = true;
  377. break;
  378. case ProxyServer::SCHEME_HTTP:
  379. case ProxyServer::SCHEME_HTTPS:
  380. next_state_ = STATE_TRANSPORT_CONNECT;
  381. break;
  382. default:
  383. NOTREACHED();
  384. }
  385. return OK;
  386. }
  387. int HttpProxyConnectJob::DoTransportConnect() {
  388. ProxyServer::Scheme scheme = GetProxyServerScheme();
  389. if (scheme == ProxyServer::SCHEME_HTTP) {
  390. nested_connect_job_ = std::make_unique<TransportConnectJob>(
  391. priority(), socket_tag(), common_connect_job_params(),
  392. params_->transport_params(), this, &net_log());
  393. } else {
  394. DCHECK_EQ(scheme, ProxyServer::SCHEME_HTTPS);
  395. DCHECK(params_->ssl_params());
  396. // Skip making a new connection if we have an existing HTTP/2 session.
  397. if (params_->tunnel() &&
  398. common_connect_job_params()->spdy_session_pool->FindAvailableSession(
  399. CreateSpdySessionKey(), /*enable_ip_based_pooling=*/false,
  400. /*is_websocket=*/false, net_log())) {
  401. next_state_ = STATE_SPDY_PROXY_CREATE_STREAM;
  402. return OK;
  403. }
  404. nested_connect_job_ = std::make_unique<SSLConnectJob>(
  405. priority(), socket_tag(), common_connect_job_params(),
  406. params_->ssl_params(), this, &net_log());
  407. }
  408. next_state_ = STATE_TRANSPORT_CONNECT_COMPLETE;
  409. return nested_connect_job_->Connect();
  410. }
  411. int HttpProxyConnectJob::DoTransportConnectComplete(int result) {
  412. resolve_error_info_ = nested_connect_job_->GetResolveErrorInfo();
  413. ProxyServer::Scheme scheme = GetProxyServerScheme();
  414. if (result != OK) {
  415. base::UmaHistogramMediumTimes(
  416. scheme == ProxyServer::SCHEME_HTTP
  417. ? "Net.HttpProxy.ConnectLatency.Insecure.Error"
  418. : "Net.HttpProxy.ConnectLatency.Secure.Error",
  419. base::TimeTicks::Now() - connect_start_time_);
  420. if (IsCertificateError(result)) {
  421. DCHECK_EQ(ProxyServer::SCHEME_HTTPS, scheme);
  422. // TODO(rch): allow the user to deal with proxy cert errors in the
  423. // same way as server cert errors.
  424. return ERR_PROXY_CERTIFICATE_INVALID;
  425. }
  426. if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
  427. DCHECK_EQ(ProxyServer::SCHEME_HTTPS, scheme);
  428. ssl_cert_request_info_ = nested_connect_job_->GetCertRequestInfo();
  429. DCHECK(ssl_cert_request_info_);
  430. ssl_cert_request_info_->is_proxy = true;
  431. return result;
  432. }
  433. return ERR_PROXY_CONNECTION_FAILED;
  434. }
  435. base::UmaHistogramMediumTimes(
  436. scheme == ProxyServer::SCHEME_HTTP
  437. ? "Net.HttpProxy.ConnectLatency.Insecure.Success"
  438. : "Net.HttpProxy.ConnectLatency.Secure.Success",
  439. base::TimeTicks::Now() - connect_start_time_);
  440. has_established_connection_ = true;
  441. if (!params_->tunnel()) {
  442. // If not tunneling, this is an HTTP URL being fetched directly over the
  443. // proxy. Return the underlying socket directly. The caller will handle the
  444. // ALPN protocol, etc., from here. Clear the DNS aliases to match the other
  445. // proxy codepaths.
  446. SetSocket(nested_connect_job_->PassSocket(),
  447. /*dns_aliases=*/std::set<std::string>());
  448. return result;
  449. }
  450. // Establish a tunnel over the proxy by making a CONNECT request. HTTP/1.1 and
  451. // HTTP/2 handle CONNECT differently.
  452. if (nested_connect_job_->socket()->GetNegotiatedProtocol() == kProtoHTTP2) {
  453. DCHECK_EQ(ProxyServer::SCHEME_HTTPS, scheme);
  454. next_state_ = STATE_SPDY_PROXY_CREATE_STREAM;
  455. } else {
  456. next_state_ = STATE_HTTP_PROXY_CONNECT;
  457. }
  458. return result;
  459. }
  460. int HttpProxyConnectJob::DoHttpProxyConnect() {
  461. DCHECK(params_->tunnel());
  462. next_state_ = STATE_HTTP_PROXY_CONNECT_COMPLETE;
  463. // Reset the timer to just the length of time allowed for HttpProxy handshake
  464. // so that a fast TCP connection plus a slow HttpProxy failure doesn't take
  465. // longer to timeout than it should.
  466. ResetTimer(kHttpProxyConnectJobTunnelTimeout);
  467. // Add a HttpProxy connection on top of the tcp socket.
  468. transport_socket_ = std::make_unique<HttpProxyClientSocket>(
  469. nested_connect_job_->PassSocket(), GetUserAgent(), params_->endpoint(),
  470. ProxyServer(GetProxyServerScheme(), GetDestination()),
  471. http_auth_controller_, common_connect_job_params()->proxy_delegate,
  472. params_->traffic_annotation());
  473. nested_connect_job_.reset();
  474. return transport_socket_->Connect(base::BindOnce(
  475. &HttpProxyConnectJob::OnIOComplete, base::Unretained(this)));
  476. }
  477. int HttpProxyConnectJob::DoHttpProxyConnectComplete(int result) {
  478. // Always inform caller of auth requests asynchronously.
  479. if (result == ERR_PROXY_AUTH_REQUESTED) {
  480. base::ThreadTaskRunnerHandle::Get()->PostTask(
  481. FROM_HERE, base::BindOnce(&HttpProxyConnectJob::OnAuthChallenge,
  482. weak_ptr_factory_.GetWeakPtr()));
  483. return ERR_IO_PENDING;
  484. }
  485. if (result == ERR_HTTP_1_1_REQUIRED)
  486. return ERR_PROXY_HTTP_1_1_REQUIRED;
  487. // In TLS 1.2 with False Start or TLS 1.3, alerts from the server rejecting
  488. // our client certificate are received at the first Read(), not Connect(), so
  489. // the error mapping in DoTransportConnectComplete does not apply. Repeat the
  490. // mapping here.
  491. if (result == ERR_BAD_SSL_CLIENT_AUTH_CERT)
  492. return ERR_PROXY_CONNECTION_FAILED;
  493. if (result == OK) {
  494. SetSocket(std::move(transport_socket_), /*dns_aliases=*/absl::nullopt);
  495. }
  496. return result;
  497. }
  498. int HttpProxyConnectJob::DoSpdyProxyCreateStream() {
  499. DCHECK(params_->tunnel());
  500. DCHECK(params_->ssl_params());
  501. // Reset the timer to just the length of time allowed for HttpProxy handshake
  502. // so that a fast TCP connection plus a slow HttpProxy failure doesn't take
  503. // longer to timeout than it should.
  504. ResetTimer(kHttpProxyConnectJobTunnelTimeout);
  505. SpdySessionKey key = CreateSpdySessionKey();
  506. base::WeakPtr<SpdySession> spdy_session =
  507. common_connect_job_params()->spdy_session_pool->FindAvailableSession(
  508. key, /* enable_ip_based_pooling = */ false,
  509. /* is_websocket = */ false, net_log());
  510. // It's possible that a session to the proxy has recently been created
  511. if (spdy_session) {
  512. nested_connect_job_.reset();
  513. } else {
  514. // Create a session direct to the proxy itself
  515. spdy_session = common_connect_job_params()
  516. ->spdy_session_pool->CreateAvailableSessionFromSocket(
  517. key, nested_connect_job_->PassSocket(),
  518. nested_connect_job_->connect_timing(), net_log());
  519. DCHECK(spdy_session);
  520. nested_connect_job_.reset();
  521. }
  522. next_state_ = STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE;
  523. spdy_stream_request_ = std::make_unique<SpdyStreamRequest>();
  524. return spdy_stream_request_->StartRequest(
  525. SPDY_BIDIRECTIONAL_STREAM, spdy_session,
  526. GURL("https://" + params_->endpoint().ToString()),
  527. false /* no early data */, kH2QuicTunnelPriority, socket_tag(),
  528. spdy_session->net_log(),
  529. base::BindOnce(&HttpProxyConnectJob::OnIOComplete,
  530. base::Unretained(this)),
  531. params_->traffic_annotation());
  532. }
  533. int HttpProxyConnectJob::DoSpdyProxyCreateStreamComplete(int result) {
  534. if (result < 0) {
  535. // See the comment in DoHttpProxyConnectComplete(). HTTP/2 proxies will
  536. // typically also fail here, as a result of SpdyProxyClientSocket::Connect()
  537. // below, but the error may surface out of SpdyStreamRequest if there were
  538. // enough requests in parallel that stream creation became asynchronous.
  539. if (result == ERR_BAD_SSL_CLIENT_AUTH_CERT)
  540. result = ERR_PROXY_CONNECTION_FAILED;
  541. spdy_stream_request_.reset();
  542. return result;
  543. }
  544. next_state_ = STATE_HTTP_PROXY_CONNECT_COMPLETE;
  545. base::WeakPtr<SpdyStream> stream = spdy_stream_request_->ReleaseStream();
  546. spdy_stream_request_.reset();
  547. DCHECK(stream.get());
  548. // |transport_socket_| will set itself as |stream|'s delegate.
  549. transport_socket_ = std::make_unique<SpdyProxyClientSocket>(
  550. stream, ProxyServer(GetProxyServerScheme(), GetDestination()),
  551. GetUserAgent(), params_->endpoint(), net_log(), http_auth_controller_,
  552. common_connect_job_params()->proxy_delegate);
  553. return transport_socket_->Connect(base::BindOnce(
  554. &HttpProxyConnectJob::OnIOComplete, base::Unretained(this)));
  555. }
  556. int HttpProxyConnectJob::DoQuicProxyCreateSession() {
  557. SSLSocketParams* ssl_params = params_->ssl_params().get();
  558. DCHECK(ssl_params);
  559. DCHECK(params_->tunnel());
  560. DCHECK(!common_connect_job_params()->quic_supported_versions->empty());
  561. // Reset the timer to just the length of time allowed for HttpProxy handshake
  562. // so that a fast QUIC connection plus a slow tunnel setup doesn't take longer
  563. // to timeout than it should.
  564. ResetTimer(kHttpProxyConnectJobTunnelTimeout);
  565. next_state_ = STATE_QUIC_PROXY_CREATE_STREAM;
  566. const HostPortPair& proxy_server = GetDestination();
  567. quic_stream_request_ = std::make_unique<QuicStreamRequest>(
  568. common_connect_job_params()->quic_stream_factory);
  569. // Use default QUIC version, which is the version listed supported version.
  570. quic::ParsedQuicVersion quic_version =
  571. common_connect_job_params()->quic_supported_versions->front();
  572. return quic_stream_request_->Request(
  573. // TODO(crbug.com/1206799) Pass the destination directly once it's
  574. // converted to contain scheme.
  575. url::SchemeHostPort(url::kHttpsScheme, proxy_server.host(),
  576. proxy_server.port()),
  577. quic_version, ssl_params->privacy_mode(), kH2QuicTunnelPriority,
  578. socket_tag(), params_->network_isolation_key(),
  579. ssl_params->GetDirectConnectionParams()->secure_dns_policy(),
  580. /*use_dns_aliases=*/false, /*require_dns_https_alpn=*/false,
  581. ssl_params->ssl_config().GetCertVerifyFlags(),
  582. GURL("https://" + proxy_server.ToString()), net_log(),
  583. &quic_net_error_details_,
  584. /*failed_on_default_network_callback=*/CompletionOnceCallback(),
  585. base::BindOnce(&HttpProxyConnectJob::OnIOComplete,
  586. base::Unretained(this)));
  587. }
  588. int HttpProxyConnectJob::DoQuicProxyCreateStream(int result) {
  589. if (result < 0) {
  590. quic_stream_request_.reset();
  591. return result;
  592. }
  593. next_state_ = STATE_QUIC_PROXY_CREATE_STREAM_COMPLETE;
  594. quic_session_ = quic_stream_request_->ReleaseSessionHandle();
  595. quic_stream_request_.reset();
  596. return quic_session_->RequestStream(
  597. false,
  598. base::BindOnce(&HttpProxyConnectJob::OnIOComplete,
  599. base::Unretained(this)),
  600. params_->traffic_annotation());
  601. }
  602. int HttpProxyConnectJob::DoQuicProxyCreateStreamComplete(int result) {
  603. if (result < 0)
  604. return result;
  605. next_state_ = STATE_HTTP_PROXY_CONNECT_COMPLETE;
  606. std::unique_ptr<QuicChromiumClientStream::Handle> quic_stream =
  607. quic_session_->ReleaseStream();
  608. spdy::SpdyPriority spdy_priority =
  609. ConvertRequestPriorityToQuicPriority(kH2QuicTunnelPriority);
  610. spdy::SpdyStreamPrecedence precedence(spdy_priority);
  611. quic_stream->SetPriority(precedence);
  612. transport_socket_ = std::make_unique<QuicProxyClientSocket>(
  613. std::move(quic_stream), std::move(quic_session_),
  614. ProxyServer(GetProxyServerScheme(), GetDestination()), GetUserAgent(),
  615. params_->endpoint(), net_log(), http_auth_controller_,
  616. common_connect_job_params()->proxy_delegate);
  617. return transport_socket_->Connect(base::BindOnce(
  618. &HttpProxyConnectJob::OnIOComplete, base::Unretained(this)));
  619. }
  620. int HttpProxyConnectJob::DoRestartWithAuth() {
  621. DCHECK(transport_socket_);
  622. // Start the timeout timer again.
  623. ResetTimer(kHttpProxyConnectJobTunnelTimeout);
  624. next_state_ = STATE_RESTART_WITH_AUTH_COMPLETE;
  625. return transport_socket_->RestartWithAuth(base::BindOnce(
  626. &HttpProxyConnectJob::OnIOComplete, base::Unretained(this)));
  627. }
  628. int HttpProxyConnectJob::DoRestartWithAuthComplete(int result) {
  629. DCHECK_NE(ERR_IO_PENDING, result);
  630. if (result == OK && !transport_socket_->IsConnected())
  631. result = ERR_UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH;
  632. // If the connection could not be reused to attempt to send proxy auth
  633. // credentials, try reconnecting. Do not reset the HttpAuthController in this
  634. // case; the server may, for instance, send "Proxy-Connection: close" and
  635. // expect that each leg of the authentication progress on separate
  636. // connections.
  637. bool reconnect = result == ERR_UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH;
  638. // If auth credentials were sent but the connection was closed, the server may
  639. // have timed out while the user was selecting credentials. Retry once.
  640. if (!has_restarted_ &&
  641. (result == ERR_CONNECTION_CLOSED || result == ERR_CONNECTION_RESET ||
  642. result == ERR_CONNECTION_ABORTED ||
  643. result == ERR_SOCKET_NOT_CONNECTED)) {
  644. reconnect = true;
  645. has_restarted_ = true;
  646. // Release any auth state bound to the connection. The new connection will
  647. // start the current scheme and identity from scratch.
  648. if (http_auth_controller_)
  649. http_auth_controller_->OnConnectionClosed();
  650. }
  651. if (reconnect) {
  652. // Attempt to create a new one.
  653. transport_socket_.reset();
  654. next_state_ = STATE_BEGIN_CONNECT;
  655. return OK;
  656. }
  657. // If not reconnecting, treat the result as the result of establishing a
  658. // tunnel through the proxy. This is important in the case another auth
  659. // challenge is seen.
  660. next_state_ = STATE_HTTP_PROXY_CONNECT_COMPLETE;
  661. return result;
  662. }
  663. void HttpProxyConnectJob::ChangePriorityInternal(RequestPriority priority) {
  664. // Do not set the priority on |spdy_stream_request_| or
  665. // |quic_stream_request_|, since those should always use
  666. // kH2QuicTunnelPriority.
  667. if (nested_connect_job_)
  668. nested_connect_job_->ChangePriority(priority);
  669. if (transport_socket_)
  670. transport_socket_->SetStreamPriority(priority);
  671. }
  672. void HttpProxyConnectJob::OnTimedOutInternal() {
  673. if (next_state_ == STATE_TRANSPORT_CONNECT_COMPLETE) {
  674. base::UmaHistogramMediumTimes(
  675. GetProxyServerScheme() == ProxyServer::SCHEME_HTTP
  676. ? "Net.HttpProxy.ConnectLatency.Insecure.TimedOut"
  677. : "Net.HttpProxy.ConnectLatency.Secure.TimedOut",
  678. base::TimeTicks::Now() - connect_start_time_);
  679. }
  680. }
  681. void HttpProxyConnectJob::OnAuthChallenge() {
  682. // Stop timer while potentially waiting for user input.
  683. ResetTimer(base::TimeDelta());
  684. NotifyDelegateOfProxyAuth(
  685. *transport_socket_->GetConnectResponseInfo(),
  686. transport_socket_->GetAuthController().get(),
  687. base::BindOnce(&HttpProxyConnectJob::RestartWithAuthCredentials,
  688. weak_ptr_factory_.GetWeakPtr()));
  689. }
  690. const HostPortPair& HttpProxyConnectJob::GetDestination() const {
  691. const TransportSocketParams* transport_params;
  692. if (params_->transport_params()) {
  693. transport_params = params_->transport_params().get();
  694. } else {
  695. transport_params = params_->ssl_params()->GetDirectConnectionParams().get();
  696. }
  697. // TODO(crbug.com/1206799): Handle proxy destination with scheme.
  698. DCHECK(
  699. absl::holds_alternative<HostPortPair>(transport_params->destination()));
  700. return absl::get<HostPortPair>(transport_params->destination());
  701. }
  702. std::string HttpProxyConnectJob::GetUserAgent() const {
  703. if (!http_user_agent_settings())
  704. return std::string();
  705. return http_user_agent_settings()->GetUserAgent();
  706. }
  707. SpdySessionKey HttpProxyConnectJob::CreateSpdySessionKey() const {
  708. return SpdySessionKey(
  709. GetDestination(), ProxyServer::Direct(), PRIVACY_MODE_DISABLED,
  710. SpdySessionKey::IsProxySession::kTrue, socket_tag(),
  711. params_->network_isolation_key(),
  712. params_->ssl_params()->GetDirectConnectionParams()->secure_dns_policy());
  713. }
  714. } // namespace net