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 "base/time/time.h"
15 #include "components/cronet/url_request_context_config.h"
16 #include "net/android/network_change_notifier_factory_android.h"
17 #include "net/base/net_errors.h"
18 #include "net/base/net_util.h"
19 #include "net/base/network_change_notifier.h"
20 #include "net/base/network_delegate_impl.h"
21 #include "net/cert/cert_verifier.h"
22 #include "net/http/http_auth_handler_factory.h"
23 #include "net/http/http_network_layer.h"
24 #include "net/http/http_server_properties.h"
25 #include "net/log/write_to_file_net_log_observer.h"
26 #include "net/proxy/proxy_service.h"
27 #include "net/sdch/sdch_owner.h"
28 #include "net/ssl/ssl_config_service_defaults.h"
29 #include "net/url_request/static_http_user_agent_settings.h"
30 #include "net/url_request/url_request_context_builder.h"
31 #include "net/url_request/url_request_context_storage.h"
32 #include "net/url_request/url_request_job_factory_impl.h"
36 class BasicNetworkDelegate
: public net::NetworkDelegateImpl
{
38 BasicNetworkDelegate() {}
39 ~BasicNetworkDelegate() override
{}
42 // net::NetworkDelegate implementation.
43 int OnBeforeURLRequest(net::URLRequest
* request
,
44 const net::CompletionCallback
& callback
,
45 GURL
* new_url
) override
{
49 int OnBeforeSendHeaders(net::URLRequest
* request
,
50 const net::CompletionCallback
& callback
,
51 net::HttpRequestHeaders
* headers
) override
{
55 void OnSendHeaders(net::URLRequest
* request
,
56 const net::HttpRequestHeaders
& headers
) override
{}
58 int OnHeadersReceived(
59 net::URLRequest
* request
,
60 const net::CompletionCallback
& callback
,
61 const net::HttpResponseHeaders
* original_response_headers
,
62 scoped_refptr
<net::HttpResponseHeaders
>* _response_headers
,
63 GURL
* allowed_unsafe_redirect_url
) override
{
67 void OnBeforeRedirect(net::URLRequest
* request
,
68 const GURL
& new_location
) override
{}
70 void OnResponseStarted(net::URLRequest
* request
) override
{}
72 void OnRawBytesRead(const net::URLRequest
& request
,
73 int bytes_read
) override
{}
75 void OnCompleted(net::URLRequest
* request
, bool started
) override
{}
77 void OnURLRequestDestroyed(net::URLRequest
* request
) override
{}
79 void OnPACScriptError(int line_number
,
80 const base::string16
& error
) override
{}
82 NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
83 net::URLRequest
* request
,
84 const net::AuthChallengeInfo
& auth_info
,
85 const AuthCallback
& callback
,
86 net::AuthCredentials
* credentials
) override
{
87 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION
;
90 bool OnCanGetCookies(const net::URLRequest
& request
,
91 const net::CookieList
& cookie_list
) override
{
95 bool OnCanSetCookie(const net::URLRequest
& request
,
96 const std::string
& cookie_line
,
97 net::CookieOptions
* options
) override
{
101 bool OnCanAccessFile(const net::URLRequest
& request
,
102 const base::FilePath
& path
) const override
{
106 DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate
);
113 URLRequestContextAdapter::URLRequestContextAdapter(
114 URLRequestContextAdapterDelegate
* delegate
,
115 std::string user_agent
)
116 : load_disable_cache_(true),
117 is_context_initialized_(false) {
118 delegate_
= delegate
;
119 user_agent_
= user_agent
;
122 void URLRequestContextAdapter::Initialize(
123 scoped_ptr
<URLRequestContextConfig
> config
) {
124 network_thread_
= new base::Thread("network");
125 base::Thread::Options options
;
126 options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
127 network_thread_
->StartWithOptions(options
);
128 config_
= config
.Pass();
131 void URLRequestContextAdapter::InitRequestContextOnMainThread() {
132 proxy_config_service_
.reset(net::ProxyService::CreateSystemProxyConfigService(
133 GetNetworkTaskRunner(), NULL
));
134 GetNetworkTaskRunner()->PostTask(
136 base::Bind(&URLRequestContextAdapter::InitRequestContextOnNetworkThread
,
140 void URLRequestContextAdapter::InitRequestContextOnNetworkThread() {
141 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
143 // TODO(mmenke): Add method to have the builder enable SPDY.
144 net::URLRequestContextBuilder context_builder
;
145 context_builder
.set_network_delegate(new BasicNetworkDelegate());
146 context_builder
.set_proxy_config_service(proxy_config_service_
.get());
147 config_
->ConfigureURLRequestContextBuilder(&context_builder
);
149 context_
.reset(context_builder
.Build());
151 if (config_
->enable_sdch
) {
152 DCHECK(context_
->sdch_manager());
154 new net::SdchOwner(context_
->sdch_manager(), context_
.get()));
157 // Currently (circa M39) enabling QUIC requires setting probability threshold.
158 if (config_
->enable_quic
) {
159 context_
->http_server_properties()
160 ->SetAlternativeServiceProbabilityThreshold(0.0f
);
161 for (size_t hint
= 0; hint
< config_
->quic_hints
.size(); ++hint
) {
162 const URLRequestContextConfig::QuicHint
& quic_hint
=
163 *config_
->quic_hints
[hint
];
164 if (quic_hint
.host
.empty()) {
165 LOG(ERROR
) << "Empty QUIC hint host: " << quic_hint
.host
;
169 url::CanonHostInfo host_info
;
170 std::string
canon_host(net::CanonicalizeHost(quic_hint
.host
, &host_info
));
171 if (!host_info
.IsIPAddress() &&
172 !net::IsCanonicalizedHostCompliant(canon_host
)) {
173 LOG(ERROR
) << "Invalid QUIC hint host: " << quic_hint
.host
;
177 if (quic_hint
.port
<= std::numeric_limits
<uint16
>::min() ||
178 quic_hint
.port
> std::numeric_limits
<uint16
>::max()) {
179 LOG(ERROR
) << "Invalid QUIC hint port: "
184 if (quic_hint
.alternate_port
<= std::numeric_limits
<uint16
>::min() ||
185 quic_hint
.alternate_port
> std::numeric_limits
<uint16
>::max()) {
186 LOG(ERROR
) << "Invalid QUIC hint alternate port: "
187 << quic_hint
.alternate_port
;
191 net::HostPortPair
quic_hint_host_port_pair(canon_host
,
193 net::AlternativeService
alternative_service(
194 net::AlternateProtocol::QUIC
, "",
195 static_cast<uint16
>(quic_hint
.alternate_port
));
196 context_
->http_server_properties()->SetAlternativeService(
197 quic_hint_host_port_pair
, alternative_service
, 1.0f
,
198 base::Time::Now() + base::TimeDelta::FromDays(1));
201 load_disable_cache_
= config_
->load_disable_cache
;
205 net_log_observer_
.reset(new NetLogObserver());
206 context_
->net_log()->DeprecatedAddObserver(
207 net_log_observer_
.get(),
208 net::NetLogCaptureMode::IncludeCookiesAndCredentials());
211 is_context_initialized_
= true;
212 while (!tasks_waiting_for_context_
.empty()) {
213 tasks_waiting_for_context_
.front().Run();
214 tasks_waiting_for_context_
.pop();
217 delegate_
->OnContextInitialized(this);
220 void URLRequestContextAdapter::PostTaskToNetworkThread(
221 const tracked_objects::Location
& posted_from
,
222 const RunAfterContextInitTask
& callback
) {
223 GetNetworkTaskRunner()->PostTask(
226 &URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread
,
231 void URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread(
232 const RunAfterContextInitTask
& callback
) {
233 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
234 if (is_context_initialized_
) {
238 tasks_waiting_for_context_
.push(callback
);
241 URLRequestContextAdapter::~URLRequestContextAdapter() {
242 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
243 if (net_log_observer_
) {
244 context_
->net_log()->DeprecatedRemoveObserver(net_log_observer_
.get());
245 net_log_observer_
.reset();
248 // TODO(mef): Ensure that |network_thread_| is destroyed properly.
251 const std::string
& URLRequestContextAdapter::GetUserAgent(
252 const GURL
& url
) const {
256 net::URLRequestContext
* URLRequestContextAdapter::GetURLRequestContext() {
257 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
259 LOG(ERROR
) << "URLRequestContext is not set up";
261 return context_
.get();
264 scoped_refptr
<base::SingleThreadTaskRunner
>
265 URLRequestContextAdapter::GetNetworkTaskRunner() const {
266 return network_thread_
->task_runner();
269 void URLRequestContextAdapter::StartNetLogToFile(const std::string
& file_name
,
271 PostTaskToNetworkThread(
273 base::Bind(&URLRequestContextAdapter::StartNetLogToFileHelper
, this,
274 file_name
, log_all
));
277 void URLRequestContextAdapter::StopNetLog() {
278 PostTaskToNetworkThread(
279 FROM_HERE
, base::Bind(&URLRequestContextAdapter::StopNetLogHelper
, this));
282 void URLRequestContextAdapter::StartNetLogToFileHelper(
283 const std::string
& file_name
, bool log_all
) {
284 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
285 // Do nothing if already logging to a file.
286 if (write_to_file_observer_
)
289 base::FilePath
file_path(file_name
);
290 base::ScopedFILE
file(base::OpenFile(file_path
, "w"));
294 write_to_file_observer_
.reset(new net::WriteToFileNetLogObserver());
296 write_to_file_observer_
->set_capture_mode(
297 net::NetLogCaptureMode::IncludeSocketBytes());
299 write_to_file_observer_
->StartObserving(context_
->net_log(), file
.Pass(),
300 nullptr, context_
.get());
303 void URLRequestContextAdapter::StopNetLogHelper() {
304 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
305 if (write_to_file_observer_
) {
306 write_to_file_observer_
->StopObserving(context_
.get());
307 write_to_file_observer_
.reset();
311 void NetLogObserver::OnAddEntry(const net::NetLog::Entry
& entry
) {
312 VLOG(2) << "Net log entry: type=" << entry
.type()
313 << ", source=" << entry
.source().type
<< ", phase=" << entry
.phase();
316 } // namespace cronet