Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / android_webview / browser / net / aw_url_request_context_getter.cc
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 #include "android_webview/browser/net/aw_url_request_context_getter.h"
6
7 #include <vector>
8
9 #include "android_webview/browser/aw_browser_context.h"
10 #include "android_webview/browser/aw_content_browser_client.h"
11 #include "android_webview/browser/aw_request_interceptor.h"
12 #include "android_webview/browser/net/aw_network_delegate.h"
13 #include "android_webview/browser/net/aw_url_request_job_factory.h"
14 #include "android_webview/browser/net/init_native_callback.h"
15 #include "android_webview/common/aw_content_client.h"
16 #include "base/command_line.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/threading/sequenced_worker_pool.h"
19 #include "components/data_reduction_proxy/browser/data_reduction_proxy_config_service.h"
20 #include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h"
21 #include "components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.h"
22 #include "content/public/browser/browser_thread.h"
23 #include "content/public/browser/content_browser_client.h"
24 #include "content/public/browser/cookie_store_factory.h"
25 #include "content/public/common/content_client.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/url_constants.h"
28 #include "net/base/cache_type.h"
29 #include "net/cookies/cookie_store.h"
30 #include "net/dns/mapped_host_resolver.h"
31 #include "net/http/http_cache.h"
32 #include "net/http/http_stream_factory.h"
33 #include "net/proxy/proxy_service.h"
34 #include "net/url_request/data_protocol_handler.h"
35 #include "net/url_request/file_protocol_handler.h"
36 #include "net/url_request/protocol_intercept_job_factory.h"
37 #include "net/url_request/url_request_context_builder.h"
38 #include "net/url_request/url_request_context.h"
39
40 using content::BrowserThread;
41 using data_reduction_proxy::DataReductionProxySettings;
42
43 namespace android_webview {
44
45
46 namespace {
47
48 void ApplyCmdlineOverridesToURLRequestContextBuilder(
49     net::URLRequestContextBuilder* builder) {
50   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
51   if (command_line.HasSwitch(switches::kHostResolverRules)) {
52     // If hostname remappings were specified on the command-line, layer these
53     // rules on top of the real host resolver. This allows forwarding all
54     // requests through a designated test server.
55     scoped_ptr<net::MappedHostResolver> host_resolver(
56         new net::MappedHostResolver(
57             net::HostResolver::CreateDefaultResolver(NULL)));
58     host_resolver->SetRulesFromString(
59         command_line.GetSwitchValueASCII(switches::kHostResolverRules));
60     builder->set_host_resolver(host_resolver.release());
61   }
62 }
63
64 void ApplyCmdlineOverridesToNetworkSessionParams(
65     net::HttpNetworkSession::Params* params) {
66   int value;
67   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
68   if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
69     base::StringToInt(command_line.GetSwitchValueASCII(
70         switches::kTestingFixedHttpPort), &value);
71     params->testing_fixed_http_port = value;
72   }
73   if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
74     base::StringToInt(command_line.GetSwitchValueASCII(
75         switches::kTestingFixedHttpsPort), &value);
76     params->testing_fixed_https_port = value;
77   }
78 }
79
80 void PopulateNetworkSessionParams(
81     net::URLRequestContext* context,
82     net::HttpNetworkSession::Params* params) {
83   params->host_resolver = context->host_resolver();
84   params->cert_verifier = context->cert_verifier();
85   params->server_bound_cert_service = context->server_bound_cert_service();
86   params->transport_security_state = context->transport_security_state();
87   params->proxy_service = context->proxy_service();
88   params->ssl_config_service = context->ssl_config_service();
89   params->http_auth_handler_factory = context->http_auth_handler_factory();
90   params->network_delegate = context->network_delegate();
91   params->http_server_properties = context->http_server_properties();
92   params->net_log = context->net_log();
93   ApplyCmdlineOverridesToNetworkSessionParams(params);
94 }
95
96 scoped_ptr<net::URLRequestJobFactory> CreateJobFactory(
97     content::ProtocolHandlerMap* protocol_handlers) {
98   scoped_ptr<AwURLRequestJobFactory> aw_job_factory(new AwURLRequestJobFactory);
99   bool set_protocol = aw_job_factory->SetProtocolHandler(
100       content::kFileScheme,
101       new net::FileProtocolHandler(
102           content::BrowserThread::GetBlockingPool()->
103               GetTaskRunnerWithShutdownBehavior(
104                   base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
105   DCHECK(set_protocol);
106   set_protocol = aw_job_factory->SetProtocolHandler(
107       content::kDataScheme, new net::DataProtocolHandler());
108   DCHECK(set_protocol);
109   set_protocol = aw_job_factory->SetProtocolHandler(
110       content::kBlobScheme,
111       (*protocol_handlers)[content::kBlobScheme].release());
112   DCHECK(set_protocol);
113   set_protocol = aw_job_factory->SetProtocolHandler(
114       content::kFileSystemScheme,
115       (*protocol_handlers)[content::kFileSystemScheme].release());
116   DCHECK(set_protocol);
117   set_protocol = aw_job_factory->SetProtocolHandler(
118       content::kChromeUIScheme,
119       (*protocol_handlers)[content::kChromeUIScheme].release());
120   DCHECK(set_protocol);
121   set_protocol = aw_job_factory->SetProtocolHandler(
122       content::kChromeDevToolsScheme,
123       (*protocol_handlers)[content::kChromeDevToolsScheme].release());
124   DCHECK(set_protocol);
125   protocol_handlers->clear();
126
127   // Create a chain of URLRequestJobFactories. The handlers will be invoked
128   // in the order in which they appear in the protocol_handlers vector.
129   typedef std::vector<net::URLRequestJobFactory::ProtocolHandler*>
130       ProtocolHandlerVector;
131   ProtocolHandlerVector protocol_interceptors;
132
133   // Note that even though the content:// scheme handler is created here,
134   // it cannot be used by child processes until access to it is granted via
135   // ChildProcessSecurityPolicy::GrantScheme(). This is done in
136   // AwContentBrowserClient.
137   protocol_interceptors.push_back(
138       CreateAndroidContentProtocolHandler().release());
139   protocol_interceptors.push_back(
140       CreateAndroidAssetFileProtocolHandler().release());
141   // The AwRequestInterceptor must come after the content and asset file job
142   // factories. This for WebViewClassic compatibility where it was not
143   // possible to intercept resource loads to resolvable content:// and
144   // file:// URIs.
145   // This logical dependency is also the reason why the Content
146   // ProtocolHandler has to be added as a ProtocolInterceptJobFactory rather
147   // than via SetProtocolHandler.
148   protocol_interceptors.push_back(new AwRequestInterceptor());
149
150   // The chain of responsibility will execute the handlers in reverse to the
151   // order in which the elements of the chain are created.
152   scoped_ptr<net::URLRequestJobFactory> job_factory(aw_job_factory.Pass());
153   for (ProtocolHandlerVector::reverse_iterator
154            i = protocol_interceptors.rbegin();
155        i != protocol_interceptors.rend();
156        ++i) {
157     job_factory.reset(new net::ProtocolInterceptJobFactory(
158         job_factory.Pass(), make_scoped_ptr(*i)));
159   }
160
161   return job_factory.Pass();
162 }
163
164 }  // namespace
165
166 AwURLRequestContextGetter::AwURLRequestContextGetter(
167     const base::FilePath& partition_path, net::CookieStore* cookie_store)
168     : partition_path_(partition_path),
169       cookie_store_(cookie_store),
170       proxy_config_service_(new DataReductionProxyConfigService(
171           scoped_ptr<net::ProxyConfigService>(
172               net::ProxyService::CreateSystemProxyConfigService(
173                   GetNetworkTaskRunner(),
174                   NULL /* Ignored on Android */)).Pass())) {
175   // CreateSystemProxyConfigService for Android must be called on main thread.
176   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
177 }
178
179 AwURLRequestContextGetter::~AwURLRequestContextGetter() {
180 }
181
182 void AwURLRequestContextGetter::InitializeURLRequestContext() {
183   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
184   DCHECK(!url_request_context_);
185
186   net::URLRequestContextBuilder builder;
187   builder.set_user_agent(GetUserAgent());
188   builder.set_network_delegate(new AwNetworkDelegate());
189 #if !defined(DISABLE_FTP_SUPPORT)
190   builder.set_ftp_enabled(false);  // Android WebView does not support ftp yet.
191 #endif
192   builder.set_proxy_config_service(proxy_config_service_.release());
193   builder.set_accept_language(net::HttpUtil::GenerateAcceptLanguageHeader(
194       AwContentBrowserClient::GetAcceptLangsImpl()));
195   ApplyCmdlineOverridesToURLRequestContextBuilder(&builder);
196
197
198   builder.add_http_auth_handler_factory(
199       data_reduction_proxy::HttpAuthHandlerDataReductionProxy::Scheme(),
200       new data_reduction_proxy::HttpAuthHandlerDataReductionProxy::Factory(
201           DataReductionProxySettings::GetDataReductionProxies()));
202
203   url_request_context_.reset(builder.Build());
204   // TODO(mnaganov): Fix URLRequestContextBuilder to use proper threads.
205   net::HttpNetworkSession::Params network_session_params;
206
207   PopulateNetworkSessionParams(url_request_context_.get(),
208                                &network_session_params);
209
210   net::HttpCache* main_cache = new net::HttpCache(
211       network_session_params,
212       new net::HttpCache::DefaultBackend(
213           net::DISK_CACHE,
214           net::CACHE_BACKEND_SIMPLE,
215           partition_path_.Append(FILE_PATH_LITERAL("Cache")),
216           20 * 1024 * 1024,  // 20M
217           BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)));
218
219   AwBrowserContext* browser_context = AwBrowserContext::GetDefault();
220   DCHECK(browser_context);
221   DataReductionProxySettings* drp_settings =
222       browser_context->GetDataReductionProxySettings();
223   DCHECK(drp_settings);
224   std::string drp_key = drp_settings->key();
225   // Only precache credentials if a key is available at URLRequestContext
226   // initialization.
227   if (!drp_key.empty()) {
228   DataReductionProxySettings::InitDataReductionProxySession(
229       main_cache->GetSession(), drp_settings->key());
230   }
231
232   main_http_factory_.reset(main_cache);
233   url_request_context_->set_http_transaction_factory(main_cache);
234   url_request_context_->set_cookie_store(cookie_store_);
235
236   job_factory_ = CreateJobFactory(&protocol_handlers_);
237   url_request_context_->set_job_factory(job_factory_.get());
238
239   // TODO(sgurun) remove once crbug.com/329681 is fixed. Should be
240   // called only once.
241   net::HttpStreamFactory::EnableNpnSpdy31();
242 }
243
244 net::URLRequestContext* AwURLRequestContextGetter::GetURLRequestContext() {
245   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
246   if (!url_request_context_)
247     InitializeURLRequestContext();
248
249   return url_request_context_.get();
250 }
251
252 scoped_refptr<base::SingleThreadTaskRunner>
253 AwURLRequestContextGetter::GetNetworkTaskRunner() const {
254   return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
255 }
256
257 void AwURLRequestContextGetter::SetProtocolHandlers(
258     content::ProtocolHandlerMap* protocol_handlers) {
259   std::swap(protocol_handlers_, *protocol_handlers);
260 }
261
262 DataReductionProxyConfigService*
263 AwURLRequestContextGetter::proxy_config_service() {
264   // TODO(bengr): return system config if data reduction proxy is disabled.
265   return proxy_config_service_.get();
266 }
267
268 }  // namespace android_webview