Revert of Refactor the avatar button/icon class (patchset #14 id:320001 of https...
[chromium-blink-merge.git] / components / cronet / android / url_request_context_adapter.cc
blobfd262c2ca6bac34b9480ddf32caf266818e5af58
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 "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/write_to_file_net_log_observer.h"
25 #include "net/proxy/proxy_service.h"
26 #include "net/sdch/sdch_owner.h"
27 #include "net/ssl/ssl_config_service_defaults.h"
28 #include "net/url_request/static_http_user_agent_settings.h"
29 #include "net/url_request/url_request_context_builder.h"
30 #include "net/url_request/url_request_context_storage.h"
31 #include "net/url_request/url_request_job_factory_impl.h"
33 namespace {
35 class BasicNetworkDelegate : public net::NetworkDelegateImpl {
36 public:
37 BasicNetworkDelegate() {}
38 ~BasicNetworkDelegate() override {}
40 private:
41 // net::NetworkDelegate implementation.
42 int OnBeforeURLRequest(net::URLRequest* request,
43 const net::CompletionCallback& callback,
44 GURL* new_url) override {
45 return net::OK;
48 int OnBeforeSendHeaders(net::URLRequest* request,
49 const net::CompletionCallback& callback,
50 net::HttpRequestHeaders* headers) override {
51 return net::OK;
54 void OnSendHeaders(net::URLRequest* request,
55 const net::HttpRequestHeaders& headers) override {}
57 int OnHeadersReceived(
58 net::URLRequest* request,
59 const net::CompletionCallback& callback,
60 const net::HttpResponseHeaders* original_response_headers,
61 scoped_refptr<net::HttpResponseHeaders>* _response_headers,
62 GURL* allowed_unsafe_redirect_url) override {
63 return net::OK;
66 void OnBeforeRedirect(net::URLRequest* request,
67 const GURL& new_location) override {}
69 void OnResponseStarted(net::URLRequest* request) override {}
71 void OnRawBytesRead(const net::URLRequest& request,
72 int bytes_read) override {}
74 void OnCompleted(net::URLRequest* request, bool started) override {}
76 void OnURLRequestDestroyed(net::URLRequest* request) override {}
78 void OnPACScriptError(int line_number,
79 const base::string16& error) override {}
81 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
82 net::URLRequest* request,
83 const net::AuthChallengeInfo& auth_info,
84 const AuthCallback& callback,
85 net::AuthCredentials* credentials) override {
86 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
89 bool OnCanGetCookies(const net::URLRequest& request,
90 const net::CookieList& cookie_list) override {
91 return false;
94 bool OnCanSetCookie(const net::URLRequest& request,
95 const std::string& cookie_line,
96 net::CookieOptions* options) override {
97 return false;
100 bool OnCanAccessFile(const net::URLRequest& request,
101 const base::FilePath& path) const override {
102 return false;
105 bool OnCanThrottleRequest(
106 const net::URLRequest& request) const override {
107 return false;
110 DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate);
113 } // namespace
115 namespace cronet {
117 URLRequestContextAdapter::URLRequestContextAdapter(
118 URLRequestContextAdapterDelegate* delegate,
119 std::string user_agent)
120 : load_disable_cache_(true),
121 is_context_initialized_(false) {
122 delegate_ = delegate;
123 user_agent_ = user_agent;
126 void URLRequestContextAdapter::Initialize(
127 scoped_ptr<URLRequestContextConfig> config) {
128 network_thread_ = new base::Thread("network");
129 base::Thread::Options options;
130 options.message_loop_type = base::MessageLoop::TYPE_IO;
131 network_thread_->StartWithOptions(options);
132 config_ = config.Pass();
135 void URLRequestContextAdapter::InitRequestContextOnMainThread() {
136 proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
137 GetNetworkTaskRunner(), NULL));
138 GetNetworkTaskRunner()->PostTask(
139 FROM_HERE,
140 base::Bind(&URLRequestContextAdapter::InitRequestContextOnNetworkThread,
141 this));
144 void URLRequestContextAdapter::InitRequestContextOnNetworkThread() {
145 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
146 DCHECK(config_);
147 // TODO(mmenke): Add method to have the builder enable SPDY.
148 net::URLRequestContextBuilder context_builder;
149 context_builder.set_network_delegate(new BasicNetworkDelegate());
150 context_builder.set_proxy_config_service(proxy_config_service_.get());
151 config_->ConfigureURLRequestContextBuilder(&context_builder);
153 context_.reset(context_builder.Build());
155 if (config_->enable_sdch) {
156 DCHECK(context_->sdch_manager());
157 sdch_owner_.reset(
158 new net::SdchOwner(context_->sdch_manager(), context_.get()));
161 // Currently (circa M39) enabling QUIC requires setting probability threshold.
162 if (config_->enable_quic) {
163 context_->http_server_properties()
164 ->SetAlternativeServiceProbabilityThreshold(0.0f);
165 for (size_t hint = 0; hint < config_->quic_hints.size(); ++hint) {
166 const URLRequestContextConfig::QuicHint& quic_hint =
167 *config_->quic_hints[hint];
168 if (quic_hint.host.empty()) {
169 LOG(ERROR) << "Empty QUIC hint host: " << quic_hint.host;
170 continue;
173 url::CanonHostInfo host_info;
174 std::string canon_host(net::CanonicalizeHost(quic_hint.host, &host_info));
175 if (!host_info.IsIPAddress() &&
176 !net::IsCanonicalizedHostCompliant(canon_host)) {
177 LOG(ERROR) << "Invalid QUIC hint host: " << quic_hint.host;
178 continue;
181 if (quic_hint.port <= std::numeric_limits<uint16>::min() ||
182 quic_hint.port > std::numeric_limits<uint16>::max()) {
183 LOG(ERROR) << "Invalid QUIC hint port: "
184 << quic_hint.port;
185 continue;
188 if (quic_hint.alternate_port <= std::numeric_limits<uint16>::min() ||
189 quic_hint.alternate_port > std::numeric_limits<uint16>::max()) {
190 LOG(ERROR) << "Invalid QUIC hint alternate port: "
191 << quic_hint.alternate_port;
192 continue;
195 net::HostPortPair quic_hint_host_port_pair(canon_host,
196 quic_hint.port);
197 net::AlternativeService alternative_service(
198 net::AlternateProtocol::QUIC, "",
199 static_cast<uint16>(quic_hint.alternate_port));
200 context_->http_server_properties()->SetAlternativeService(
201 quic_hint_host_port_pair, alternative_service, 1.0f);
204 load_disable_cache_ = config_->load_disable_cache;
205 config_.reset(NULL);
207 if (VLOG_IS_ON(2)) {
208 net_log_observer_.reset(new NetLogObserver());
209 context_->net_log()->DeprecatedAddObserver(
210 net_log_observer_.get(),
211 net::NetLogCaptureMode::IncludeCookiesAndCredentials());
214 is_context_initialized_ = true;
215 while (!tasks_waiting_for_context_.empty()) {
216 tasks_waiting_for_context_.front().Run();
217 tasks_waiting_for_context_.pop();
220 delegate_->OnContextInitialized(this);
223 void URLRequestContextAdapter::PostTaskToNetworkThread(
224 const tracked_objects::Location& posted_from,
225 const RunAfterContextInitTask& callback) {
226 GetNetworkTaskRunner()->PostTask(
227 posted_from,
228 base::Bind(
229 &URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread,
230 this,
231 callback));
234 void URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread(
235 const RunAfterContextInitTask& callback) {
236 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
237 if (is_context_initialized_) {
238 callback.Run();
239 return;
241 tasks_waiting_for_context_.push(callback);
244 URLRequestContextAdapter::~URLRequestContextAdapter() {
245 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
246 if (net_log_observer_) {
247 context_->net_log()->DeprecatedRemoveObserver(net_log_observer_.get());
248 net_log_observer_.reset();
250 StopNetLogHelper();
251 // TODO(mef): Ensure that |network_thread_| is destroyed properly.
254 const std::string& URLRequestContextAdapter::GetUserAgent(
255 const GURL& url) const {
256 return user_agent_;
259 net::URLRequestContext* URLRequestContextAdapter::GetURLRequestContext() {
260 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
261 if (!context_) {
262 LOG(ERROR) << "URLRequestContext is not set up";
264 return context_.get();
267 scoped_refptr<base::SingleThreadTaskRunner>
268 URLRequestContextAdapter::GetNetworkTaskRunner() const {
269 return network_thread_->message_loop_proxy();
272 void URLRequestContextAdapter::StartNetLogToFile(const std::string& file_name,
273 bool log_all) {
274 PostTaskToNetworkThread(
275 FROM_HERE,
276 base::Bind(&URLRequestContextAdapter::StartNetLogToFileHelper, this,
277 file_name, log_all));
280 void URLRequestContextAdapter::StopNetLog() {
281 PostTaskToNetworkThread(
282 FROM_HERE, base::Bind(&URLRequestContextAdapter::StopNetLogHelper, this));
285 void URLRequestContextAdapter::StartNetLogToFileHelper(
286 const std::string& file_name, bool log_all) {
287 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
288 // Do nothing if already logging to a file.
289 if (write_to_file_observer_)
290 return;
292 base::FilePath file_path(file_name);
293 base::ScopedFILE file(base::OpenFile(file_path, "w"));
294 if (!file)
295 return;
297 write_to_file_observer_.reset(new net::WriteToFileNetLogObserver());
298 if (log_all) {
299 write_to_file_observer_->set_capture_mode(
300 net::NetLogCaptureMode::IncludeSocketBytes());
302 write_to_file_observer_->StartObserving(context_->net_log(), file.Pass(),
303 nullptr, context_.get());
306 void URLRequestContextAdapter::StopNetLogHelper() {
307 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
308 if (write_to_file_observer_) {
309 write_to_file_observer_->StopObserving(context_.get());
310 write_to_file_observer_.reset();
314 void NetLogObserver::OnAddEntry(const net::NetLog::Entry& entry) {
315 VLOG(2) << "Net log entry: type=" << entry.type()
316 << ", source=" << entry.source().type << ", phase=" << entry.phase();
319 } // namespace cronet