1 // Copyright 2012 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_ 6 #define NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <list> 12 #include <map> 13 #include <memory> 14 #include <set> 15 #include <string> 16 #include <utility> 17 #include <vector> 18 19 #include "base/memory/raw_ptr.h" 20 #include "base/memory/scoped_refptr.h" 21 #include "base/memory/weak_ptr.h" 22 #include "base/time/time.h" 23 #include "base/timer/timer.h" 24 #include "net/base/address_list.h" 25 #include "net/base/completion_once_callback.h" 26 #include "net/base/load_states.h" 27 #include "net/base/load_timing_info.h" 28 #include "net/base/net_errors.h" 29 #include "net/base/net_export.h" 30 #include "net/base/network_change_notifier.h" 31 #include "net/base/priority_queue.h" 32 #include "net/base/proxy_server.h" 33 #include "net/base/request_priority.h" 34 #include "net/log/net_log_with_source.h" 35 #include "net/socket/client_socket_handle.h" 36 #include "net/socket/client_socket_pool.h" 37 #include "net/socket/connect_job.h" 38 #include "net/socket/connection_attempts.h" 39 #include "net/socket/socket_tag.h" 40 #include "net/socket/ssl_client_socket.h" 41 #include "net/socket/stream_socket.h" 42 #include "third_party/abseil-cpp/absl/types/optional.h" 43 44 namespace net { 45 46 struct CommonConnectJobParams; 47 class ConnectJobFactory; 48 struct NetLogSource; 49 struct NetworkTrafficAnnotationTag; 50 51 // TransportClientSocketPool establishes network connections through using 52 // ConnectJobs, and maintains a list of idle persistent sockets available for 53 // reuse. It restricts the number of sockets open at a time, both globally, and 54 // for each unique GroupId, which roughly corresponds to origin and privacy mode 55 // setting. TransportClientSocketPool is designed to work with HTTP reuse 56 // semantics, handling each request serially, before reusable sockets are 57 // returned to the socket pool. 58 // 59 // In order to manage connection limits on a per-Proxy basis, separate 60 // TransportClientSocketPools are created for each proxy, and another for 61 // connections that have no proxy. 62 // TransportClientSocketPool is an internal class that implements almost all 63 // the functionality from ClientSocketPool. 64 class NET_EXPORT_PRIVATE TransportClientSocketPool 65 : public ClientSocketPool, 66 public NetworkChangeNotifier::IPAddressObserver, 67 public SSLClientContext::Observer { 68 public: 69 // Reasons for closing sockets. Exposed here for testing. 70 static const char kCertDatabaseChanged[]; 71 static const char kCertVerifierChanged[]; 72 static const char kClosedConnectionReturnedToPool[]; 73 static const char kDataReceivedUnexpectedly[]; 74 static const char kIdleTimeLimitExpired[]; 75 static const char kNetworkChanged[]; 76 static const char kRemoteSideClosedConnection[]; 77 static const char kSocketGenerationOutOfDate[]; 78 static const char kSocketPoolDestroyed[]; 79 static const char kSslConfigChanged[]; 80 81 using Flags = uint32_t; 82 83 // Used to specify specific behavior for the ClientSocketPool. 84 enum Flag { 85 NORMAL = 0, // Normal behavior. 86 NO_IDLE_SOCKETS = 0x1, // Do not return an idle socket. Create a new one. 87 }; 88 89 class NET_EXPORT_PRIVATE Request { 90 public: 91 // If |proxy_auth_callback| is null, proxy auth challenges will 92 // result in an error. 93 Request( 94 ClientSocketHandle* handle, 95 CompletionOnceCallback callback, 96 const ProxyAuthCallback& proxy_auth_callback, 97 RequestPriority priority, 98 const SocketTag& socket_tag, 99 RespectLimits respect_limits, 100 Flags flags, 101 scoped_refptr<SocketParams> socket_params, 102 const absl::optional<NetworkTrafficAnnotationTag>& proxy_annotation_tag, 103 const NetLogWithSource& net_log); 104 105 Request(const Request&) = delete; 106 Request& operator=(const Request&) = delete; 107 108 ~Request(); 109 handle()110 ClientSocketHandle* handle() const { return handle_; } release_callback()111 CompletionOnceCallback release_callback() { return std::move(callback_); } proxy_auth_callback()112 const ProxyAuthCallback& proxy_auth_callback() const { 113 return proxy_auth_callback_; 114 } priority()115 RequestPriority priority() const { return priority_; } set_priority(RequestPriority priority)116 void set_priority(RequestPriority priority) { priority_ = priority; } respect_limits()117 RespectLimits respect_limits() const { return respect_limits_; } flags()118 Flags flags() const { return flags_; } socket_params()119 SocketParams* socket_params() const { return socket_params_.get(); } proxy_annotation_tag()120 const absl::optional<NetworkTrafficAnnotationTag>& proxy_annotation_tag() 121 const { 122 return proxy_annotation_tag_; 123 } net_log()124 const NetLogWithSource& net_log() const { return net_log_; } socket_tag()125 const SocketTag& socket_tag() const { return socket_tag_; } job()126 ConnectJob* job() const { return job_; } 127 128 // Associates a ConnectJob with the request. Must be called on a request 129 // that does not already have a job. 130 void AssignJob(ConnectJob* job); 131 132 // Unassigns the request's |job_| and returns it. Must be called on a 133 // request with a job. 134 ConnectJob* ReleaseJob(); 135 136 private: 137 const raw_ptr<ClientSocketHandle> handle_; 138 CompletionOnceCallback callback_; 139 const ProxyAuthCallback proxy_auth_callback_; 140 RequestPriority priority_; 141 const RespectLimits respect_limits_; 142 const Flags flags_; 143 const scoped_refptr<SocketParams> socket_params_; 144 const absl::optional<NetworkTrafficAnnotationTag> proxy_annotation_tag_; 145 const NetLogWithSource net_log_; 146 const SocketTag socket_tag_; 147 raw_ptr<ConnectJob> job_ = nullptr; 148 }; 149 150 TransportClientSocketPool( 151 int max_sockets, 152 int max_sockets_per_group, 153 base::TimeDelta unused_idle_socket_timeout, 154 const ProxyServer& proxy_server, 155 bool is_for_websockets, 156 const CommonConnectJobParams* common_connect_job_params, 157 bool cleanup_on_ip_address_change = true); 158 159 TransportClientSocketPool(const TransportClientSocketPool&) = delete; 160 TransportClientSocketPool& operator=(const TransportClientSocketPool&) = 161 delete; 162 163 // Creates a socket pool with an alternative ConnectJobFactory, for use in 164 // testing. 165 // 166 // |connect_backup_jobs_enabled| can be set to false to disable backup connect 167 // jobs (Which are normally enabled). 168 static std::unique_ptr<TransportClientSocketPool> CreateForTesting( 169 int max_sockets, 170 int max_sockets_per_group, 171 base::TimeDelta unused_idle_socket_timeout, 172 base::TimeDelta used_idle_socket_timeout, 173 const ProxyServer& proxy_server, 174 bool is_for_websockets, 175 const CommonConnectJobParams* common_connect_job_params, 176 std::unique_ptr<ConnectJobFactory> connect_job_factory, 177 SSLClientContext* ssl_client_context, 178 bool connect_backup_jobs_enabled); 179 180 ~TransportClientSocketPool() override; 181 182 // See LowerLayeredPool::IsStalled for documentation on this function. 183 bool IsStalled() const override; 184 185 // See LowerLayeredPool for documentation on these functions. It is expected 186 // in the destructor that no higher layer pools remain. 187 void AddHigherLayeredPool(HigherLayeredPool* higher_pool) override; 188 void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool) override; 189 190 // ClientSocketPool implementation: 191 int RequestSocket( 192 const GroupId& group_id, 193 scoped_refptr<SocketParams> params, 194 const absl::optional<NetworkTrafficAnnotationTag>& proxy_annotation_tag, 195 RequestPriority priority, 196 const SocketTag& socket_tag, 197 RespectLimits respect_limits, 198 ClientSocketHandle* handle, 199 CompletionOnceCallback callback, 200 const ProxyAuthCallback& proxy_auth_callback, 201 const NetLogWithSource& net_log) override; 202 int RequestSockets( 203 const GroupId& group_id, 204 scoped_refptr<SocketParams> params, 205 const absl::optional<NetworkTrafficAnnotationTag>& proxy_annotation_tag, 206 int num_sockets, 207 CompletionOnceCallback callback, 208 const NetLogWithSource& net_log) override; 209 void SetPriority(const GroupId& group_id, 210 ClientSocketHandle* handle, 211 RequestPriority priority) override; 212 void CancelRequest(const GroupId& group_id, 213 ClientSocketHandle* handle, 214 bool cancel_connect_job) override; 215 void ReleaseSocket(const GroupId& group_id, 216 std::unique_ptr<StreamSocket> socket, 217 int64_t group_generation) override; 218 void FlushWithError(int error, const char* net_log_reason_utf8) override; 219 void CloseIdleSockets(const char* net_log_reason_utf8) override; 220 void CloseIdleSocketsInGroup(const GroupId& group_id, 221 const char* net_log_reason_utf8) override; 222 int IdleSocketCount() const override; 223 size_t IdleSocketCountInGroup(const GroupId& group_id) const override; 224 LoadState GetLoadState(const GroupId& group_id, 225 const ClientSocketHandle* handle) const override; 226 base::Value GetInfoAsValue(const std::string& name, 227 const std::string& type) const override; 228 bool HasActiveSocket(const GroupId& group_id) const override; 229 RequestInGroupWithHandleHasJobForTesting(const GroupId & group_id,const ClientSocketHandle * handle)230 bool RequestInGroupWithHandleHasJobForTesting( 231 const GroupId& group_id, 232 const ClientSocketHandle* handle) const { 233 return group_map_.find(group_id)->second->RequestWithHandleHasJobForTesting( 234 handle); 235 } 236 NumNeverAssignedConnectJobsInGroupForTesting(const GroupId & group_id)237 size_t NumNeverAssignedConnectJobsInGroupForTesting( 238 const GroupId& group_id) const { 239 return NumNeverAssignedConnectJobsInGroup(group_id); 240 } 241 NumUnassignedConnectJobsInGroupForTesting(const GroupId & group_id)242 size_t NumUnassignedConnectJobsInGroupForTesting( 243 const GroupId& group_id) const { 244 return NumUnassignedConnectJobsInGroup(group_id); 245 } 246 NumConnectJobsInGroupForTesting(const GroupId & group_id)247 size_t NumConnectJobsInGroupForTesting(const GroupId& group_id) const { 248 return NumConnectJobsInGroup(group_id); 249 } 250 NumActiveSocketsInGroupForTesting(const GroupId & group_id)251 int NumActiveSocketsInGroupForTesting(const GroupId& group_id) const { 252 return NumActiveSocketsInGroup(group_id); 253 } 254 HasGroupForTesting(const GroupId & group_id)255 bool HasGroupForTesting(const GroupId& group_id) const { 256 return HasGroup(group_id); 257 } 258 259 static bool connect_backup_jobs_enabled(); 260 static bool set_connect_backup_jobs_enabled(bool enabled); 261 262 // NetworkChangeNotifier::IPAddressObserver methods: 263 void OnIPAddressChanged() override; 264 265 // SSLClientContext::Observer methods. 266 void OnSSLConfigChanged( 267 SSLClientContext::SSLConfigChangeType change_type) override; 268 void OnSSLConfigForServerChanged(const HostPortPair& server) override; 269 270 private: 271 // Entry for a persistent socket which became idle at time |start_time|. 272 struct IdleSocket; 273 274 using RequestQueue = PriorityQueue<std::unique_ptr<Request>>; 275 276 // A Group is allocated per GroupId when there are idle sockets, unbound 277 // request, or bound requests. Otherwise, the Group object is removed from the 278 // map. 279 // 280 // A request is "bound" to a ConnectJob when an unbound ConnectJob encounters 281 // a proxy HTTP auth challenge, and the auth challenge is presented to that 282 // request. Once a request and ConnectJob are bound together: 283 // * All auth challenges the ConnectJob sees will be sent to that request. 284 // * Cancelling the request will cancel the ConnectJob. 285 // * The final result of the ConnectJob, and any returned socket, will only be 286 // sent to that bound request, though if the returned socket is returned to 287 // the socket pool, it can then be used to service any request. 288 // 289 // "assigned" jobs are unbound ConnectJobs that have a corresponding Request. 290 // If there are 5 Jobs and 10 Requests, the 5 highest priority requests are 291 // each assigned a Job. If there are 10 Jobs and 5 Requests, the first 5 Jobs 292 // are each assigned to a request. Assignment is determined by order in their 293 // corresponding arrays. The assignment concept is used to deal with 294 // reprioritizing Jobs, and computing a Request's LoadState. 295 // 296 // |active_socket_count| tracks the number of sockets held by clients. 297 // SanityCheck() will always be true, except during the invocation of a 298 // method. So all public methods expect the Group to pass SanityCheck() when 299 // invoked. 300 class NET_EXPORT_PRIVATE Group : public ConnectJob::Delegate { 301 public: 302 using JobList = std::list<std::unique_ptr<ConnectJob>>; 303 304 struct BoundRequest { 305 BoundRequest(); 306 BoundRequest(std::unique_ptr<ConnectJob> connect_job, 307 std::unique_ptr<Request> request, 308 int64_t generation); 309 BoundRequest(BoundRequest&& other); 310 BoundRequest& operator=(BoundRequest&& other); 311 ~BoundRequest(); 312 313 std::unique_ptr<ConnectJob> connect_job; 314 std::unique_ptr<Request> request; 315 316 // Generation of |connect_job|. If it doesn't match the current 317 // generation, ConnectJob will be destroyed, and a new one created on 318 // completion. 319 int64_t generation; 320 321 // It's not safe to fail a request in a |CancelAllRequestsWithError| call 322 // while it's waiting on user input, as the request may have raw pointers 323 // to objects owned by |connect_job| that it could racily write to after 324 // |connect_job| is destroyed. Instead, just track an error in that case, 325 // and fail the request once the ConnectJob completes. 326 int pending_error; 327 }; 328 329 Group(const GroupId& group_id, 330 TransportClientSocketPool* client_socket_pool); 331 ~Group() override; 332 333 // ConnectJob::Delegate methods: 334 void OnConnectJobComplete(int result, ConnectJob* job) override; 335 void OnNeedsProxyAuth(const HttpResponseInfo& response, 336 HttpAuthController* auth_controller, 337 base::OnceClosure restart_with_auth_callback, 338 ConnectJob* job) override; 339 IsEmpty()340 bool IsEmpty() const { 341 return active_socket_count_ == 0 && idle_sockets_.empty() && 342 jobs_.empty() && unbound_requests_.empty() && 343 bound_requests_.empty(); 344 } 345 HasAvailableSocketSlot(int max_sockets_per_group)346 bool HasAvailableSocketSlot(int max_sockets_per_group) const { 347 return NumActiveSocketSlots() < max_sockets_per_group; 348 } 349 NumActiveSocketSlots()350 int NumActiveSocketSlots() const { 351 return active_socket_count_ + static_cast<int>(jobs_.size()) + 352 static_cast<int>(idle_sockets_.size()) + 353 static_cast<int>(bound_requests_.size()); 354 } 355 356 // Returns true if the group could make use of an additional socket slot, if 357 // it were given one. CanUseAdditionalSocketSlot(int max_sockets_per_group)358 bool CanUseAdditionalSocketSlot(int max_sockets_per_group) const { 359 return HasAvailableSocketSlot(max_sockets_per_group) && 360 unbound_requests_.size() > jobs_.size(); 361 } 362 363 // Returns the priority of the top of the unbound request queue 364 // (which may be less than the maximum priority over the entire 365 // queue, due to how we prioritize requests with |respect_limits| 366 // DISABLED over others). TopPendingPriority()367 RequestPriority TopPendingPriority() const { 368 // NOTE: FirstMax().value()->priority() is not the same as 369 // FirstMax().priority()! 370 return unbound_requests_.FirstMax().value()->priority(); 371 } 372 373 // Set a timer to create a backup job if it takes too long to 374 // create one and if a timer isn't already running. 375 void StartBackupJobTimer(const GroupId& group_id); 376 377 bool BackupJobTimerIsRunning() const; 378 379 // If there's a ConnectJob that's never been assigned to Request, 380 // decrements |never_assigned_job_count_| and returns true. 381 // Otherwise, returns false. 382 bool TryToUseNeverAssignedConnectJob(); 383 384 void AddJob(std::unique_ptr<ConnectJob> job, bool is_preconnect); 385 // Remove |job| from this group, which must already own |job|. Returns the 386 // removed ConnectJob. 387 std::unique_ptr<ConnectJob> RemoveUnboundJob(ConnectJob* job); 388 void RemoveAllUnboundJobs(); 389 has_unbound_requests()390 bool has_unbound_requests() const { return !unbound_requests_.empty(); } 391 unbound_request_count()392 size_t unbound_request_count() const { return unbound_requests_.size(); } 393 394 size_t ConnectJobCount() const; 395 396 // Returns the connect job correspding to |handle|. In particular, if 397 // |handle| is bound to a ConnectJob, returns that job. If |handle| is 398 // "assigned" a ConnectJob, return that job. Otherwise, returns nullptr. 399 ConnectJob* GetConnectJobForHandle(const ClientSocketHandle* handle) const; 400 401 // Inserts the request into the queue based on priority 402 // order. Older requests are prioritized over requests of equal 403 // priority. 404 void InsertUnboundRequest(std::unique_ptr<Request> request); 405 406 // Gets (but does not remove) the next unbound request. Returns 407 // NULL if there are no unbound requests. 408 const Request* GetNextUnboundRequest() const; 409 410 // Gets and removes the next unbound request. Returns NULL if 411 // there are no unbound requests. 412 std::unique_ptr<Request> PopNextUnboundRequest(); 413 414 // Finds the unbound request for |handle| and removes it. Returns 415 // the removed unbound request, or NULL if there was none. 416 std::unique_ptr<Request> FindAndRemoveUnboundRequest( 417 ClientSocketHandle* handle); 418 419 // Sets a pending error for all bound requests. Bound requests may be in the 420 // middle of a callback, so can't be failed at arbitrary points in time. 421 void SetPendingErrorForAllBoundRequests(int pending_error); 422 423 // Attempts to bind the highest priority unbound request to |connect_job|, 424 // and returns the bound request. If the request has previously been bound 425 // to |connect_job|, returns the previously bound request. If there are no 426 // requests, or the highest priority request doesn't have a proxy auth 427 // callback, returns nullptr. 428 const Request* BindRequestToConnectJob(ConnectJob* connect_job); 429 430 // Finds the request, if any, bound to |connect_job|, and returns the 431 // BoundRequest or absl::nullopt if there was none. 432 absl::optional<BoundRequest> FindAndRemoveBoundRequestForConnectJob( 433 ConnectJob* connect_job); 434 435 // Finds the bound request, if any, corresponding to |client_socket_handle| 436 // and returns it. Destroys the ConnectJob bound to the request, if there 437 // was one. 438 std::unique_ptr<Request> FindAndRemoveBoundRequest( 439 ClientSocketHandle* client_socket_handle); 440 441 // Change the priority of the request named by |*handle|. |*handle| 442 // must refer to a request currently present in the group. If |priority| 443 // is the same as the current priority of the request, this is a no-op. 444 void SetPriority(ClientSocketHandle* handle, RequestPriority priority); 445 IncrementActiveSocketCount()446 void IncrementActiveSocketCount() { active_socket_count_++; } DecrementActiveSocketCount()447 void DecrementActiveSocketCount() { active_socket_count_--; } 448 IncrementGeneration()449 void IncrementGeneration() { generation_++; } 450 451 // Whether the request in |unbound_requests_| with a given handle has a job. 452 bool RequestWithHandleHasJobForTesting( 453 const ClientSocketHandle* handle) const; 454 group_id()455 const GroupId& group_id() { return group_id_; } unassigned_job_count()456 size_t unassigned_job_count() const { return unassigned_jobs_.size(); } jobs()457 const JobList& jobs() const { return jobs_; } idle_sockets()458 const std::list<IdleSocket>& idle_sockets() const { return idle_sockets_; } active_socket_count()459 int active_socket_count() const { return active_socket_count_; } mutable_idle_sockets()460 std::list<IdleSocket>* mutable_idle_sockets() { return &idle_sockets_; } never_assigned_job_count()461 size_t never_assigned_job_count() const { 462 return never_assigned_job_count_; 463 } generation()464 int64_t generation() const { return generation_; } 465 466 private: 467 // Returns the iterator's unbound request after removing it from 468 // the queue. Expects the Group to pass SanityCheck() when called. 469 std::unique_ptr<Request> RemoveUnboundRequest( 470 const RequestQueue::Pointer& pointer); 471 472 // Finds the Request which is associated with the given ConnectJob. 473 // Returns nullptr if none is found. Expects the Group to pass SanityCheck() 474 // when called. 475 RequestQueue::Pointer FindUnboundRequestWithJob( 476 const ConnectJob* job) const; 477 478 // Finds the Request in |unbound_requests_| which is the first request 479 // without a job. Returns a null pointer if all requests have jobs. Does not 480 // expect the Group to pass SanityCheck() when called, but does expect all 481 // jobs to either be assigned to a request or in |unassigned_jobs_|. Expects 482 // that no requests with jobs come after any requests without a job. 483 RequestQueue::Pointer GetFirstRequestWithoutJob() const; 484 485 // Tries to assign an unassigned |job| to a request. If no requests need a 486 // job, |job| is added to |unassigned_jobs_|. 487 // When called, does not expect the Group to pass SanityCheck(), but does 488 // expect it to have passed SanityCheck() before the given ConnectJob was 489 // either created or had the request it was assigned to removed. 490 void TryToAssignUnassignedJob(ConnectJob* job); 491 492 // Tries to assign a job to the given request. If any unassigned jobs are 493 // available, the first unassigned job is assigned to the request. 494 // Otherwise, if the request is ahead of the last request with a job, the 495 // job is stolen from the last request with a job. 496 // When called, does not expect the Group to pass SanityCheck(), but does 497 // expect that: 498 // - the request associated with |request_pointer| must not have 499 // an assigned ConnectJob, 500 // - the first min( jobs_.size(), unbound_requests_.size() - 1 ) Requests 501 // other than the given request must have ConnectJobs, i.e. the group 502 // must have passed SanityCheck() before the passed in Request was either 503 // added or had its job unassigned. 504 void TryToAssignJobToRequest(RequestQueue::Pointer request_pointer); 505 506 // Transfers the associated ConnectJob from one Request to another. Expects 507 // the source request to have a job, and the destination request to not have 508 // a job. Does not expect the Group to pass SanityCheck() when called. 509 void TransferJobBetweenRequests(Request* source, Request* dest); 510 511 // Called when the backup socket timer fires. 512 void OnBackupJobTimerFired(const GroupId& group_id); 513 514 // Checks that: 515 // - |unassigned_jobs_| is empty iff there are at least as many requests 516 // as jobs. 517 // - Exactly the first |jobs_.size() - unassigned_jobs_.size()| requests 518 // have ConnectJobs. 519 // - No requests are assigned a ConnectJob in |unassigned_jobs_|. 520 // - No requests are assigned a ConnectJob not in |jobs_|. 521 // - No two requests are assigned the same ConnectJob. 522 // - All entries in |unassigned_jobs_| are also in |jobs_|. 523 // - There are no duplicate entries in |unassigned_jobs_|. 524 void SanityCheck() const; 525 526 const GroupId group_id_; 527 const raw_ptr<TransportClientSocketPool> client_socket_pool_; 528 529 // Total number of ConnectJobs that have never been assigned to a Request. 530 // Since jobs use late binding to requests, which ConnectJobs have or have 531 // not been assigned to a request are not tracked. This is incremented on 532 // preconnect and decremented when a preconnect is assigned, or when there 533 // are fewer than |never_assigned_job_count_| ConnectJobs. Not incremented 534 // when a request is cancelled. 535 size_t never_assigned_job_count_ = 0; 536 537 std::list<IdleSocket> idle_sockets_; 538 JobList jobs_; // For bookkeeping purposes, there is a copy of the raw 539 // pointer of each element of |jobs_| stored either in 540 // |unassigned_jobs_|, or as the associated |job_| of an 541 // element of |unbound_requests_|. 542 std::list<ConnectJob*> unassigned_jobs_; 543 RequestQueue unbound_requests_; 544 int active_socket_count_ = 0; // number of active sockets used by clients 545 // A timer for when to start the backup job. 546 base::OneShotTimer backup_job_timer_; 547 548 // List of Requests bound to ConnectJobs currently undergoing proxy auth. 549 // The Requests and ConnectJobs in this list do not appear in 550 // |unbound_requests_| or |jobs_|. 551 std::vector<BoundRequest> bound_requests_; 552 553 // An id for the group. It gets incremented every time we FlushWithError() 554 // the socket pool, or refresh the group. This is so that when sockets get 555 // released back to the group, we can make sure that they are discarded 556 // rather than reused. Destroying a group will reset the generation number, 557 // but as that only happens once there are no outstanding sockets or 558 // requests associated with the group, that's harmless. 559 int64_t generation_ = 0; 560 }; 561 562 using GroupMap = std::map<GroupId, Group*>; 563 564 struct CallbackResultPair { 565 CallbackResultPair(); 566 CallbackResultPair(CompletionOnceCallback callback_in, int result_in); 567 CallbackResultPair(CallbackResultPair&& other); 568 CallbackResultPair& operator=(CallbackResultPair&& other); 569 ~CallbackResultPair(); 570 571 CompletionOnceCallback callback; 572 int result; 573 }; 574 575 using PendingCallbackMap = 576 std::map<const ClientSocketHandle*, CallbackResultPair>; 577 578 TransportClientSocketPool( 579 int max_sockets, 580 int max_sockets_per_group, 581 base::TimeDelta unused_idle_socket_timeout, 582 base::TimeDelta used_idle_socket_timeout, 583 const ProxyServer& proxy_server, 584 bool is_for_websockets, 585 const CommonConnectJobParams* common_connect_job_params, 586 bool cleanup_on_ip_address_change, 587 std::unique_ptr<ConnectJobFactory> connect_job_factory, 588 SSLClientContext* ssl_client_context, 589 bool connect_backup_jobs_enabled); 590 ConnectRetryInterval()591 base::TimeDelta ConnectRetryInterval() const { 592 // TODO(mbelshe): Make this tuned dynamically based on measured RTT. 593 // For now, just use the max retry interval. 594 return base::Milliseconds(kMaxConnectRetryIntervalMs); 595 } 596 597 // TODO(mmenke): de-inline these. NumNeverAssignedConnectJobsInGroup(const GroupId & group_id)598 size_t NumNeverAssignedConnectJobsInGroup(const GroupId& group_id) const { 599 return group_map_.find(group_id)->second->never_assigned_job_count(); 600 } 601 NumUnassignedConnectJobsInGroup(const GroupId & group_id)602 size_t NumUnassignedConnectJobsInGroup(const GroupId& group_id) const { 603 return group_map_.find(group_id)->second->unassigned_job_count(); 604 } 605 NumConnectJobsInGroup(const GroupId & group_id)606 size_t NumConnectJobsInGroup(const GroupId& group_id) const { 607 return group_map_.find(group_id)->second->ConnectJobCount(); 608 } 609 NumActiveSocketsInGroup(const GroupId & group_id)610 int NumActiveSocketsInGroup(const GroupId& group_id) const { 611 return group_map_.find(group_id)->second->active_socket_count(); 612 } 613 614 bool HasGroup(const GroupId& group_id) const; 615 616 // Closes all idle sockets if |force| is true. Else, only closes idle 617 // sockets that timed out or can't be reused. Made public for testing. 618 // |reason| must be non-empty when |force| is true. 619 void CleanupIdleSockets(bool force, const char* net_log_reason_utf8); 620 621 // Closes one idle socket. Picks the first one encountered. 622 // TODO(willchan): Consider a better algorithm for doing this. Perhaps we 623 // should keep an ordered list of idle sockets, and close them in order. 624 // Requires maintaining more state. It's not clear if it's worth it since 625 // I'm not sure if we hit this situation often. 626 bool CloseOneIdleSocket(); 627 628 // Checks higher layered pools to see if they can close an idle connection. 629 bool CloseOneIdleConnectionInHigherLayeredPool(); 630 631 // Closes all idle sockets in |group| if |force| is true. Else, only closes 632 // idle sockets in |group| that timed out with respect to |now| or can't be 633 // reused. 634 void CleanupIdleSocketsInGroup(bool force, 635 Group* group, 636 const base::TimeTicks& now, 637 const char* net_log_reason_utf8); 638 639 Group* GetOrCreateGroup(const GroupId& group_id); 640 void RemoveGroup(const GroupId& group_id); 641 GroupMap::iterator RemoveGroup(GroupMap::iterator it); 642 643 // Called when the number of idle sockets changes. 644 void IncrementIdleCount(); 645 void DecrementIdleCount(); 646 647 // Scans the group map for groups which have an available socket slot and 648 // at least one pending request. Returns true if any groups are stalled, and 649 // if so (and if both |group| and |group_id| are not NULL), fills |group| 650 // and |group_id| with data of the stalled group having highest priority. 651 bool FindTopStalledGroup(Group** group, GroupId* group_id) const; 652 653 // Removes |job| from |group|, which must already own |job|. 654 void RemoveConnectJob(ConnectJob* job, Group* group); 655 656 // Tries to see if we can handle any more requests for |group|. 657 void OnAvailableSocketSlot(const GroupId& group_id, Group* group); 658 659 // Process a pending socket request for a group. 660 void ProcessPendingRequest(const GroupId& group_id, Group* group); 661 662 // Assigns |socket| to |handle| and updates |group|'s counters appropriately. 663 void HandOutSocket(std::unique_ptr<StreamSocket> socket, 664 ClientSocketHandle::SocketReuseType reuse_type, 665 const LoadTimingInfo::ConnectTiming& connect_timing, 666 ClientSocketHandle* handle, 667 base::TimeDelta time_idle, 668 Group* group, 669 const NetLogWithSource& net_log); 670 671 // Adds |socket| to the list of idle sockets for |group|. 672 void AddIdleSocket(std::unique_ptr<StreamSocket> socket, Group* group); 673 674 // Iterates through |group_map_|, canceling all ConnectJobs and deleting 675 // groups if they are no longer needed. 676 void CancelAllConnectJobs(); 677 678 // Iterates through |group_map_|, posting |error| callbacks for all 679 // requests, and then deleting groups if they are no longer needed. 680 void CancelAllRequestsWithError(int error); 681 682 // Returns true if we can't create any more sockets due to the total limit. 683 bool ReachedMaxSocketsLimit() const; 684 685 // This is the internal implementation of RequestSocket(). It differs in that 686 // it does not handle logging into NetLog of the queueing status of 687 // |request|. 688 // |preconnect_done_closure| is used only for preconnect requests. For 689 // preconnect requests, this method returns ERR_IO_PENDING only if a connect 690 // job is created and the connect job didn't finish synchronously. In such 691 // case, |preconnect_done_closure| will be called when the created connect job 692 // will be deleted. 693 // For normal non-preconnect requests, |preconnect_done_closure| must be null. 694 // And this method returns ERR_IO_PENDING when the number of sockets has 695 // reached the limit or the created connect job didn't finish synchronously. 696 // In such a case, the Request with a ClientSocketHandle must be registered to 697 // |group_map_| to receive the completion callback. 698 int RequestSocketInternal(const GroupId& group_id, 699 const Request& request, 700 base::OnceClosure preconnect_done_closure); 701 702 // Assigns an idle socket for the group to the request. 703 // Returns |true| if an idle socket is available, false otherwise. 704 bool AssignIdleSocketToRequest(const Request& request, Group* group); 705 706 static void LogBoundConnectJobToRequest( 707 const NetLogSource& connect_job_source, 708 const Request& request); 709 710 // Same as CloseOneIdleSocket() except it won't close an idle socket in 711 // |group|. If |group| is NULL, it is ignored. Returns true if it closed a 712 // socket. 713 bool CloseOneIdleSocketExceptInGroup(const Group* group); 714 715 // Checks if there are stalled socket groups that should be notified 716 // for possible wakeup. 717 void CheckForStalledSocketGroups(); 718 719 // Posts a task to call InvokeUserCallback() on the next iteration through the 720 // current message loop. Inserts |callback| into |pending_callback_map_|, 721 // keyed by |handle|. Apply |socket_tag| to the socket if socket successfully 722 // created. 723 void InvokeUserCallbackLater(ClientSocketHandle* handle, 724 CompletionOnceCallback callback, 725 int rv, 726 const SocketTag& socket_tag); 727 728 // These correspond to ConnectJob::Delegate methods, and are invoked by the 729 // Group a ConnectJob belongs to. 730 void OnConnectJobComplete(Group* group, int result, ConnectJob* job); 731 void OnNeedsProxyAuth(Group* group, 732 const HttpResponseInfo& response, 733 HttpAuthController* auth_controller, 734 base::OnceClosure restart_with_auth_callback, 735 ConnectJob* job); 736 737 // Invokes the user callback for |handle|. By the time this task has run, 738 // it's possible that the request has been cancelled, so |handle| may not 739 // exist in |pending_callback_map_|. We look up the callback and result code 740 // in |pending_callback_map_|. 741 void InvokeUserCallback(MayBeDangling<ClientSocketHandle> handle); 742 743 // Tries to close idle sockets in a higher level socket pool as long as this 744 // this pool is stalled. 745 void TryToCloseSocketsInLayeredPools(); 746 747 // Closes all idle sockets and cancels all unbound ConnectJobs associated with 748 // |it->second|. Also increments the group's generation number, ensuring any 749 // currently existing handed out socket will be silently closed when it is 750 // returned to the socket pool. Bound ConnectJobs will only be destroyed on 751 // once they complete, as they may be waiting on user input. No request 752 // (including bound ones) will be failed as a result of this call - instead, 753 // new ConnectJobs will be created. 754 // 755 // The group may be removed if this leaves the group empty. The caller must 756 // call CheckForStalledSocketGroups() after all applicable groups have been 757 // refreshed. 758 GroupMap::iterator RefreshGroup(GroupMap::iterator it, 759 const base::TimeTicks& now, 760 const char* net_log_reason_utf8); 761 762 GroupMap group_map_; 763 764 // Map of the ClientSocketHandles for which we have a pending Task to invoke a 765 // callback. This is necessary since, before we invoke said callback, it's 766 // possible that the request is cancelled. 767 PendingCallbackMap pending_callback_map_; 768 769 // The total number of idle sockets in the system. 770 int idle_socket_count_ = 0; 771 772 // Number of connecting sockets across all groups. 773 int connecting_socket_count_ = 0; 774 775 // Number of connected sockets we handed out across all groups. 776 int handed_out_socket_count_ = 0; 777 778 // The maximum total number of sockets. See ReachedMaxSocketsLimit. 779 const int max_sockets_; 780 781 // The maximum number of sockets kept per group. 782 const int max_sockets_per_group_; 783 784 // The time to wait until closing idle sockets. 785 const base::TimeDelta unused_idle_socket_timeout_; 786 const base::TimeDelta used_idle_socket_timeout_; 787 788 const ProxyServer proxy_server_; 789 790 const bool cleanup_on_ip_address_change_; 791 792 // TODO(vandebo) Remove when backup jobs move to TransportClientSocketPool 793 bool connect_backup_jobs_enabled_; 794 795 // Pools that create connections through |this|. |this| will try to close 796 // their idle sockets when it stalls. Must be empty on destruction. 797 std::set<HigherLayeredPool*> higher_pools_; 798 799 const raw_ptr<SSLClientContext> ssl_client_context_; 800 801 #if DCHECK_IS_ON() 802 // Reentrancy guard for RequestSocketInternal(). 803 bool request_in_process_ = false; 804 #endif // DCHECK_IS_ON() 805 806 base::WeakPtrFactory<TransportClientSocketPool> weak_factory_{this}; 807 }; 808 809 } // namespace net 810 811 #endif // NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_ 812