PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/net/socket/connect_job.h

https://github.com/chromium/chromium
C Header | 334 lines | 186 code | 47 blank | 101 comment | 0 complexity | 506b65cc3b0a4ebbcde2c6f42a29f857 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, Apache-2.0, BSD-3-Clause
  1. // Copyright 2018 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. #ifndef NET_SOCKET_CONNECT_JOB_H_
  5. #define NET_SOCKET_CONNECT_JOB_H_
  6. #include <memory>
  7. #include <set>
  8. #include <string>
  9. #include "base/callback_forward.h"
  10. #include "base/callback_helpers.h"
  11. #include "base/memory/raw_ptr.h"
  12. #include "base/memory/ref_counted.h"
  13. #include "base/time/time.h"
  14. #include "base/timer/timer.h"
  15. #include "net/base/address_list.h"
  16. #include "net/base/load_states.h"
  17. #include "net/base/load_timing_info.h"
  18. #include "net/base/net_export.h"
  19. #include "net/base/request_priority.h"
  20. #include "net/dns/public/resolve_error_info.h"
  21. #include "net/log/net_log_with_source.h"
  22. #include "net/socket/connection_attempts.h"
  23. #include "net/socket/socket_tag.h"
  24. #include "net/socket/ssl_client_socket.h"
  25. #include "net/third_party/quiche/src/quiche/quic/core/quic_versions.h"
  26. #include "third_party/abseil-cpp/absl/types/optional.h"
  27. namespace net {
  28. class ClientSocketFactory;
  29. class HostPortPair;
  30. class HostResolver;
  31. struct HostResolverEndpointResult;
  32. class HttpAuthCache;
  33. class HttpAuthController;
  34. class HttpAuthHandlerFactory;
  35. class HttpResponseInfo;
  36. class HttpUserAgentSettings;
  37. class NetLog;
  38. class NetLogWithSource;
  39. class NetworkQualityEstimator;
  40. class ProxyDelegate;
  41. class QuicStreamFactory;
  42. class SocketPerformanceWatcherFactory;
  43. class SocketTag;
  44. class SpdySessionPool;
  45. class SSLCertRequestInfo;
  46. class StreamSocket;
  47. class WebSocketEndpointLockManager;
  48. // Immutable socket parameters intended for shared use by all ConnectJob types.
  49. // Excludes priority because it can be modified over the lifetime of a
  50. // ConnectJob. Excludes connection timeout and NetLogWithSource because
  51. // ConnectJobs that wrap other ConnectJobs typically have different values for
  52. // those.
  53. struct NET_EXPORT_PRIVATE CommonConnectJobParams {
  54. CommonConnectJobParams(
  55. ClientSocketFactory* client_socket_factory,
  56. HostResolver* host_resolver,
  57. HttpAuthCache* http_auth_cache,
  58. HttpAuthHandlerFactory* http_auth_handler_factory,
  59. SpdySessionPool* spdy_session_pool,
  60. const quic::ParsedQuicVersionVector* quic_supported_versions,
  61. QuicStreamFactory* quic_stream_factory,
  62. ProxyDelegate* proxy_delegate,
  63. const HttpUserAgentSettings* http_user_agent_settings,
  64. SSLClientContext* ssl_client_context,
  65. SocketPerformanceWatcherFactory* socket_performance_watcher_factory,
  66. NetworkQualityEstimator* network_quality_estimator,
  67. NetLog* net_log,
  68. WebSocketEndpointLockManager* websocket_endpoint_lock_manager);
  69. CommonConnectJobParams(const CommonConnectJobParams& other);
  70. ~CommonConnectJobParams();
  71. CommonConnectJobParams& operator=(const CommonConnectJobParams& other);
  72. raw_ptr<ClientSocketFactory> client_socket_factory;
  73. raw_ptr<HostResolver> host_resolver;
  74. raw_ptr<HttpAuthCache> http_auth_cache;
  75. raw_ptr<HttpAuthHandlerFactory> http_auth_handler_factory;
  76. raw_ptr<SpdySessionPool> spdy_session_pool;
  77. raw_ptr<const quic::ParsedQuicVersionVector> quic_supported_versions;
  78. raw_ptr<QuicStreamFactory> quic_stream_factory;
  79. raw_ptr<ProxyDelegate> proxy_delegate;
  80. raw_ptr<const HttpUserAgentSettings> http_user_agent_settings;
  81. raw_ptr<SSLClientContext> ssl_client_context;
  82. raw_ptr<SocketPerformanceWatcherFactory> socket_performance_watcher_factory;
  83. raw_ptr<NetworkQualityEstimator> network_quality_estimator;
  84. raw_ptr<NetLog> net_log;
  85. // This must only be non-null for WebSockets.
  86. raw_ptr<WebSocketEndpointLockManager> websocket_endpoint_lock_manager;
  87. };
  88. // When a host resolution completes, OnHostResolutionCallback() is invoked. If
  89. // it returns |kContinue|, the ConnectJob can continue immediately. If it
  90. // returns |kMayBeDeletedAsync|, the ConnectJob may be slated for asychronous
  91. // destruction, so should post a task before continuing, in case it will be
  92. // deleted. The purpose of kMayBeDeletedAsync is to avoid needlessly creating
  93. // and connecting a socket when it might not be needed.
  94. enum class OnHostResolutionCallbackResult {
  95. kContinue,
  96. kMayBeDeletedAsync,
  97. };
  98. // If non-null, invoked when host resolution completes. May not destroy the
  99. // ConnectJob synchronously, but may signal the ConnectJob may be destroyed
  100. // asynchronously. See OnHostResolutionCallbackResult above.
  101. //
  102. // |address_list| is the list of addresses the host being connected to was
  103. // resolved to, with the port fields populated to the port being connected to.
  104. using OnHostResolutionCallback =
  105. base::RepeatingCallback<OnHostResolutionCallbackResult(
  106. const HostPortPair& host_port_pair,
  107. const AddressList& address_list)>;
  108. // ConnectJob provides an abstract interface for "connecting" a socket.
  109. // The connection may involve host resolution, tcp connection, ssl connection,
  110. // etc.
  111. class NET_EXPORT_PRIVATE ConnectJob {
  112. public:
  113. // Alerts the delegate that the connection completed. |job| must be destroyed
  114. // by the delegate. A std::unique_ptr<> isn't used because the caller of this
  115. // function doesn't own |job|.
  116. class NET_EXPORT_PRIVATE Delegate {
  117. public:
  118. Delegate() {}
  119. Delegate(const Delegate&) = delete;
  120. Delegate& operator=(const Delegate&) = delete;
  121. virtual ~Delegate() {}
  122. // Alerts the delegate that the connection completed. |job| must be
  123. // destroyed by the delegate. A std::unique_ptr<> isn't used because the
  124. // caller of this function doesn't own |job|.
  125. virtual void OnConnectJobComplete(int result, ConnectJob* job) = 0;
  126. // Invoked when an HTTP proxy returns an HTTP auth challenge during tunnel
  127. // establishment. Always invoked asynchronously. The caller should use
  128. // |auth_controller| to set challenge response information and then invoke
  129. // |restart_with_auth_callback| to continue establishing a connection, or
  130. // delete the ConnectJob if it doesn't want to respond to the challenge.
  131. //
  132. // Will only be called once at a time. Neither OnConnectJobComplete() nor
  133. // OnNeedsProxyAuth() will be called synchronously when
  134. // |restart_with_auth_callback| is invoked. Will not be called after
  135. // OnConnectJobComplete() has been invoked.
  136. virtual void OnNeedsProxyAuth(const HttpResponseInfo& response,
  137. HttpAuthController* auth_controller,
  138. base::OnceClosure restart_with_auth_callback,
  139. ConnectJob* job) = 0;
  140. };
  141. // A |timeout_duration| of 0 corresponds to no timeout.
  142. //
  143. // If |net_log| is non-NULL, the ConnectJob will use it for logging.
  144. // Otherwise, a new one will be created of type |net_log_source_type|.
  145. //
  146. // |net_log_connect_event_type| is the NetLog event type logged on Connect()
  147. // and connect completion.
  148. ConnectJob(RequestPriority priority,
  149. const SocketTag& socket_tag,
  150. base::TimeDelta timeout_duration,
  151. const CommonConnectJobParams* common_connect_job_params,
  152. Delegate* delegate,
  153. const NetLogWithSource* net_log,
  154. NetLogSourceType net_log_source_type,
  155. NetLogEventType net_log_connect_event_type);
  156. ConnectJob(const ConnectJob&) = delete;
  157. ConnectJob& operator=(const ConnectJob&) = delete;
  158. virtual ~ConnectJob();
  159. // Accessors
  160. const NetLogWithSource& net_log() { return net_log_; }
  161. RequestPriority priority() const { return priority_; }
  162. // Releases ownership of the underlying socket to the caller. Returns the
  163. // released socket, or nullptr if there was a connection error.
  164. std::unique_ptr<StreamSocket> PassSocket();
  165. // Returns the connected socket, or nullptr if PassSocket() has already been
  166. // called. Used to query the socket state. May only be called after the
  167. // ConnectJob completes.
  168. StreamSocket* socket() { return socket_.get(); }
  169. void ChangePriority(RequestPriority priority);
  170. // Begins connecting the socket. Returns OK on success, ERR_IO_PENDING if it
  171. // cannot complete synchronously without blocking, or another net error code
  172. // on error. In asynchronous completion, the ConnectJob will notify
  173. // |delegate_| via OnConnectJobComplete. In both asynchronous and synchronous
  174. // completion, ReleaseSocket() can be called to acquire the connected socket
  175. // if it succeeded.
  176. //
  177. // On completion, the ConnectJob must be destroyed synchronously, since it
  178. // doesn't bother to stop its timer when complete.
  179. // TODO(mmenke): Can that be fixed?
  180. int Connect();
  181. // Returns the current LoadState of the ConnectJob. Each ConnectJob class must
  182. // start (optionally) with a LOAD_STATE_RESOLVING_HOST followed by
  183. // LOAD_STATE_CONNECTING, and never return to LOAD_STATE_CONNECTING. This
  184. // behavior is needed for backup ConnectJobs to function correctly.
  185. //
  186. // TODO(mmenke): Can something better be done here?
  187. virtual LoadState GetLoadState() const = 0;
  188. // Returns true if the ConnectJob has ever successfully established a TCP
  189. // connection. Used solely for deciding if a backup job is needed. Once it
  190. // starts returning true, must always return true when called in the future.
  191. // Not safe to call after NotifyComplete() is invoked.
  192. virtual bool HasEstablishedConnection() const = 0;
  193. // Returns a list of failed attempts to connect to the destination server.
  194. // Returns an empty list if connecting to a proxy.
  195. virtual ConnectionAttempts GetConnectionAttempts() const;
  196. // Returns error information about any host resolution attempt.
  197. virtual ResolveErrorInfo GetResolveErrorInfo() const = 0;
  198. // If the ConnectJob failed, returns true if the failure occurred after SSL
  199. // negotiation started. If the ConnectJob succeeded, the returned value is
  200. // undefined.
  201. virtual bool IsSSLError() const;
  202. // If the ConnectJob failed with ERR_SSL_CLIENT_AUTH_CERT_NEEDED, returns the
  203. // SSLCertRequestInfo received. Otherwise, returns nullptr.
  204. virtual scoped_refptr<SSLCertRequestInfo> GetCertRequestInfo();
  205. // Returns the `HostResolverEndpointResult` structure corresponding to the
  206. // chosen route. Should only be called on a successful connect. If the
  207. // `ConnectJob` does not make DNS queries, or does not use the SVCB/HTTPS
  208. // record, it may return `absl::nullopt`, to avoid callers getting confused by
  209. // an empty `IPEndPoint` list.
  210. virtual absl::optional<HostResolverEndpointResult>
  211. GetHostResolverEndpointResult() const;
  212. const LoadTimingInfo::ConnectTiming& connect_timing() const {
  213. return connect_timing_;
  214. }
  215. // Sets |done_closure_| which will be called when |this| is deleted.
  216. void set_done_closure(base::OnceClosure done_closure);
  217. const NetLogWithSource& net_log() const { return net_log_; }
  218. protected:
  219. const SocketTag& socket_tag() const { return socket_tag_; }
  220. ClientSocketFactory* client_socket_factory() {
  221. return common_connect_job_params_->client_socket_factory;
  222. }
  223. HostResolver* host_resolver() {
  224. return common_connect_job_params_->host_resolver;
  225. }
  226. const HttpUserAgentSettings* http_user_agent_settings() const {
  227. return common_connect_job_params_->http_user_agent_settings;
  228. }
  229. SSLClientContext* ssl_client_context() {
  230. return common_connect_job_params_->ssl_client_context;
  231. }
  232. SocketPerformanceWatcherFactory* socket_performance_watcher_factory() {
  233. return common_connect_job_params_->socket_performance_watcher_factory;
  234. }
  235. NetworkQualityEstimator* network_quality_estimator() {
  236. return common_connect_job_params_->network_quality_estimator;
  237. }
  238. WebSocketEndpointLockManager* websocket_endpoint_lock_manager() {
  239. return common_connect_job_params_->websocket_endpoint_lock_manager;
  240. }
  241. const CommonConnectJobParams* common_connect_job_params() {
  242. return common_connect_job_params_;
  243. }
  244. void SetSocket(std::unique_ptr<StreamSocket> socket,
  245. absl::optional<std::set<std::string>> dns_aliases);
  246. void NotifyDelegateOfCompletion(int rv);
  247. void NotifyDelegateOfProxyAuth(const HttpResponseInfo& response,
  248. HttpAuthController* auth_controller,
  249. base::OnceClosure restart_with_auth_callback);
  250. // If |remaining_time| is base::TimeDelta(), stops the timeout timer, if it's
  251. // running. Otherwise, Starts / restarts the timeout timer to trigger in the
  252. // specified amount of time.
  253. void ResetTimer(base::TimeDelta remaining_time);
  254. // Returns whether or not the timeout timer is running. Only intended for use
  255. // by DCHECKs.
  256. bool TimerIsRunning() const;
  257. // Connection establishment timing information.
  258. // TODO(mmenke): This should be private.
  259. LoadTimingInfo::ConnectTiming connect_timing_;
  260. private:
  261. virtual int ConnectInternal() = 0;
  262. virtual void ChangePriorityInternal(RequestPriority priority) = 0;
  263. void LogConnectStart();
  264. void LogConnectCompletion(int net_error);
  265. // Alerts the delegate that the ConnectJob has timed out.
  266. void OnTimeout();
  267. // Invoked to notify subclasses that the has request timed out.
  268. virtual void OnTimedOutInternal();
  269. const base::TimeDelta timeout_duration_;
  270. RequestPriority priority_;
  271. const SocketTag socket_tag_;
  272. raw_ptr<const CommonConnectJobParams> common_connect_job_params_;
  273. // Timer to abort jobs that take too long.
  274. base::OneShotTimer timer_;
  275. raw_ptr<Delegate> delegate_;
  276. std::unique_ptr<StreamSocket> socket_;
  277. // Indicates if this is the topmost ConnectJob. The topmost ConnectJob logs an
  278. // extra begin and end event, to allow callers to log extra data before the
  279. // ConnectJob has started / after it has completed.
  280. const bool top_level_job_;
  281. NetLogWithSource net_log_;
  282. // This is called when |this| is deleted.
  283. base::ScopedClosureRunner done_closure_;
  284. const NetLogEventType net_log_connect_event_type_;
  285. };
  286. } // namespace net
  287. #endif // NET_SOCKET_CONNECT_JOB_H_