Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / cronet / android / url_request_context_adapter.cc
blob29a9456fc23383d8d0a8637c2ffc97feb3836978
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"
7 #include <limits>
9 #include "base/bind.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"
34 namespace {
36 class BasicNetworkDelegate : public net::NetworkDelegateImpl {
37 public:
38 BasicNetworkDelegate() {}
39 ~BasicNetworkDelegate() override {}
41 private:
42 // net::NetworkDelegate implementation.
43 int OnBeforeURLRequest(net::URLRequest* request,
44 const net::CompletionCallback& callback,
45 GURL* new_url) override {
46 return net::OK;
49 int OnBeforeSendHeaders(net::URLRequest* request,
50 const net::CompletionCallback& callback,
51 net::HttpRequestHeaders* headers) override {
52 return net::OK;
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 {
64 return net::OK;
67 void OnBeforeRedirect(net::URLRequest* request,
68 const GURL& new_location) override {}
70 void OnResponseStarted(net::URLRequest* request) override {}
72 void OnCompleted(net::URLRequest* request, bool started) override {}
74 void OnURLRequestDestroyed(net::URLRequest* request) override {}
76 void OnPACScriptError(int line_number,
77 const base::string16& error) override {}
79 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
80 net::URLRequest* request,
81 const net::AuthChallengeInfo& auth_info,
82 const AuthCallback& callback,
83 net::AuthCredentials* credentials) override {
84 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
87 bool OnCanGetCookies(const net::URLRequest& request,
88 const net::CookieList& cookie_list) override {
89 return false;
92 bool OnCanSetCookie(const net::URLRequest& request,
93 const std::string& cookie_line,
94 net::CookieOptions* options) override {
95 return false;
98 bool OnCanAccessFile(const net::URLRequest& request,
99 const base::FilePath& path) const override {
100 return false;
103 DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate);
106 } // namespace
108 namespace cronet {
110 URLRequestContextAdapter::URLRequestContextAdapter(
111 URLRequestContextAdapterDelegate* delegate,
112 std::string user_agent)
113 : load_disable_cache_(true),
114 is_context_initialized_(false) {
115 delegate_ = delegate;
116 user_agent_ = user_agent;
119 void URLRequestContextAdapter::Initialize(
120 scoped_ptr<URLRequestContextConfig> config) {
121 network_thread_ = new base::Thread("network");
122 base::Thread::Options options;
123 options.message_loop_type = base::MessageLoop::TYPE_IO;
124 network_thread_->StartWithOptions(options);
125 config_ = config.Pass();
128 void URLRequestContextAdapter::InitRequestContextOnMainThread() {
129 proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
130 GetNetworkTaskRunner(), NULL));
131 GetNetworkTaskRunner()->PostTask(
132 FROM_HERE,
133 base::Bind(&URLRequestContextAdapter::InitRequestContextOnNetworkThread,
134 this));
137 void URLRequestContextAdapter::InitRequestContextOnNetworkThread() {
138 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
139 DCHECK(config_);
140 // TODO(mmenke): Add method to have the builder enable SPDY.
141 net::URLRequestContextBuilder context_builder;
142 context_builder.set_network_delegate(
143 make_scoped_ptr(new BasicNetworkDelegate()));
144 context_builder.set_proxy_config_service(proxy_config_service_.Pass());
145 config_->ConfigureURLRequestContextBuilder(&context_builder);
147 context_ = context_builder.Build().Pass();
149 if (config_->enable_sdch) {
150 DCHECK(context_->sdch_manager());
151 sdch_owner_.reset(
152 new net::SdchOwner(context_->sdch_manager(), context_.get()));
155 // Currently (circa M39) enabling QUIC requires setting probability threshold.
156 if (config_->enable_quic) {
157 context_->http_server_properties()
158 ->SetAlternativeServiceProbabilityThreshold(0.0f);
159 for (size_t hint = 0; hint < config_->quic_hints.size(); ++hint) {
160 const URLRequestContextConfig::QuicHint& quic_hint =
161 *config_->quic_hints[hint];
162 if (quic_hint.host.empty()) {
163 LOG(ERROR) << "Empty QUIC hint host: " << quic_hint.host;
164 continue;
167 url::CanonHostInfo host_info;
168 std::string canon_host(net::CanonicalizeHost(quic_hint.host, &host_info));
169 if (!host_info.IsIPAddress() &&
170 !net::IsCanonicalizedHostCompliant(canon_host)) {
171 LOG(ERROR) << "Invalid QUIC hint host: " << quic_hint.host;
172 continue;
175 if (quic_hint.port <= std::numeric_limits<uint16>::min() ||
176 quic_hint.port > std::numeric_limits<uint16>::max()) {
177 LOG(ERROR) << "Invalid QUIC hint port: "
178 << quic_hint.port;
179 continue;
182 if (quic_hint.alternate_port <= std::numeric_limits<uint16>::min() ||
183 quic_hint.alternate_port > std::numeric_limits<uint16>::max()) {
184 LOG(ERROR) << "Invalid QUIC hint alternate port: "
185 << quic_hint.alternate_port;
186 continue;
189 net::HostPortPair quic_hint_host_port_pair(canon_host,
190 quic_hint.port);
191 net::AlternativeService alternative_service(
192 net::AlternateProtocol::QUIC, "",
193 static_cast<uint16>(quic_hint.alternate_port));
194 context_->http_server_properties()->SetAlternativeService(
195 quic_hint_host_port_pair, alternative_service, 1.0f,
196 base::Time::Max());
199 load_disable_cache_ = config_->load_disable_cache;
200 config_.reset(NULL);
202 if (VLOG_IS_ON(2)) {
203 net_log_observer_.reset(new NetLogObserver());
204 context_->net_log()->DeprecatedAddObserver(
205 net_log_observer_.get(),
206 net::NetLogCaptureMode::IncludeCookiesAndCredentials());
209 is_context_initialized_ = true;
210 while (!tasks_waiting_for_context_.empty()) {
211 tasks_waiting_for_context_.front().Run();
212 tasks_waiting_for_context_.pop();
215 delegate_->OnContextInitialized(this);
218 void URLRequestContextAdapter::PostTaskToNetworkThread(
219 const tracked_objects::Location& posted_from,
220 const RunAfterContextInitTask& callback) {
221 GetNetworkTaskRunner()->PostTask(
222 posted_from,
223 base::Bind(
224 &URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread,
225 this,
226 callback));
229 void URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread(
230 const RunAfterContextInitTask& callback) {
231 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
232 if (is_context_initialized_) {
233 callback.Run();
234 return;
236 tasks_waiting_for_context_.push(callback);
239 URLRequestContextAdapter::~URLRequestContextAdapter() {
240 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
241 if (net_log_observer_) {
242 context_->net_log()->DeprecatedRemoveObserver(net_log_observer_.get());
243 net_log_observer_.reset();
245 StopNetLogHelper();
246 // TODO(mef): Ensure that |network_thread_| is destroyed properly.
249 const std::string& URLRequestContextAdapter::GetUserAgent(
250 const GURL& url) const {
251 return user_agent_;
254 net::URLRequestContext* URLRequestContextAdapter::GetURLRequestContext() {
255 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
256 if (!context_) {
257 LOG(ERROR) << "URLRequestContext is not set up";
259 return context_.get();
262 scoped_refptr<base::SingleThreadTaskRunner>
263 URLRequestContextAdapter::GetNetworkTaskRunner() const {
264 return network_thread_->task_runner();
267 void URLRequestContextAdapter::StartNetLogToFile(const std::string& file_name,
268 bool log_all) {
269 PostTaskToNetworkThread(
270 FROM_HERE,
271 base::Bind(&URLRequestContextAdapter::StartNetLogToFileHelper, this,
272 file_name, log_all));
275 void URLRequestContextAdapter::StopNetLog() {
276 PostTaskToNetworkThread(
277 FROM_HERE, base::Bind(&URLRequestContextAdapter::StopNetLogHelper, this));
280 void URLRequestContextAdapter::StartNetLogToFileHelper(
281 const std::string& file_name, bool log_all) {
282 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
283 // Do nothing if already logging to a file.
284 if (write_to_file_observer_)
285 return;
287 base::FilePath file_path(file_name);
288 base::ScopedFILE file(base::OpenFile(file_path, "w"));
289 if (!file)
290 return;
292 write_to_file_observer_.reset(new net::WriteToFileNetLogObserver());
293 if (log_all) {
294 write_to_file_observer_->set_capture_mode(
295 net::NetLogCaptureMode::IncludeSocketBytes());
297 write_to_file_observer_->StartObserving(context_->net_log(), file.Pass(),
298 nullptr, context_.get());
301 void URLRequestContextAdapter::StopNetLogHelper() {
302 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
303 if (write_to_file_observer_) {
304 write_to_file_observer_->StopObserving(context_.get());
305 write_to_file_observer_.reset();
309 void NetLogObserver::OnAddEntry(const net::NetLog::Entry& entry) {
310 VLOG(2) << "Net log entry: type=" << entry.type()
311 << ", source=" << entry.source().type << ", phase=" << entry.phase();
314 } // namespace cronet