1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/cronet/android/url_request_context_adapter.h"
#include <limits>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "components/cronet/url_request_context_config.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/net_errors.h"
#include "net/base/net_log_logger.h"
#include "net/base/net_util.h"
#include "net/base/network_change_notifier.h"
#include "net/base/network_delegate_impl.h"
#include "net/cert/cert_verifier.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_server_properties.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
namespace {
// MessageLoop on the main thread, which is where objects that receive Java
// notifications generally live.
base::MessageLoop* g_main_message_loop = nullptr;
net::NetworkChangeNotifier* g_network_change_notifier = nullptr;
class BasicNetworkDelegate : public net::NetworkDelegateImpl {
public:
BasicNetworkDelegate() {}
virtual ~BasicNetworkDelegate() {}
private:
// net::NetworkDelegate implementation.
int OnBeforeURLRequest(net::URLRequest* request,
const net::CompletionCallback& callback,
GURL* new_url) override {
return net::OK;
}
int OnBeforeSendHeaders(net::URLRequest* request,
const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) override {
return net::OK;
}
void OnSendHeaders(net::URLRequest* request,
const net::HttpRequestHeaders& headers) override {}
int OnHeadersReceived(
net::URLRequest* request,
const net::CompletionCallback& callback,
const net::HttpResponseHeaders* original_response_headers,
scoped_refptr<net::HttpResponseHeaders>* _response_headers,
GURL* allowed_unsafe_redirect_url) override {
return net::OK;
}
void OnBeforeRedirect(net::URLRequest* request,
const GURL& new_location) override {}
void OnResponseStarted(net::URLRequest* request) override {}
void OnRawBytesRead(const net::URLRequest& request,
int bytes_read) override {}
void OnCompleted(net::URLRequest* request, bool started) override {}
void OnURLRequestDestroyed(net::URLRequest* request) override {}
void OnPACScriptError(int line_number,
const base::string16& error) override {}
NetworkDelegate::AuthRequiredResponse OnAuthRequired(
net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
const AuthCallback& callback,
net::AuthCredentials* credentials) override {
return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
}
bool OnCanGetCookies(const net::URLRequest& request,
const net::CookieList& cookie_list) override {
return false;
}
bool OnCanSetCookie(const net::URLRequest& request,
const std::string& cookie_line,
net::CookieOptions* options) override {
return false;
}
bool OnCanAccessFile(const net::URLRequest& request,
const base::FilePath& path) const override {
return false;
}
bool OnCanThrottleRequest(
const net::URLRequest& request) const override {
return false;
}
DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate);
};
} // namespace
namespace cronet {
URLRequestContextAdapter::URLRequestContextAdapter(
URLRequestContextAdapterDelegate* delegate,
std::string user_agent) {
delegate_ = delegate;
user_agent_ = user_agent;
}
void URLRequestContextAdapter::Initialize(
scoped_ptr<URLRequestContextConfig> config) {
network_thread_ = new base::Thread("network");
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_IO;
network_thread_->StartWithOptions(options);
config_ = config.Pass();
}
void URLRequestContextAdapter::InitRequestContextOnMainThread() {
if (!base::MessageLoop::current()) {
DCHECK(!g_main_message_loop);
g_main_message_loop = new base::MessageLoopForUI();
base::MessageLoopForUI::current()->Start();
}
DCHECK_EQ(g_main_message_loop, base::MessageLoop::current());
if (!g_network_change_notifier) {
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
g_network_change_notifier = net::NetworkChangeNotifier::Create();
}
proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
GetNetworkTaskRunner(), NULL));
GetNetworkTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&URLRequestContextAdapter::InitRequestContextOnNetworkThread,
this));
}
void URLRequestContextAdapter::InitRequestContextOnNetworkThread() {
DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
DCHECK(config_);
// TODO(mmenke): Add method to have the builder enable SPDY.
net::URLRequestContextBuilder context_builder;
context_builder.set_network_delegate(new BasicNetworkDelegate());
context_builder.set_proxy_config_service(proxy_config_service_.get());
config_->ConfigureURLRequestContextBuilder(&context_builder);
context_.reset(context_builder.Build());
// Currently (circa M39) enabling QUIC requires setting probability threshold.
if (config_->enable_quic) {
context_->http_server_properties()
->SetAlternateProtocolProbabilityThreshold(0.0f);
for (size_t hint = 0; hint < config_->quic_hints.size(); ++hint) {
const URLRequestContextConfig::QuicHint& quic_hint =
*config_->quic_hints[hint];
if (quic_hint.host.empty()) {
LOG(ERROR) << "Empty QUIC hint host: " << quic_hint.host;
continue;
}
url::CanonHostInfo host_info;
std::string canon_host(net::CanonicalizeHost(quic_hint.host, &host_info));
if (!host_info.IsIPAddress() &&
!net::IsCanonicalizedHostCompliant(canon_host)) {
LOG(ERROR) << "Invalid QUIC hint host: " << quic_hint.host;
continue;
}
if (quic_hint.port <= std::numeric_limits<uint16>::min() ||
quic_hint.port > std::numeric_limits<uint16>::max()) {
LOG(ERROR) << "Invalid QUIC hint port: "
<< quic_hint.port;
continue;
}
if (quic_hint.alternate_port <= std::numeric_limits<uint16>::min() ||
quic_hint.alternate_port > std::numeric_limits<uint16>::max()) {
LOG(ERROR) << "Invalid QUIC hint alternate port: "
<< quic_hint.alternate_port;
continue;
}
net::HostPortPair quic_hint_host_port_pair(canon_host,
quic_hint.port);
context_->http_server_properties()->SetAlternateProtocol(
quic_hint_host_port_pair,
static_cast<uint16>(quic_hint.alternate_port),
net::AlternateProtocol::QUIC,
1.0f);
}
}
config_.reset(NULL);
if (VLOG_IS_ON(2)) {
net_log_observer_.reset(new NetLogObserver());
context_->net_log()->AddThreadSafeObserver(net_log_observer_.get(),
net::NetLog::LOG_ALL_BUT_BYTES);
}
is_context_initialized_ = true;
while (!tasks_waiting_for_context_.empty()) {
tasks_waiting_for_context_.front().Run();
tasks_waiting_for_context_.pop();
}
delegate_->OnContextInitialized(this);
}
void URLRequestContextAdapter::PostTaskToNetworkThread(
const tracked_objects::Location& posted_from,
const RunAfterContextInitTask& callback) {
GetNetworkTaskRunner()->PostTask(
posted_from,
base::Bind(
&URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread,
this,
callback));
}
void URLRequestContextAdapter::RunTaskAfterContextInitOnNetworkThread(
const RunAfterContextInitTask& callback) {
DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
if (is_context_initialized_) {
callback.Run();
return;
}
tasks_waiting_for_context_.push(callback);
}
URLRequestContextAdapter::~URLRequestContextAdapter() {
DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
if (net_log_observer_) {
context_->net_log()->RemoveThreadSafeObserver(net_log_observer_.get());
net_log_observer_.reset();
}
StopNetLogHelper();
// TODO(mef): Ensure that |network_thread_| is destroyed properly.
}
const std::string& URLRequestContextAdapter::GetUserAgent(
const GURL& url) const {
return user_agent_;
}
net::URLRequestContext* URLRequestContextAdapter::GetURLRequestContext() {
DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
if (!context_) {
LOG(ERROR) << "URLRequestContext is not set up";
}
return context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner>
URLRequestContextAdapter::GetNetworkTaskRunner() const {
return network_thread_->message_loop_proxy();
}
void URLRequestContextAdapter::StartNetLogToFile(const std::string& file_name) {
PostTaskToNetworkThread(
FROM_HERE,
base::Bind(
&URLRequestContextAdapter::StartNetLogToFileHelper, this, file_name));
}
void URLRequestContextAdapter::StopNetLog() {
PostTaskToNetworkThread(
FROM_HERE, base::Bind(&URLRequestContextAdapter::StopNetLogHelper, this));
}
void URLRequestContextAdapter::StartNetLogToFileHelper(
const std::string& file_name) {
DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
// Do nothing if already logging to a file.
if (net_log_logger_)
return;
base::FilePath file_path(file_name);
FILE* file = base::OpenFile(file_path, "w");
if (!file)
return;
scoped_ptr<base::Value> constants(net::NetLogLogger::GetConstants());
net_log_logger_.reset(new net::NetLogLogger(file, *constants));
net_log_logger_->StartObserving(context_->net_log());
}
void URLRequestContextAdapter::StopNetLogHelper() {
DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread());
if (net_log_logger_) {
net_log_logger_->StopObserving();
net_log_logger_.reset();
}
}
void NetLogObserver::OnAddEntry(const net::NetLog::Entry& entry) {
VLOG(2) << "Net log entry: type=" << entry.type()
<< ", source=" << entry.source().type << ", phase=" << entry.phase();
}
} // namespace cronet
|