url_request_context_getter.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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-CHROMIUM file.
  4. #include "brightray/browser/url_request_context_getter.h"
  5. #include <algorithm>
  6. #include "base/command_line.h"
  7. #include "base/memory/ptr_util.h"
  8. #include "base/strings/string_number_conversions.h"
  9. #include "base/strings/string_util.h"
  10. #include "base/task_scheduler/post_task.h"
  11. #include "brightray/browser/browser_client.h"
  12. #include "brightray/browser/net/require_ct_delegate.h"
  13. #include "brightray/browser/net_log.h"
  14. #include "brightray/browser/network_delegate.h"
  15. #include "brightray/common/switches.h"
  16. #include "components/network_session_configurator/common/network_switches.h"
  17. #include "content/public/browser/browser_thread.h"
  18. #include "content/public/browser/cookie_store_factory.h"
  19. #include "content/public/browser/devtools_network_transaction_factory.h"
  20. #include "content/public/common/content_switches.h"
  21. #include "net/base/host_mapping_rules.h"
  22. #include "net/cert/cert_verifier.h"
  23. #include "net/cert/ct_known_logs.h"
  24. #include "net/cert/ct_log_verifier.h"
  25. #include "net/cert/ct_policy_enforcer.h"
  26. #include "net/cert/multi_log_ct_verifier.h"
  27. #include "net/cookies/cookie_monster.h"
  28. #include "net/dns/mapped_host_resolver.h"
  29. #include "net/http/http_auth_filter.h"
  30. #include "net/http/http_auth_handler_factory.h"
  31. #include "net/http/http_auth_preferences.h"
  32. #include "net/http/http_server_properties_impl.h"
  33. #include "net/log/net_log.h"
  34. #include "net/proxy/dhcp_proxy_script_fetcher_factory.h"
  35. #include "net/proxy/proxy_config.h"
  36. #include "net/proxy/proxy_config_service.h"
  37. #include "net/proxy/proxy_script_fetcher_impl.h"
  38. #include "net/proxy/proxy_service.h"
  39. #include "net/ssl/channel_id_service.h"
  40. #include "net/ssl/default_channel_id_store.h"
  41. #include "net/ssl/ssl_config_service_defaults.h"
  42. #include "net/url_request/data_protocol_handler.h"
  43. #include "net/url_request/file_protocol_handler.h"
  44. #include "net/url_request/static_http_user_agent_settings.h"
  45. #include "net/url_request/url_request_context.h"
  46. #include "net/url_request/url_request_context_builder.h"
  47. #include "net/url_request/url_request_context_storage.h"
  48. #include "net/url_request/url_request_intercepting_job_factory.h"
  49. #include "net/url_request/url_request_job_factory_impl.h"
  50. #include "storage/browser/quota/special_storage_policy.h"
  51. #include "url/url_constants.h"
  52. using content::BrowserThread;
  53. namespace brightray {
  54. std::string URLRequestContextGetter::Delegate::GetUserAgent() {
  55. return base::EmptyString();
  56. }
  57. std::unique_ptr<net::NetworkDelegate>
  58. URLRequestContextGetter::Delegate::CreateNetworkDelegate() {
  59. return nullptr;
  60. }
  61. std::unique_ptr<net::URLRequestJobFactory>
  62. URLRequestContextGetter::Delegate::CreateURLRequestJobFactory(
  63. content::ProtocolHandlerMap* protocol_handlers) {
  64. std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory(
  65. new net::URLRequestJobFactoryImpl);
  66. for (auto& it : *protocol_handlers) {
  67. job_factory->SetProtocolHandler(it.first,
  68. base::WrapUnique(it.second.release()));
  69. }
  70. protocol_handlers->clear();
  71. job_factory->SetProtocolHandler(
  72. url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));
  73. job_factory->SetProtocolHandler(
  74. url::kFileScheme,
  75. base::WrapUnique(
  76. new net::FileProtocolHandler(base::CreateTaskRunnerWithTraits(
  77. {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
  78. base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}))));
  79. return std::move(job_factory);
  80. }
  81. net::HttpCache::BackendFactory*
  82. URLRequestContextGetter::Delegate::CreateHttpCacheBackendFactory(
  83. const base::FilePath& base_path) {
  84. auto* command_line = base::CommandLine::ForCurrentProcess();
  85. int max_size = 0;
  86. base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize),
  87. &max_size);
  88. base::FilePath cache_path = base_path.Append(FILE_PATH_LITERAL("Cache"));
  89. return new net::HttpCache::DefaultBackend(
  90. net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path, max_size);
  91. }
  92. std::unique_ptr<net::CertVerifier>
  93. URLRequestContextGetter::Delegate::CreateCertVerifier(
  94. RequireCTDelegate* ct_delegate) {
  95. return net::CertVerifier::CreateDefault();
  96. }
  97. net::SSLConfigService*
  98. URLRequestContextGetter::Delegate::CreateSSLConfigService() {
  99. return new net::SSLConfigServiceDefaults;
  100. }
  101. std::vector<std::string>
  102. URLRequestContextGetter::Delegate::GetCookieableSchemes() {
  103. return {"http", "https", "ws", "wss"};
  104. }
  105. URLRequestContextGetter::URLRequestContextGetter(
  106. Delegate* delegate,
  107. NetLog* net_log,
  108. const base::FilePath& base_path,
  109. bool in_memory,
  110. scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
  111. content::ProtocolHandlerMap* protocol_handlers,
  112. content::URLRequestInterceptorScopedVector protocol_interceptors)
  113. : delegate_(delegate),
  114. net_log_(net_log),
  115. base_path_(base_path),
  116. in_memory_(in_memory),
  117. io_task_runner_(io_task_runner),
  118. protocol_interceptors_(std::move(protocol_interceptors)),
  119. job_factory_(nullptr),
  120. context_shutting_down_(false) {
  121. // Must first be created on the UI thread.
  122. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  123. if (protocol_handlers)
  124. std::swap(protocol_handlers_, *protocol_handlers);
  125. if (delegate_)
  126. user_agent_ = delegate_->GetUserAgent();
  127. // We must create the proxy config service on the UI loop on Linux because it
  128. // must synchronously run on the glib message loop. This will be passed to
  129. // the URLRequestContextStorage on the IO thread in GetURLRequestContext().
  130. proxy_config_service_ =
  131. net::ProxyService::CreateSystemProxyConfigService(io_task_runner_);
  132. }
  133. URLRequestContextGetter::~URLRequestContextGetter() {}
  134. void URLRequestContextGetter::NotifyContextShutdownOnIO() {
  135. context_shutting_down_ = true;
  136. cookie_change_sub_.reset();
  137. http_network_session_.reset();
  138. http_auth_preferences_.reset();
  139. host_mapping_rules_.reset();
  140. url_request_context_.reset();
  141. storage_.reset();
  142. ct_delegate_.reset();
  143. net::URLRequestContextGetter::NotifyContextShuttingDown();
  144. }
  145. void URLRequestContextGetter::OnCookieChanged(
  146. const net::CanonicalCookie& cookie,
  147. net::CookieStore::ChangeCause cause) {
  148. DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  149. if (!delegate_ || context_shutting_down_)
  150. return;
  151. content::BrowserThread::PostTask(
  152. content::BrowserThread::UI, FROM_HERE,
  153. base::BindOnce(
  154. &Delegate::NotifyCookieChange, base::Unretained(delegate_), cookie,
  155. !(cause == net::CookieStore::ChangeCause::INSERTED), cause));
  156. }
  157. net::HostResolver* URLRequestContextGetter::host_resolver() {
  158. return url_request_context_->host_resolver();
  159. }
  160. net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
  161. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  162. if (context_shutting_down_)
  163. return nullptr;
  164. if (!url_request_context_.get()) {
  165. ct_delegate_.reset(new RequireCTDelegate);
  166. auto& command_line = *base::CommandLine::ForCurrentProcess();
  167. url_request_context_.reset(new net::URLRequestContext);
  168. // --log-net-log
  169. if (net_log_) {
  170. net_log_->StartLogging();
  171. url_request_context_->set_net_log(net_log_);
  172. }
  173. storage_.reset(
  174. new net::URLRequestContextStorage(url_request_context_.get()));
  175. storage_->set_network_delegate(delegate_->CreateNetworkDelegate());
  176. auto cookie_path = in_memory_
  177. ? base::FilePath()
  178. : base_path_.Append(FILE_PATH_LITERAL("Cookies"));
  179. std::unique_ptr<net::CookieStore> cookie_store =
  180. content::CreateCookieStore(content::CookieStoreConfig(
  181. cookie_path, content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
  182. nullptr));
  183. storage_->set_cookie_store(std::move(cookie_store));
  184. // Set custom schemes that can accept cookies.
  185. net::CookieMonster* cookie_monster =
  186. static_cast<net::CookieMonster*>(url_request_context_->cookie_store());
  187. cookie_monster->SetCookieableSchemes(delegate_->GetCookieableSchemes());
  188. // Cookie store will outlive notifier by order of declaration
  189. // in the header.
  190. cookie_change_sub_ =
  191. url_request_context_->cookie_store()->AddCallbackForAllChanges(
  192. base::Bind(&URLRequestContextGetter::OnCookieChanged, this));
  193. storage_->set_channel_id_service(std::make_unique<net::ChannelIDService>(
  194. new net::DefaultChannelIDStore(nullptr)));
  195. storage_->set_http_user_agent_settings(
  196. base::WrapUnique(new net::StaticHttpUserAgentSettings(
  197. net::HttpUtil::GenerateAcceptLanguageHeader(
  198. BrowserClient::Get()->GetApplicationLocale()),
  199. user_agent_)));
  200. std::unique_ptr<net::HostResolver> host_resolver(
  201. net::HostResolver::CreateDefaultResolver(nullptr));
  202. // --host-resolver-rules
  203. if (command_line.HasSwitch(::switches::kHostResolverRules)) {
  204. std::unique_ptr<net::MappedHostResolver> remapped_resolver(
  205. new net::MappedHostResolver(std::move(host_resolver)));
  206. remapped_resolver->SetRulesFromString(
  207. command_line.GetSwitchValueASCII(::switches::kHostResolverRules));
  208. host_resolver = std::move(remapped_resolver);
  209. }
  210. // --proxy-server
  211. if (command_line.HasSwitch(switches::kNoProxyServer)) {
  212. storage_->set_proxy_service(net::ProxyService::CreateDirect());
  213. } else if (command_line.HasSwitch(switches::kProxyServer)) {
  214. net::ProxyConfig proxy_config;
  215. proxy_config.proxy_rules().ParseFromString(
  216. command_line.GetSwitchValueASCII(switches::kProxyServer));
  217. proxy_config.proxy_rules().bypass_rules.ParseFromString(
  218. command_line.GetSwitchValueASCII(switches::kProxyBypassList));
  219. storage_->set_proxy_service(net::ProxyService::CreateFixed(proxy_config));
  220. } else if (command_line.HasSwitch(switches::kProxyPacUrl)) {
  221. auto proxy_config = net::ProxyConfig::CreateFromCustomPacURL(
  222. GURL(command_line.GetSwitchValueASCII(switches::kProxyPacUrl)));
  223. proxy_config.set_pac_mandatory(true);
  224. storage_->set_proxy_service(net::ProxyService::CreateFixed(proxy_config));
  225. } else {
  226. storage_->set_proxy_service(
  227. net::ProxyService::CreateUsingSystemProxyResolver(
  228. std::move(proxy_config_service_), net_log_));
  229. }
  230. std::vector<std::string> schemes;
  231. schemes.push_back(std::string("basic"));
  232. schemes.push_back(std::string("digest"));
  233. schemes.push_back(std::string("ntlm"));
  234. schemes.push_back(std::string("negotiate"));
  235. #if defined(OS_POSIX)
  236. http_auth_preferences_.reset(
  237. new net::HttpAuthPreferences(schemes, std::string()));
  238. #else
  239. http_auth_preferences_.reset(new net::HttpAuthPreferences(schemes));
  240. #endif
  241. // --auth-server-whitelist
  242. if (command_line.HasSwitch(switches::kAuthServerWhitelist)) {
  243. http_auth_preferences_->set_server_whitelist(
  244. command_line.GetSwitchValueASCII(switches::kAuthServerWhitelist));
  245. }
  246. // --auth-negotiate-delegate-whitelist
  247. if (command_line.HasSwitch(switches::kAuthNegotiateDelegateWhitelist)) {
  248. http_auth_preferences_->set_delegate_whitelist(
  249. command_line.GetSwitchValueASCII(
  250. switches::kAuthNegotiateDelegateWhitelist));
  251. }
  252. auto auth_handler_factory = net::HttpAuthHandlerRegistryFactory::Create(
  253. http_auth_preferences_.get(), host_resolver.get());
  254. std::unique_ptr<net::TransportSecurityState> transport_security_state =
  255. base::WrapUnique(new net::TransportSecurityState);
  256. transport_security_state->SetRequireCTDelegate(ct_delegate_.get());
  257. storage_->set_transport_security_state(std::move(transport_security_state));
  258. storage_->set_cert_verifier(
  259. delegate_->CreateCertVerifier(ct_delegate_.get()));
  260. storage_->set_ssl_config_service(delegate_->CreateSSLConfigService());
  261. storage_->set_http_auth_handler_factory(std::move(auth_handler_factory));
  262. std::unique_ptr<net::HttpServerProperties> server_properties(
  263. new net::HttpServerPropertiesImpl);
  264. storage_->set_http_server_properties(std::move(server_properties));
  265. std::unique_ptr<net::MultiLogCTVerifier> ct_verifier =
  266. std::make_unique<net::MultiLogCTVerifier>();
  267. ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
  268. storage_->set_cert_transparency_verifier(std::move(ct_verifier));
  269. storage_->set_ct_policy_enforcer(std::make_unique<net::CTPolicyEnforcer>());
  270. net::HttpNetworkSession::Params network_session_params;
  271. network_session_params.ignore_certificate_errors = false;
  272. // --disable-http2
  273. if (command_line.HasSwitch(switches::kDisableHttp2))
  274. network_session_params.enable_http2 = false;
  275. // --ignore-certificate-errors
  276. if (command_line.HasSwitch(::switches::kIgnoreCertificateErrors))
  277. network_session_params.ignore_certificate_errors = true;
  278. // --host-rules
  279. if (command_line.HasSwitch(switches::kHostRules)) {
  280. host_mapping_rules_.reset(new net::HostMappingRules);
  281. host_mapping_rules_->SetRulesFromString(
  282. command_line.GetSwitchValueASCII(switches::kHostRules));
  283. network_session_params.host_mapping_rules = *host_mapping_rules_.get();
  284. }
  285. // Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
  286. storage_->set_host_resolver(std::move(host_resolver));
  287. net::HttpNetworkSession::Context network_session_context;
  288. net::URLRequestContextBuilder::SetHttpNetworkSessionComponents(
  289. url_request_context_.get(), &network_session_context);
  290. http_network_session_.reset(new net::HttpNetworkSession(
  291. network_session_params, network_session_context));
  292. std::unique_ptr<net::HttpCache::BackendFactory> backend;
  293. if (in_memory_) {
  294. backend = net::HttpCache::DefaultBackend::InMemory(0);
  295. } else {
  296. backend.reset(delegate_->CreateHttpCacheBackendFactory(base_path_));
  297. }
  298. storage_->set_http_transaction_factory(std::make_unique<net::HttpCache>(
  299. content::CreateDevToolsNetworkTransactionFactory(
  300. http_network_session_.get()),
  301. std::move(backend), false));
  302. std::unique_ptr<net::URLRequestJobFactory> job_factory =
  303. delegate_->CreateURLRequestJobFactory(&protocol_handlers_);
  304. job_factory_ = job_factory.get();
  305. // Set up interceptors in the reverse order.
  306. std::unique_ptr<net::URLRequestJobFactory> top_job_factory =
  307. std::move(job_factory);
  308. if (!protocol_interceptors_.empty()) {
  309. for (auto it = protocol_interceptors_.rbegin();
  310. it != protocol_interceptors_.rend(); ++it) {
  311. top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
  312. std::move(top_job_factory), std::move(*it)));
  313. }
  314. protocol_interceptors_.clear();
  315. }
  316. storage_->set_job_factory(std::move(top_job_factory));
  317. }
  318. return url_request_context_.get();
  319. }
  320. scoped_refptr<base::SingleThreadTaskRunner>
  321. URLRequestContextGetter::GetNetworkTaskRunner() const {
  322. return BrowserThread::GetTaskRunnerForThread(BrowserThread::IO);
  323. }
  324. } // namespace brightray