Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / components / cronet / android / url_request_context_adapter.cc
blob9cd612f5f57102ea57ee407b07db7d36483144c7
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/message_loop/message_loop.h"
12 #include "base/single_thread_task_runner.h"
13 #include "components/cronet/url_request_context_config.h"
14 #include "net/android/network_change_notifier_factory_android.h"
15 #include "net/base/net_errors.h"
16 #include "net/base/net_log_logger.h"
17 #include "net/base/net_util.h"
18 #include "net/base/network_change_notifier.h"
19 #include "net/cert/cert_verifier.h"
20 #include "net/http/http_auth_handler_factory.h"
21 #include "net/http/http_network_layer.h"
22 #include "net/http/http_server_properties.h"
23 #include "net/proxy/proxy_service.h"
24 #include "net/ssl/ssl_config_service_defaults.h"
25 #include "net/url_request/static_http_user_agent_settings.h"
26 #include "net/url_request/url_request_context_builder.h"
27 #include "net/url_request/url_request_context_storage.h"
28 #include "net/url_request/url_request_job_factory_impl.h"
30 namespace {
32 // MessageLoop on the main thread, which is where objects that receive Java
33 // notifications generally live.
34 base::MessageLoop* g_main_message_loop = nullptr;
36 net::NetworkChangeNotifier* g_network_change_notifier = nullptr;
38 class BasicNetworkDelegate : public net::NetworkDelegate {
39 public:
40 BasicNetworkDelegate() {}
41 virtual ~BasicNetworkDelegate() {}
43 private:
44 // net::NetworkDelegate implementation.
45 int OnBeforeURLRequest(net::URLRequest* request,
46 const net::CompletionCallback& callback,
47 GURL* new_url) override {
48 return net::OK;
51 int OnBeforeSendHeaders(net::URLRequest* request,
52 const net::CompletionCallback& callback,
53 net::HttpRequestHeaders* headers) override {
54 return net::OK;
57 void OnSendHeaders(net::URLRequest* request,
58 const net::HttpRequestHeaders& headers) override {}
60 int OnHeadersReceived(
61 net::URLRequest* request,
62 const net::CompletionCallback& callback,
63 const net::HttpResponseHeaders* original_response_headers,
64 scoped_refptr<net::HttpResponseHeaders>* _response_headers,
65 GURL* allowed_unsafe_redirect_url) override {
66 return net::OK;
69 void OnBeforeRedirect(net::URLRequest* request,
70 const GURL& new_location) override {}
72 void OnResponseStarted(net::URLRequest* request) override {}
74 void OnRawBytesRead(const net::URLRequest& request,
75 int bytes_read) override {}
77 void OnCompleted(net::URLRequest* request, bool started) override {}
79 void OnURLRequestDestroyed(net::URLRequest* request) override {}
81 void OnPACScriptError(int line_number,
82 const base::string16& error) override {}
84 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
85 net::URLRequest* request,
86 const net::AuthChallengeInfo& auth_info,
87 const AuthCallback& callback,
88 net::AuthCredentials* credentials) override {
89 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
92 bool OnCanGetCookies(const net::URLRequest& request,
93 const net::CookieList& cookie_list) override {
94 return false;
97 bool OnCanSetCookie(const net::URLRequest& request,
98 const std::string& cookie_line,
99 net::CookieOptions* options) override {
100 return false;
103 bool OnCanAccessFile(const net::URLRequest& request,
104 const base::FilePath& path) const override {
105 return false;
108 bool OnCanThrottleRequest(
109 const net::URLRequest& request) const override {
110 return false;
113 DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate);
116 } // namespace
118 namespace cronet {
120 URLRequestContextAdapter::URLRequestContextAdapter(
121 URLRequestContextAdapterDelegate* delegate,
122 std::string user_agent) {
123 delegate_ = delegate;
124 user_agent_ = user_agent;
127 void URLRequestContextAdapter::Initialize(
128 scoped_ptr<URLRequestContextConfig> config) {
129 network_thread_ = new base::Thread("network");
130 base::Thread::Options options;
131 options.message_loop_type = base::MessageLoop::TYPE_IO;
132 network_thread_->StartWithOptions(options);
133 config_ = config.Pass();
136 void URLRequestContextAdapter::InitRequestContextOnMainThread() {
137 if (!base::MessageLoop::current()) {
138 DCHECK(!g_main_message_loop);
139 g_main_message_loop = new base::MessageLoopForUI();
140 base::MessageLoopForUI::current()->Start();
142 DCHECK_EQ(g_main_message_loop, base::MessageLoop::current());
143 if (!g_network_change_notifier) {
144 net::NetworkChangeNotifier::SetFactory(
145 new net::NetworkChangeNotifierFactoryAndroid());
146 g_network_change_notifier = net::NetworkChangeNotifier::Create();
148 proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
149 GetNetworkTaskRunner(), NULL));
150 GetNetworkTaskRunner()->PostTask(
151 FROM_HERE,
152 base::Bind(&URLRequestContextAdapter::InitRequestContextOnNetworkThread,
153 this));
156 void URLRequestContextAdapter::InitRequestContextOnNetworkThread() {
157 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
158 DCHECK(config_);
159 // TODO(mmenke): Add method to have the builder enable SPDY.
160 net::URLRequestContextBuilder context_builder;
161 context_builder.set_network_delegate(new BasicNetworkDelegate());
162 context_builder.set_proxy_config_service(proxy_config_service_.get());
163 config_->ConfigureURLRequestContextBuilder(&context_builder);
165 context_.reset(context_builder.Build());
167 // Currently (circa M39) enabling QUIC requires setting probability threshold.
168 if (config_->enable_quic) {
169 context_->http_server_properties()
170 ->SetAlternateProtocolProbabilityThreshold(0.0f);
171 for (size_t hint = 0; hint < config_->quic_hints.size(); ++hint) {
172 const URLRequestContextConfig::QuicHint& quic_hint =
173 *config_->quic_hints[hint];
174 if (quic_hint.host.empty()) {
175 LOG(ERROR) << "Empty QUIC hint host: " << quic_hint.host;
176 continue;
179 url::CanonHostInfo host_info;
180 std::string canon_host(net::CanonicalizeHost(quic_hint.host, &host_info));
181 if (!host_info.IsIPAddress() &&
182 !net::IsCanonicalizedHostCompliant(canon_host)) {
183 LOG(ERROR) << "Invalid QUIC hint host: " << quic_hint.host;
184 continue;
187 if (quic_hint.port <= std::numeric_limits<uint16>::min() ||
188 quic_hint.port > std::numeric_limits<uint16>::max()) {
189 LOG(ERROR) << "Invalid QUIC hint port: "
190 << quic_hint.port;
191 continue;
194 if (quic_hint.alternate_port <= std::numeric_limits<uint16>::min() ||
195 quic_hint.alternate_port > std::numeric_limits<uint16>::max()) {
196 LOG(ERROR) << "Invalid QUIC hint alternate port: "
197 << quic_hint.alternate_port;
198 continue;
201 net::HostPortPair quic_hint_host_port_pair(canon_host,
202 quic_hint.port);
203 context_->http_server_properties()->SetAlternateProtocol(
204 quic_hint_host_port_pair,
205 static_cast<uint16>(quic_hint.alternate_port),
206 net::AlternateProtocol::QUIC,
207 1.0f);
210 config_.reset(NULL);
212 if (VLOG_IS_ON(2)) {
213 net_log_observer_.reset(new NetLogObserver());
214 context_->net_log()->AddThreadSafeObserver(net_log_observer_.get(),
215 net::NetLog::LOG_ALL_BUT_BYTES);
218 is_context_initialized_ = true;
219 while (!tasks_waiting_for_context_.empty()) {
220 tasks_waiting_for_context_.front().Run();
221 tasks_waiting_for_context_.pop();
224 delegate_->OnContextInitialized(this);
227 void URLRequestContextAdapter::PostTaskToNetworkThread(
228 const tracked_objects::Location& posted_from,
229 const RunAfterContextInitTask& callback) {
230 GetNetworkTaskRunner()->PostTask(
231 posted_from,
232 base::Bind(
233 &URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread,
234 this,
235 callback));
238 void URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread(
239 const RunAfterContextInitTask& callback) {
240 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
241 if (is_context_initialized_) {
242 callback.Run();
243 return;
245 tasks_waiting_for_context_.push(callback);
248 URLRequestContextAdapter::~URLRequestContextAdapter() {
249 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
250 if (net_log_observer_) {
251 context_->net_log()->RemoveThreadSafeObserver(net_log_observer_.get());
252 net_log_observer_.reset();
254 StopNetLogHelper();
255 // TODO(mef): Ensure that |network_thread_| is destroyed properly.
258 const std::string& URLRequestContextAdapter::GetUserAgent(
259 const GURL& url) const {
260 return user_agent_;
263 net::URLRequestContext* URLRequestContextAdapter::GetURLRequestContext() {
264 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
265 if (!context_) {
266 LOG(ERROR) << "URLRequestContext is not set up";
268 return context_.get();
271 scoped_refptr<base::SingleThreadTaskRunner>
272 URLRequestContextAdapter::GetNetworkTaskRunner() const {
273 return network_thread_->message_loop_proxy();
276 void URLRequestContextAdapter::StartNetLogToFile(const std::string& file_name) {
277 PostTaskToNetworkThread(
278 FROM_HERE,
279 base::Bind(
280 &URLRequestContextAdapter::StartNetLogToFileHelper, this, file_name));
283 void URLRequestContextAdapter::StopNetLog() {
284 PostTaskToNetworkThread(
285 FROM_HERE, base::Bind(&URLRequestContextAdapter::StopNetLogHelper, this));
288 void URLRequestContextAdapter::StartNetLogToFileHelper(
289 const std::string& file_name) {
290 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
291 // Do nothing if already logging to a file.
292 if (net_log_logger_)
293 return;
295 base::FilePath file_path(file_name);
296 FILE* file = base::OpenFile(file_path, "w");
297 if (!file)
298 return;
300 scoped_ptr<base::Value> constants(net::NetLogLogger::GetConstants());
301 net_log_logger_.reset(new net::NetLogLogger(file, *constants));
302 net_log_logger_->StartObserving(context_->net_log());
305 void URLRequestContextAdapter::StopNetLogHelper() {
306 DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
307 if (net_log_logger_) {
308 net_log_logger_->StopObserving();
309 net_log_logger_.reset();
313 void NetLogObserver::OnAddEntry(const net::NetLog::Entry& entry) {
314 VLOG(2) << "Net log entry: type=" << entry.type()
315 << ", source=" << entry.source().type << ", phase=" << entry.phase();
318 } // namespace cronet