1 // Copyright 2014 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.
5 #include "components/cronet/android/url_request_context_adapter.h"
10 #include "base/files/file_util.h"
11 #include "base/files/scoped_file.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/single_thread_task_runner.h"
14 #include "components/cronet/url_request_context_config.h"
15 #include "net/android/network_change_notifier_factory_android.h"
16 #include "net/base/net_errors.h"
17 #include "net/base/net_util.h"
18 #include "net/base/network_change_notifier.h"
19 #include "net/base/network_delegate_impl.h"
20 #include "net/cert/cert_verifier.h"
21 #include "net/http/http_auth_handler_factory.h"
22 #include "net/http/http_network_layer.h"
23 #include "net/http/http_server_properties.h"
24 #include "net/log/net_log_logger.h"
25 #include "net/proxy/proxy_service.h"
26 #include "net/ssl/ssl_config_service_defaults.h"
27 #include "net/url_request/static_http_user_agent_settings.h"
28 #include "net/url_request/url_request_context_builder.h"
29 #include "net/url_request/url_request_context_storage.h"
30 #include "net/url_request/url_request_job_factory_impl.h"
34 class BasicNetworkDelegate
: public net::NetworkDelegateImpl
{
36 BasicNetworkDelegate() {}
37 ~BasicNetworkDelegate() override
{}
40 // net::NetworkDelegate implementation.
41 int OnBeforeURLRequest(net::URLRequest
* request
,
42 const net::CompletionCallback
& callback
,
43 GURL
* new_url
) override
{
47 int OnBeforeSendHeaders(net::URLRequest
* request
,
48 const net::CompletionCallback
& callback
,
49 net::HttpRequestHeaders
* headers
) override
{
53 void OnSendHeaders(net::URLRequest
* request
,
54 const net::HttpRequestHeaders
& headers
) override
{}
56 int OnHeadersReceived(
57 net::URLRequest
* request
,
58 const net::CompletionCallback
& callback
,
59 const net::HttpResponseHeaders
* original_response_headers
,
60 scoped_refptr
<net::HttpResponseHeaders
>* _response_headers
,
61 GURL
* allowed_unsafe_redirect_url
) override
{
65 void OnBeforeRedirect(net::URLRequest
* request
,
66 const GURL
& new_location
) override
{}
68 void OnResponseStarted(net::URLRequest
* request
) override
{}
70 void OnRawBytesRead(const net::URLRequest
& request
,
71 int bytes_read
) override
{}
73 void OnCompleted(net::URLRequest
* request
, bool started
) override
{}
75 void OnURLRequestDestroyed(net::URLRequest
* request
) override
{}
77 void OnPACScriptError(int line_number
,
78 const base::string16
& error
) override
{}
80 NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
81 net::URLRequest
* request
,
82 const net::AuthChallengeInfo
& auth_info
,
83 const AuthCallback
& callback
,
84 net::AuthCredentials
* credentials
) override
{
85 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION
;
88 bool OnCanGetCookies(const net::URLRequest
& request
,
89 const net::CookieList
& cookie_list
) override
{
93 bool OnCanSetCookie(const net::URLRequest
& request
,
94 const std::string
& cookie_line
,
95 net::CookieOptions
* options
) override
{
99 bool OnCanAccessFile(const net::URLRequest
& request
,
100 const base::FilePath
& path
) const override
{
104 bool OnCanThrottleRequest(
105 const net::URLRequest
& request
) const override
{
109 DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate
);
116 URLRequestContextAdapter::URLRequestContextAdapter(
117 URLRequestContextAdapterDelegate
* delegate
,
118 std::string user_agent
)
119 : load_disable_cache_(true),
120 is_context_initialized_(false) {
121 delegate_
= delegate
;
122 user_agent_
= user_agent
;
125 void URLRequestContextAdapter::Initialize(
126 scoped_ptr
<URLRequestContextConfig
> config
) {
127 network_thread_
= new base::Thread("network");
128 base::Thread::Options options
;
129 options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
130 network_thread_
->StartWithOptions(options
);
131 config_
= config
.Pass();
134 void URLRequestContextAdapter::InitRequestContextOnMainThread() {
135 proxy_config_service_
.reset(net::ProxyService::CreateSystemProxyConfigService(
136 GetNetworkTaskRunner(), NULL
));
137 GetNetworkTaskRunner()->PostTask(
139 base::Bind(&URLRequestContextAdapter::InitRequestContextOnNetworkThread
,
143 void URLRequestContextAdapter::InitRequestContextOnNetworkThread() {
144 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
146 // TODO(mmenke): Add method to have the builder enable SPDY.
147 net::URLRequestContextBuilder context_builder
;
148 context_builder
.set_network_delegate(new BasicNetworkDelegate());
149 context_builder
.set_proxy_config_service(proxy_config_service_
.get());
150 config_
->ConfigureURLRequestContextBuilder(&context_builder
);
152 context_
.reset(context_builder
.Build());
154 // Currently (circa M39) enabling QUIC requires setting probability threshold.
155 if (config_
->enable_quic
) {
156 context_
->http_server_properties()
157 ->SetAlternateProtocolProbabilityThreshold(0.0f
);
158 for (size_t hint
= 0; hint
< config_
->quic_hints
.size(); ++hint
) {
159 const URLRequestContextConfig::QuicHint
& quic_hint
=
160 *config_
->quic_hints
[hint
];
161 if (quic_hint
.host
.empty()) {
162 LOG(ERROR
) << "Empty QUIC hint host: " << quic_hint
.host
;
166 url::CanonHostInfo host_info
;
167 std::string
canon_host(net::CanonicalizeHost(quic_hint
.host
, &host_info
));
168 if (!host_info
.IsIPAddress() &&
169 !net::IsCanonicalizedHostCompliant(canon_host
)) {
170 LOG(ERROR
) << "Invalid QUIC hint host: " << quic_hint
.host
;
174 if (quic_hint
.port
<= std::numeric_limits
<uint16
>::min() ||
175 quic_hint
.port
> std::numeric_limits
<uint16
>::max()) {
176 LOG(ERROR
) << "Invalid QUIC hint port: "
181 if (quic_hint
.alternate_port
<= std::numeric_limits
<uint16
>::min() ||
182 quic_hint
.alternate_port
> std::numeric_limits
<uint16
>::max()) {
183 LOG(ERROR
) << "Invalid QUIC hint alternate port: "
184 << quic_hint
.alternate_port
;
188 net::HostPortPair
quic_hint_host_port_pair(canon_host
,
190 net::AlternativeService
alternative_service(
191 net::AlternateProtocol::QUIC
, "",
192 static_cast<uint16
>(quic_hint
.alternate_port
));
193 context_
->http_server_properties()->SetAlternativeService(
194 quic_hint_host_port_pair
, alternative_service
, 1.0f
);
197 load_disable_cache_
= config_
->load_disable_cache
;
201 net_log_observer_
.reset(new NetLogObserver());
202 context_
->net_log()->DeprecatedAddObserver(net_log_observer_
.get(),
203 net::NetLog::LOG_ALL_BUT_BYTES
);
206 is_context_initialized_
= true;
207 while (!tasks_waiting_for_context_
.empty()) {
208 tasks_waiting_for_context_
.front().Run();
209 tasks_waiting_for_context_
.pop();
212 delegate_
->OnContextInitialized(this);
215 void URLRequestContextAdapter::PostTaskToNetworkThread(
216 const tracked_objects::Location
& posted_from
,
217 const RunAfterContextInitTask
& callback
) {
218 GetNetworkTaskRunner()->PostTask(
221 &URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread
,
226 void URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread(
227 const RunAfterContextInitTask
& callback
) {
228 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
229 if (is_context_initialized_
) {
233 tasks_waiting_for_context_
.push(callback
);
236 URLRequestContextAdapter::~URLRequestContextAdapter() {
237 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
238 if (net_log_observer_
) {
239 context_
->net_log()->DeprecatedRemoveObserver(net_log_observer_
.get());
240 net_log_observer_
.reset();
243 // TODO(mef): Ensure that |network_thread_| is destroyed properly.
246 const std::string
& URLRequestContextAdapter::GetUserAgent(
247 const GURL
& url
) const {
251 net::URLRequestContext
* URLRequestContextAdapter::GetURLRequestContext() {
252 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
254 LOG(ERROR
) << "URLRequestContext is not set up";
256 return context_
.get();
259 scoped_refptr
<base::SingleThreadTaskRunner
>
260 URLRequestContextAdapter::GetNetworkTaskRunner() const {
261 return network_thread_
->message_loop_proxy();
264 void URLRequestContextAdapter::StartNetLogToFile(const std::string
& file_name
) {
265 PostTaskToNetworkThread(
268 &URLRequestContextAdapter::StartNetLogToFileHelper
, this, file_name
));
271 void URLRequestContextAdapter::StopNetLog() {
272 PostTaskToNetworkThread(
273 FROM_HERE
, base::Bind(&URLRequestContextAdapter::StopNetLogHelper
, this));
276 void URLRequestContextAdapter::StartNetLogToFileHelper(
277 const std::string
& file_name
) {
278 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
279 // Do nothing if already logging to a file.
283 base::FilePath
file_path(file_name
);
284 base::ScopedFILE
file(base::OpenFile(file_path
, "w"));
288 net_log_logger_
.reset(new net::NetLogLogger());
289 net_log_logger_
->StartObserving(context_
->net_log(), file
.Pass(), nullptr,
293 void URLRequestContextAdapter::StopNetLogHelper() {
294 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
295 if (net_log_logger_
) {
296 net_log_logger_
->StopObserving(context_
.get());
297 net_log_logger_
.reset();
301 void NetLogObserver::OnAddEntry(const net::NetLog::Entry
& entry
) {
302 VLOG(2) << "Net log entry: type=" << entry
.type()
303 << ", source=" << entry
.source().type
<< ", phase=" << entry
.phase();
306 } // namespace cronet