Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1252)

Side by Side Diff: components/cronet/ios/cronet_environment.cc

Issue 1858483002: Cronet for iOS with C API for GRPC support. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@small
Patch Set: Make it syncable Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 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.
4
5 #include "components/cronet/ios/cronet_environment.h"
6
7 #include <utility>
8
9 #include "base/at_exit.h"
10 #include "base/atomicops.h"
11 #include "base/command_line.h"
12 #include "base/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_file.h"
15 #include "base/json/json_writer.h"
16 #include "base/mac/bind_objc_block.h"
17 #include "base/mac/foundation_util.h"
18 #include "base/mac/scoped_block.h"
19 #include "base/macros.h"
20 #include "base/metrics/statistics_recorder.h"
21 #include "base/path_service.h"
22 #include "base/threading/worker_pool.h"
23 #include "components/cronet/version.h"
24 #include "components/prefs/json_pref_store.h"
25 #include "components/prefs/pref_filter.h"
26 #include "net/base/net_errors.h"
27 #include "net/base/network_change_notifier.h"
28 #include "net/base/sdch_manager.h"
29 #include "net/cert/cert_verify_result.h"
30 #include "net/dns/host_resolver.h"
31 #include "net/dns/mapped_host_resolver.h"
32 #include "net/http/http_auth_handler_factory.h"
33 #include "net/http/http_cache.h"
34 #include "net/http/http_response_headers.h"
35 #include "net/http/http_server_properties_impl.h"
36 #include "net/http/http_stream_factory.h"
37 #include "net/http/http_util.h"
38 #include "net/log/net_log.h"
39 #include "net/log/write_to_file_net_log_observer.h"
40 #include "net/proxy/proxy_service.h"
41 #include "net/sdch/sdch_owner.h"
42 #include "net/socket/ssl_client_socket.h"
43 #include "net/ssl/channel_id_service.h"
44 #include "net/ssl/default_channel_id_store.h"
45 #include "net/ssl/ssl_config_service_defaults.h"
46 #include "net/url_request/static_http_user_agent_settings.h"
47 #include "net/url_request/url_request_context_storage.h"
48 #include "net/url_request/url_request_job_factory_impl.h"
49 #include "url/url_util.h"
50
51 namespace {
52
53 base::AtExitManager* g_at_exit_ = nullptr;
54 net::NetworkChangeNotifier* g_network_change_notifier = nullptr;
55
56 // TODO(mef): Remove this after GRPC testing is done.
57 class FakeCertVerifier : public net::CertVerifier {
58 public:
59 FakeCertVerifier() {}
60
61 ~FakeCertVerifier() override {}
62
63 // CertVerifier implementation
64 int Verify(net::X509Certificate* cert,
65 const std::string& hostname,
66 const std::string& ocsp_response,
67 int flags,
68 net::CRLSet* crl_set,
69 net::CertVerifyResult* verify_result,
70 const net::CompletionCallback& callback,
71 scoped_ptr<Request>* out_req,
72 const net::BoundNetLog& net_log) override {
73 // It's all good!
74 verify_result->verified_cert = cert;
75 verify_result->cert_status = MapNetErrorToCertStatus(net::OK);
76 return net::OK;
77 }
78 };
79
80 } // namespace
81
82 namespace cronet {
83
84 bool CronetEnvironment::IsOnNetworkThread() {
85 return network_io_thread_->task_runner()->BelongsToCurrentThread();
86 }
87
88 void CronetEnvironment::PostToNetworkThread(
89 const tracked_objects::Location& from_here,
90 const base::Closure& task) {
91 network_io_thread_->task_runner()->PostTask(from_here, task);
92 }
93
94 void CronetEnvironment::PostToFileUserBlockingThread(
95 const tracked_objects::Location& from_here,
96 const base::Closure& task) {
97 file_user_blocking_thread_->message_loop()->PostTask(from_here, task);
98 }
99
100 net::URLRequestContext* CronetEnvironment::GetURLRequestContext() const {
101 return main_context_.get();
102 }
103
104 // static
105 void CronetEnvironment::Initialize() {
106 // DCHECK_EQ([NSThread currentThread], [NSThread mainThread]);
107 // This method must be called once from the main thread.
108 if (!g_at_exit_)
109 g_at_exit_ = new base::AtExitManager;
110
111 url::Initialize();
112 base::CommandLine::Init(0, nullptr);
113
114 // Without doing this, StatisticsRecorder::FactoryGet() leaks one histogram
115 // per call after the first for a given name.
116 base::StatisticsRecorder::Initialize();
117
118 // Create a message loop on the UI thread.
119 base::MessageLoop* main_message_loop =
120 new base::MessageLoop(base::MessageLoop::TYPE_UI);
121 #pragma unused(main_message_loop)
122 base::MessageLoopForUI::current()->Attach();
123 // The network change notifier must be initialized so that registered
124 // delegates will receive callbacks.
125 g_network_change_notifier = net::NetworkChangeNotifier::Create();
126 }
127
128 void CronetEnvironment::StartNetLog(base::FilePath::StringType file_name,
129 bool log_bytes) {
130 DCHECK(file_name.length());
131 PostToNetworkThread(FROM_HERE,
132 base::Bind(&CronetEnvironment::StartNetLogInternal,
133 base::Unretained(this), file_name, log_bytes));
134 }
135
136 void CronetEnvironment::StartNetLogInternal(
137 base::FilePath::StringType file_name,
138 bool log_bytes) {
139 DCHECK(file_name.length());
140 DCHECK(net_log_);
141
142 if (net_log_observer_)
143 return;
144
145 base::FilePath files_root;
146 if (!PathService::Get(base::DIR_HOME, &files_root))
147 return;
148
149 base::FilePath full_path = files_root.Append(file_name);
150 base::ScopedFILE file(base::OpenFile(full_path, "w"));
151 if (!file)
152 return;
153
154 net::NetLogCaptureMode capture_mode =
155 log_bytes ? net::NetLogCaptureMode::IncludeSocketBytes()
156 : net::NetLogCaptureMode::Default();
157
158 net_log_observer_.reset(new net::WriteToFileNetLogObserver());
159 net_log_observer_->set_capture_mode(capture_mode);
160 net_log_observer_->StartObserving(main_context_->net_log(), std::move(file),
161 nullptr, main_context_.get());
162 DLOG(WARNING) << "Started NetLog to " << full_path.value();
163 }
164
165 void CronetEnvironment::StopNetLog() {
166 PostToNetworkThread(FROM_HERE,
167 base::Bind(&CronetEnvironment::StopNetLogInternal,
168 base::Unretained(this)));
169 }
170
171 void CronetEnvironment::StopNetLogInternal() {
172 if (net_log_observer_) {
173 DLOG(WARNING) << "Stopped NetLog.";
174 net_log_observer_->StopObserving(main_context_.get());
175 net_log_observer_.reset();
176 }
177 }
178
179 net::HttpNetworkSession* CronetEnvironment::GetHttpNetworkSession(
180 net::URLRequestContext* context) {
181 DCHECK(context);
182 if (!context->http_transaction_factory())
183 return nullptr;
184
185 return context->http_transaction_factory()->GetSession();
186 }
187
188 void CronetEnvironment::AddQuicHint(const std::string& host,
189 int port,
190 int alternate_port) {
191 DCHECK(port == alternate_port);
192 quic_hints_.push_back(net::HostPortPair(host, port));
193 }
194
195 CronetEnvironment::CronetEnvironment(const std::string& user_agent_product_name)
196 : http2_enabled_(false),
197 quic_enabled_(false),
198 user_agent_product_name_(user_agent_product_name),
199 net_log_(new net::NetLog) {}
200
201 void CronetEnvironment::Install() {
202 // TODO(mef): Remove this and FakeCertVerifier after GRPC testing.
203 set_cert_verifier(scoped_ptr<net::CertVerifier>(new FakeCertVerifier()));
204
205 // Threads setup.
206 network_cache_thread_.reset(new base::Thread("Chrome Network Cache Thread"));
207 network_cache_thread_->StartWithOptions(
208 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
209 network_io_thread_.reset(new base::Thread("Chrome Network IO Thread"));
210 network_io_thread_->StartWithOptions(
211 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
212 file_thread_.reset(new base::Thread("Chrome File Thread"));
213 file_thread_->StartWithOptions(
214 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
215 file_user_blocking_thread_.reset(
216 new base::Thread("Chrome File User Blocking Thread"));
217 file_user_blocking_thread_->StartWithOptions(
218 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
219
220 static bool ssl_key_log_file_set = false;
221 if (!ssl_key_log_file_set && !ssl_key_log_file_name_.empty()) {
222 ssl_key_log_file_set = true;
223 base::FilePath ssl_key_log_file;
224 if (!PathService::Get(base::DIR_HOME, &ssl_key_log_file))
225 return;
226 net::SSLClientSocket::SetSSLKeyLogFile(
227 ssl_key_log_file.Append(ssl_key_log_file_name_),
228 file_thread_->task_runner());
229 }
230
231 proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
232 network_io_thread_->task_runner(), nullptr);
233
234 #if defined(USE_NSS_VERIFIER)
235 net::SetURLRequestContextForNSSHttpIO(main_context_.get());
236 #endif
237 base::subtle::MemoryBarrier();
238 PostToNetworkThread(FROM_HERE,
239 base::Bind(&CronetEnvironment::InitializeOnNetworkThread,
240 base::Unretained(this)));
241 }
242
243 CronetEnvironment::~CronetEnvironment() {
244 // net::HTTPProtocolHandlerDelegate::SetInstance(nullptr);
245 #if defined(USE_NSS_VERIFIER)
246 net::SetURLRequestContextForNSSHttpIO(nullptr);
247 #endif
248 }
249
250 void CronetEnvironment::InitializeOnNetworkThread() {
251 DCHECK(network_io_thread_->task_runner()->BelongsToCurrentThread());
252 main_context_.reset(new net::URLRequestContext);
xunjieli 2016/04/08 14:43:15 Can we use net::URLRequestContextBuilder?
mef 2016/04/08 16:43:03 Yes, and we totally should, just not in this CL. T
253 main_context_->set_net_log(net_log_.get());
254 std::string user_agent(user_agent_product_name_ +
255 " (iOS); Cronet/" CRONET_VERSION);
256 main_context_->set_http_user_agent_settings(
257 new net::StaticHttpUserAgentSettings("en", user_agent));
258
259 main_context_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
260 main_context_->set_transport_security_state(
261 new net::TransportSecurityState());
262 http_server_properties_.reset(new net::HttpServerPropertiesImpl());
263 main_context_->set_http_server_properties(
264 http_server_properties_->GetWeakPtr());
265
266 // TODO(rdsmith): Note that the ".release()" calls below are leaking
267 // the objects in question; this should be fixed by having an object
268 // corresponding to URLRequestContextStorage that actually owns those
269 // objects. See http://crbug.com/523858.
270 scoped_ptr<net::MappedHostResolver> mapped_host_resolver(
271 new net::MappedHostResolver(
272 net::HostResolver::CreateDefaultResolver(nullptr)));
273
274 mapped_host_resolver->SetRulesFromString(host_resolver_rules_);
275 main_context_->set_host_resolver(mapped_host_resolver.release());
276
277 if (!cert_verifier_)
278 cert_verifier_ = net::CertVerifier::CreateDefault();
279 main_context_->set_cert_verifier(cert_verifier_.get());
280
281 main_context_->set_http_auth_handler_factory(
282 net::HttpAuthHandlerRegistryFactory::CreateDefault(
283 main_context_->host_resolver())
284 .release());
285 main_context_->set_proxy_service(
286 net::ProxyService::CreateUsingSystemProxyResolver(
287 std::move(proxy_config_service_), 0, nullptr)
288 .release());
289
290 // Cache
291 base::FilePath cache_path;
292 if (!PathService::Get(base::DIR_CACHE, &cache_path))
293 return;
294 cache_path = cache_path.Append(FILE_PATH_LITERAL("cronet"));
295 scoped_ptr<net::HttpCache::DefaultBackend> main_backend(
296 new net::HttpCache::DefaultBackend(net::DISK_CACHE,
297 net::CACHE_BACKEND_SIMPLE, cache_path,
298 0, // Default cache size.
299 network_cache_thread_->task_runner()));
300
301 net::HttpNetworkSession::Params params;
302
303 params.host_resolver = main_context_->host_resolver();
304 params.cert_verifier = main_context_->cert_verifier();
305 params.channel_id_service = main_context_->channel_id_service();
306 params.transport_security_state = main_context_->transport_security_state();
307 params.proxy_service = main_context_->proxy_service();
308 params.ssl_config_service = main_context_->ssl_config_service();
309 params.http_auth_handler_factory = main_context_->http_auth_handler_factory();
310 params.http_server_properties = main_context_->http_server_properties();
311 params.net_log = main_context_->net_log();
312 params.enable_http2 = http2_enabled();
313 params.parse_alternative_services = false;
314 params.enable_quic = quic_enabled();
315
316 for (auto quic_hint : quic_hints_) {
317 net::AlternativeService alternative_service(net::AlternateProtocol::QUIC,
318 "", quic_hint.port());
319
320 main_context_->http_server_properties()->SetAlternativeService(
321 quic_hint, alternative_service, base::Time::Max());
322 params.quic_host_whitelist.insert(quic_hint.host());
323 }
324
325 if (!params.channel_id_service) {
326 // The main context may not have a ChannelIDService, since it is lazily
327 // constructed. If not, build an ephemeral ChannelIDService with no backing
328 // disk store.
329 // TODO(ellyjones): support persisting ChannelID.
330 params.channel_id_service =
331 new net::ChannelIDService(new net::DefaultChannelIDStore(NULL),
332 base::WorkerPool::GetTaskRunner(true));
333 }
334
335 // TODO(mmenke): These really shouldn't be leaked.
336 // See https://crbug.com/523858.
337 net::HttpNetworkSession* http_network_session =
338 new net::HttpNetworkSession(params);
339 net::HttpCache* main_cache =
340 new net::HttpCache(http_network_session, std::move(main_backend),
341 true /* set_up_quic_server_info */);
342 main_context_->set_http_transaction_factory(main_cache);
343
344 net::URLRequestJobFactoryImpl* job_factory =
345 new net::URLRequestJobFactoryImpl;
346 main_context_->set_job_factory(job_factory);
347 main_context_->set_net_log(net_log_.get());
348 }
349
350 std::string CronetEnvironment::user_agent() {
351 const net::HttpUserAgentSettings* user_agent_settings =
352 main_context_->http_user_agent_settings();
353 if (!user_agent_settings) {
354 return nullptr;
355 }
356
357 return user_agent_settings->GetUserAgent();
358 }
359
360 } // namespace cronet
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698