Debian Codegraph @

samples/chromium-sample/src/io_thread.h

raw symbols SCIP
1 // Copyright (c) 2012 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
5 #ifndef CHROME_BROWSER_IO_THREAD_H_
6 #define CHROME_BROWSER_IO_THREAD_H_
7
8 #include <stddef.h>
9 #include <stdint.h>
10
11 #include <map>
12 #include <memory>
13 #include <set>
14 #include <string>
15 #include <unordered_set>
16 #include <vector>
17
18 #include "base/compiler_specific.h"
19 #include "base/macros.h"
20 #include "base/memory/ref_counted.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/strings/string_piece.h"
23 #include "base/time/time.h"
24 #include "build/build_config.h"
25 #include "chrome/browser/net/chrome_network_delegate.h"
26 #include "chrome/common/features.h"
27 #include "components/prefs/pref_member.h"
28 #include "components/ssl_config/ssl_config_service_manager.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/browser/browser_thread_delegate.h"
31 #include "net/base/network_change_notifier.h"
32 #include "net/http/http_network_session.h"
33
34 class PrefProxyConfigTracker;
35 class PrefService;
36 class PrefRegistrySimple;
37 class SystemURLRequestContextGetter;
38
39 namespace base {
40 class CommandLine;
41 }
42
43 #if BUILDFLAG(ANDROID_JAVA_UI)
44 namespace chrome {
45 namespace android {
46 class ExternalDataUseObserver;
47 }
48 }
49 #endif // BUILDFLAG(ANDROID_JAVA_UI)
50
51 namespace chrome_browser_net {
52 class DnsProbeService;
53 }
54
55 namespace data_usage {
56 class DataUseAggregator;
57 }
58
59 namespace extensions {
60 class EventRouterForwarder;
61 }
62
63 namespace net {
64 class CTPolicyEnforcer;
65 class CertVerifier;
66 class ChannelIDService;
67 class CookieStore;
68 class CTLogVerifier;
69 class FtpTransactionFactory;
70 class HostMappingRules;
71 class HostResolver;
72 class HttpAuthHandlerRegistryFactory;
73 class HttpAuthPreferences;
74 class HttpServerProperties;
75 class HttpTransactionFactory;
76 class HttpUserAgentSettings;
77 class NetworkDelegate;
78 class NetworkQualityEstimator;
79 class ProxyConfigService;
80 class ProxyService;
81 class SSLConfigService;
82 class TransportSecurityState;
83 class URLRequestBackoffManager;
84 class URLRequestContext;
85 class URLRequestContextGetter;
86 class URLRequestJobFactory;
87 } // namespace net
88
89 namespace net_log {
90 class ChromeNetLog;
91 }
92
93 namespace policy {
94 class PolicyService;
95 } // namespace policy
96
97 namespace test {
98 class IOThreadPeer;
99 } // namespace test
100
101 // Contains state associated with, initialized and cleaned up on, and
102 // primarily used on, the IO thread.
103 //
104 // If you are looking to interact with the IO thread (e.g. post tasks
105 // to it or check if it is the current thread), see
106 // content::BrowserThread.
107 class IOThread : public content::BrowserThreadDelegate {
108 public:
109 struct Globals {
110 class SystemRequestContextLeakChecker {
111 public:
112 explicit SystemRequestContextLeakChecker(Globals* globals);
113 ~SystemRequestContextLeakChecker();
114
115 private:
116 Globals* const globals_;
117 };
118
119 Globals();
120 ~Globals();
121
122 // Global aggregator of data use. It must outlive the
123 // |system_network_delegate|.
124 std::unique_ptr<data_usage::DataUseAggregator> data_use_aggregator;
125 #if BUILDFLAG(ANDROID_JAVA_UI)
126 // An external observer of data use.
127 std::unique_ptr<chrome::android::ExternalDataUseObserver>
128 external_data_use_observer;
129 #endif // BUILDFLAG(ANDROID_JAVA_UI)
130 // The "system" NetworkDelegate, used for Profile-agnostic network events.
131 std::unique_ptr<net::NetworkDelegate> system_network_delegate;
132 std::unique_ptr<net::HostResolver> host_resolver;
133 std::unique_ptr<net::CertVerifier> cert_verifier;
134 // The ChannelIDService must outlive the HttpTransactionFactory.
135 std::unique_ptr<net::ChannelIDService> system_channel_id_service;
136 // This TransportSecurityState doesn't load or save any state. It's only
137 // used to enforce pinning for system requests and will only use built-in
138 // pins.
139 std::unique_ptr<net::TransportSecurityState> transport_security_state;
140 std::vector<scoped_refptr<const net::CTLogVerifier>> ct_logs;
141 std::unique_ptr<net::CTVerifier> cert_transparency_verifier;
142 std::unique_ptr<net::CTPolicyEnforcer> ct_policy_enforcer;
143 scoped_refptr<net::SSLConfigService> ssl_config_service;
144 std::unique_ptr<net::HttpAuthHandlerFactory> http_auth_handler_factory;
145 std::unique_ptr<net::HttpServerProperties> http_server_properties;
146 std::unique_ptr<net::ProxyService> proxy_script_fetcher_proxy_service;
147 std::unique_ptr<net::HttpNetworkSession>
148 proxy_script_fetcher_http_network_session;
149 std::unique_ptr<net::HttpTransactionFactory>
150 proxy_script_fetcher_http_transaction_factory;
151 std::unique_ptr<net::FtpTransactionFactory>
152 proxy_script_fetcher_ftp_transaction_factory;
153 std::unique_ptr<net::URLRequestJobFactory>
154 proxy_script_fetcher_url_request_job_factory;
155 std::unique_ptr<net::URLRequestBackoffManager> url_request_backoff_manager;
156 std::unique_ptr<net::HttpAuthPreferences> http_auth_preferences;
157 // TODO(willchan): Remove proxy script fetcher context since it's not
158 // necessary now that I got rid of refcounting URLRequestContexts.
159 //
160 // The first URLRequestContext is |system_url_request_context|. We introduce
161 // |proxy_script_fetcher_context| for the second context. It has a direct
162 // ProxyService, since we always directly connect to fetch the PAC script.
163 std::unique_ptr<net::URLRequestContext> proxy_script_fetcher_context;
164 std::unique_ptr<net::ProxyService> system_proxy_service;
165 std::unique_ptr<net::HttpNetworkSession> system_http_network_session;
166 std::unique_ptr<net::HttpTransactionFactory>
167 system_http_transaction_factory;
168 std::unique_ptr<net::URLRequestJobFactory> system_url_request_job_factory;
169 std::unique_ptr<net::URLRequestContext> system_request_context;
170 SystemRequestContextLeakChecker system_request_context_leak_checker;
171 // |system_cookie_store| and |system_channel_id_service| are shared
172 // between |proxy_script_fetcher_context| and |system_request_context|.
173 std::unique_ptr<net::CookieStore> system_cookie_store;
174 #if defined(ENABLE_EXTENSIONS)
175 scoped_refptr<extensions::EventRouterForwarder>
176 extension_event_router_forwarder;
177 #endif
178 std::unique_ptr<net::HostMappingRules> host_mapping_rules;
179 std::unique_ptr<net::HttpUserAgentSettings> http_user_agent_settings;
180 std::unique_ptr<net::NetworkQualityEstimator> network_quality_estimator;
181
182 // NetErrorTabHelper uses |dns_probe_service| to send DNS probes when a
183 // main frame load fails with a DNS error in order to provide more useful
184 // information to the renderer so it can show a more specific error page.
185 std::unique_ptr<chrome_browser_net::DnsProbeService> dns_probe_service;
186
187 // Enables Brotli Content-Encoding support
188 bool enable_brotli;
189 };
190
191 // Helper class to configure HttpNetworkSession::Params and
192 // HttpServerProperties based on field trials, policy, and command line.
193 class NetworkSessionConfigurator {
194 public:
195 // Configure |params| based on field trials and policy arguments.
196 static void ParseFieldTrials(bool is_spdy_allowed_by_policy,
197 bool is_quic_allowed_by_policy,
198 net::HttpNetworkSession::Params* params);
199
200 // Configure |params| based on field trials, policy arguments,
201 // and command line.
202 static void ParseFieldTrialsAndCommandLine(
203 bool is_spdy_allowed_by_policy,
204 bool is_quic_allowed_by_policy,
205 net::HttpNetworkSession::Params* params);
206
207 private:
208 // Map from name to value for all parameters associate with a field trial.
209 using VariationParameters = std::map<std::string, std::string>;
210
211 static void ParseFieldTrialsAndCommandLineInternal(
212 const base::CommandLine& command_line,
213 bool is_spdy_allowed_by_policy,
214 bool is_quic_allowed_by_policy,
215 net::HttpNetworkSession::Params* params);
216
217 // Configures Alternative Services based on command line options and the
218 // field trial group.
219 static void ConfigureAltSvcParams(const base::CommandLine& command_line,
220 base::StringPiece altsvc_trial_group,
221 net::HttpNetworkSession::Params* params);
222
223 // Configures QUIC options based on the flags in |command_line| as well as
224 // the QUIC field trial group and parameters. Must be called before
225 // ConfigureSpdyParams.
226 static void ConfigureQuicParams(
227 const base::CommandLine& command_line,
228 base::StringPiece quic_trial_group,
229 const VariationParameters& quic_trial_params,
230 bool is_quic_allowed_by_policy,
231 net::HttpNetworkSession::Params* params);
232
233 // Configures available SPDY protocol versions and parameters based on
234 // command line flags as well as SPDY field trial group and parameters.
235 // Must be called after ConfigureQuicParams.
236 static void ConfigureSpdyParams(
237 const base::CommandLine& command_line,
238 base::StringPiece spdy_trial_group,
239 const VariationParameters& spdy_trial_params,
240 bool is_spdy_allowed_by_policy,
241 net::HttpNetworkSession::Params* params);
242
243 // Configure TCP FastOpen based on the field trial group.
244 static void ConfigureTCPFastOpenParams(
245 base::StringPiece tfo_trial_group,
246 net::HttpNetworkSession::Params* params);
247
248 // Configures NPN based on command line and the field trial group.
249 static void ConfigureNPNParams(const base::CommandLine& command_line,
250 base::StringPiece npn_trial_group,
251 net::HttpNetworkSession::Params* params);
252
253 // Configures the use of priority dependencies based on the field trial
254 // group.
255 static void ConfigurePriorityDependencies(
256 base::StringPiece priority_dependencies_trial_group,
257 net::HttpNetworkSession::Params* params);
258
259 // Returns true if QUIC should be disabled when a connection times out with
260 // open streams.
261 static bool ShouldDisableQuicWhenConnectionTimesOutWithOpenStreams(
262 const VariationParameters& quic_trial_params);
263
264 // Returns true if QUIC should be enabled, either as a result of a field
265 // trial or a command line flag.
266 static bool ShouldEnableQuic(const base::CommandLine& command_line,
267 base::StringPiece quic_trial_group,
268 bool quic_allowed_by_policy);
269
270 // Returns true if the selection of the ephemeral port in bind() should be
271 // performed by Chromium, and false if the OS should select the port. The
272 // OS option is used to prevent Windows from posting a security warning
273 // dialog.
274 static bool ShouldEnableQuicPortSelection(
275 const base::CommandLine& command_line);
276
277 // Returns true if QUIC should always require handshake confirmation during
278 // the QUIC handshake.
279 static bool ShouldQuicAlwaysRequireHandshakeConfirmation(
280 const VariationParameters& quic_trial_params);
281
282 // Returns true if QUIC should disable connection pooling.
283 static bool ShouldQuicDisableConnectionPooling(
284 const VariationParameters& quic_trial_params);
285
286 // Returns the ratio of time to load QUIC sever information from disk cache
287 // to 'smoothed RTT' based on field trial. Returns 0 if there is an error
288 // parsing the field trial params, or if the default value should be used.
289 static float GetQuicLoadServerInfoTimeoutSrttMultiplier(
290 const VariationParameters& quic_trial_params);
291
292 // Returns true if QUIC's connection racing should be enabled.
293 static bool ShouldQuicEnableConnectionRacing(
294 const VariationParameters& quic_trial_params);
295
296 // Returns true if QUIC's should use non-blocking IO.
297 static bool ShouldQuicEnableNonBlockingIO(
298 const VariationParameters& quic_trial_params);
299
300 // Returns true if QUIC shouldn't load QUIC server information from the disk
301 // cache.
302 static bool ShouldQuicDisableDiskCache(
303 const VariationParameters& quic_trial_params);
304
305 // Returns true if QUIC should prefer AES-GCN even without hardware support.
306 static bool ShouldQuicPreferAes(
307 const VariationParameters& quic_trial_params);
308
309 // Returns true if QUIC should enable alternative services for different
310 // host.
311 static bool ShouldQuicEnableAlternativeServicesForDifferentHost(
312 const base::CommandLine& command_line,
313 const VariationParameters& quic_trial_params);
314
315 // Returns the maximum number of QUIC connections with high packet loss in a
316 // row after which QUIC should be disabled. Returns 0 if the default value
317 // should be used.
318 static int GetQuicMaxNumberOfLossyConnections(
319 const VariationParameters& quic_trial_params);
320
321 // Returns the packet loss rate in fraction after which a QUIC connection is
322 // closed and is considered as a lossy connection. Returns 0 if the default
323 // value should be used.
324 static float GetQuicPacketLossThreshold(
325 const VariationParameters& quic_trial_params);
326
327 // Returns the size of the QUIC receive buffer to use, or 0 if the default
328 // should be used.
329 static int GetQuicSocketReceiveBufferSize(
330 const VariationParameters& quic_trial_params);
331
332 // Returns true if QUIC should close sessions when any of the client's IP
333 // addresses change.
334 static bool ShouldQuicCloseSessionsOnIpChange(
335 const VariationParameters& quic_trial_params);
336
337 // Returns the idle connection timeout for QUIC connections. Returns 0 if
338 // there is an error parsing any of the options, or if the default value
339 // should be used.
340 static int GetQuicIdleConnectionTimeoutSeconds(
341 const VariationParameters& quic_trial_params);
342
343 // Returns true if PreConnect should be disabled if QUIC can do 0RTT.
344 static bool ShouldQuicDisablePreConnectIfZeroRtt(
345 const VariationParameters& quic_trial_params);
346
347 // Returns the set of hosts to whitelist for QUIC.
348 static std::unordered_set<std::string> GetQuicHostWhitelist(
349 const base::CommandLine& command_line,
350 const VariationParameters& quic_trial_params);
351
352 // Returns true if QUIC should migrate sessions when primary network
353 // changes.
354 static bool ShouldQuicMigrateSessionsOnNetworkChange(
355 const VariationParameters& quic_trial_params);
356
357 // Returns true if QUIC should migrate sessions early.
358 static bool ShouldQuicMigrateSessionsEarly(
359 const VariationParameters& quic_trial_params);
360
361 // Returns the maximum length for QUIC packets, based on any flags in
362 // |command_line| or the field trial. Returns 0 if there is an error
363 // parsing any of the options, or if the default value should be used.
364 static size_t GetQuicMaxPacketLength(
365 const base::CommandLine& command_line,
366 const VariationParameters& quic_trial_params);
367
368 // Returns the QUIC versions specified by any flags in |command_line| or
369 // |quic_trial_params|.
370 static net::QuicVersion GetQuicVersion(
371 const base::CommandLine& command_line,
372 const VariationParameters& quic_trial_params);
373
374 // Returns the QUIC version specified by |quic_version| or
375 // QUIC_VERSION_UNSUPPORTED if |quic_version| is invalid.
376 static net::QuicVersion ParseQuicVersion(const std::string& quic_version);
377
378 // Returns the QUIC connection options specified by any flags in
379 // |command_line| or |quic_trial_params|.
380 static net::QuicTagVector GetQuicConnectionOptions(
381 const base::CommandLine& command_line,
382 const VariationParameters& quic_trial_params);
383 };
384
385 // |net_log| must either outlive the IOThread or be NULL.
386 IOThread(PrefService* local_state,
387 policy::PolicyService* policy_service,
388 net_log::ChromeNetLog* net_log,
389 extensions::EventRouterForwarder* extension_event_router_forwarder);
390
391 ~IOThread() override;
392
393 static void RegisterPrefs(PrefRegistrySimple* registry);
394
395 // Can only be called on the IO thread.
396 Globals* globals();
397
398 // Allows overriding Globals in tests where IOThread::Init() and
399 // IOThread::CleanUp() are not called. This allows for injecting mocks into
400 // IOThread global objects.
401 void SetGlobalsForTesting(Globals* globals);
402
403 net_log::ChromeNetLog* net_log();
404
405 // Handles changing to On The Record mode, discarding confidential data.
406 void ChangedToOnTheRecord();
407
408 // Returns a getter for the URLRequestContext. Only called on the UI thread.
409 net::URLRequestContextGetter* system_url_request_context_getter();
410
411 // Clears the host cache. Intended to be used to prevent exposing recently
412 // visited sites on about:net-internals/#dns and about:dns pages. Must be
413 // called on the IO thread.
414 void ClearHostCache();
415
416 const net::HttpNetworkSession::Params& NetworkSessionParams() const;
417
418 base::TimeTicks creation_time() const;
419
420 // Returns the callback for updating data use prefs.
421 const metrics::UpdateUsagePrefCallbackType& GetMetricsDataUseForwarder();
422
423 private:
424 // Provide SystemURLRequestContextGetter with access to
425 // InitSystemRequestContext().
426 friend class SystemURLRequestContextGetter;
427
428 friend class test::IOThreadPeer;
429
430 // BrowserThreadDelegate implementation, runs on the IO thread.
431 // This handles initialization and destruction of state that must
432 // live on the IO thread.
433 void Init() override;
434 void CleanUp() override;
435
436 void InitializeNetworkOptions(const base::CommandLine& parsed_command_line);
437
438 // Global state must be initialized on the IO thread, then this
439 // method must be invoked on the UI thread.
440 void InitSystemRequestContext();
441
442 // Lazy initialization of system request context for
443 // SystemURLRequestContextGetter. To be called on IO thread only
444 // after global state has been initialized on the IO thread, and
445 // SystemRequestContext state has been initialized on the UI thread.
446 void InitSystemRequestContextOnIOThread();
447
448 void CreateDefaultAuthHandlerFactory();
449
450 // Returns an SSLConfigService instance.
451 net::SSLConfigService* GetSSLConfigService();
452
453 void ChangedToOnTheRecordOnIOThread();
454
455 void UpdateDnsClientEnabled();
456 void UpdateServerWhitelist();
457 void UpdateDelegateWhitelist();
458 void UpdateAndroidAuthNegotiateAccountType();
459 void UpdateNegotiateDisableCnameLookup();
460 void UpdateNegotiateEnablePort();
461
462 extensions::EventRouterForwarder* extension_event_router_forwarder() {
463 #if defined(ENABLE_EXTENSIONS)
464 return extension_event_router_forwarder_;
465 #else
466 return NULL;
467 #endif
468 }
469 static net::URLRequestContext* ConstructSystemRequestContext(
470 IOThread::Globals* globals,
471 const net::HttpNetworkSession::Params& params,
472 net::NetLog* net_log);
473
474 // TODO(willchan): Remove proxy script fetcher context since it's not
475 // necessary now that I got rid of refcounting URLRequestContexts.
476 // See IOThread::Globals for details.
477 static net::URLRequestContext* ConstructProxyScriptFetcherContext(
478 IOThread::Globals* globals,
479 const net::HttpNetworkSession::Params& params,
480 net::NetLog* net_log);
481
482 // The NetLog is owned by the browser process, to allow logging from other
483 // threads during shutdown, but is used most frequently on the IOThread.
484 net_log::ChromeNetLog* net_log_;
485
486 #if defined(ENABLE_EXTENSIONS)
487 // The extensions::EventRouterForwarder allows for sending events to
488 // extensions from the IOThread.
489 extensions::EventRouterForwarder* extension_event_router_forwarder_;
490 #endif
491
492 // These member variables are basically global, but their lifetimes are tied
493 // to the IOThread. IOThread owns them all, despite not using scoped_ptr.
494 // This is because the destructor of IOThread runs on the wrong thread. All
495 // member variables should be deleted in CleanUp().
496
497 // These member variables are initialized in Init() and do not change for the
498 // lifetime of the IO thread.
499
500 Globals* globals_;
501
502 net::HttpNetworkSession::Params params_;
503 NetworkSessionConfigurator network_session_configurator_;
504
505 // Observer that logs network changes to the ChromeNetLog.
506 class LoggingNetworkChangeObserver;
507 std::unique_ptr<LoggingNetworkChangeObserver> network_change_observer_;
508
509 BooleanPrefMember system_enable_referrers_;
510
511 BooleanPrefMember dns_client_enabled_;
512
513 BooleanPrefMember quick_check_enabled_;
514
515 // Store HTTP Auth-related policies in this thread.
516 // TODO(aberent) Make the list of auth schemes a PrefMember, so that the
517 // policy can change after startup (https://crbug/549273).
518 std::string auth_schemes_;
519 BooleanPrefMember negotiate_disable_cname_lookup_;
520 BooleanPrefMember negotiate_enable_port_;
521 StringPrefMember auth_server_whitelist_;
522 StringPrefMember auth_delegate_whitelist_;
523
524 #if defined(OS_ANDROID)
525 StringPrefMember auth_android_negotiate_account_type_;
526 #endif
527 #if defined(OS_POSIX) && !defined(OS_ANDROID)
528 // No PrefMember for the GSSAPI library name, since changing it after startup
529 // requires unloading the existing GSSAPI library, which could cause all sorts
530 // of problems for, for example, active Negotiate transactions.
531 std::string gssapi_library_name_;
532 #endif
533
534 // This is an instance of the default SSLConfigServiceManager for the current
535 // platform and it gets SSL preferences from local_state object.
536 std::unique_ptr<ssl_config::SSLConfigServiceManager>
537 ssl_config_service_manager_;
538
539 // These member variables are initialized by a task posted to the IO thread,
540 // which gets posted by calling certain member functions of IOThread.
541 std::unique_ptr<net::ProxyConfigService> system_proxy_config_service_;
542
543 std::unique_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
544
545 scoped_refptr<net::URLRequestContextGetter>
546 system_url_request_context_getter_;
547
548 // True if SPDY is allowed by policy.
549 bool is_spdy_allowed_by_policy_;
550
551 // True if QUIC is allowed by policy.
552 bool is_quic_allowed_by_policy_;
553
554 const base::TimeTicks creation_time_;
555
556 // Callback for updating data use prefs which needs to be initialized on UI
557 // thread and passed to |ChromeNetworkDelegate|.
558 metrics::UpdateUsagePrefCallbackType metrics_data_use_forwarder_;
559
560 base::WeakPtrFactory<IOThread> weak_factory_;
561
562 DISALLOW_COPY_AND_ASSIGN(IOThread);
563 };
564
565 #endif // CHROME_BROWSER_IO_THREAD_H_