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

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: Address Helen's comments. 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)
xunjieli 2016/04/08 17:46:15 Can we get rid of this and add a base::MessageLoop
mef 2016/04/08 20:40:43 Done.
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(
xunjieli 2016/04/08 17:46:15 StartNetLog(OnNetworkThread) ?
mef 2016/04/08 20:40:43 Done.
137 const 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 LOG(ERROR) << "Can not start NetLog to " << full_path.value();
153 return;
154 }
155
156 net::NetLogCaptureMode capture_mode =
157 log_bytes ? net::NetLogCaptureMode::IncludeSocketBytes()
158 : net::NetLogCaptureMode::Default();
159
160 net_log_observer_.reset(new net::WriteToFileNetLogObserver());
161 net_log_observer_->set_capture_mode(capture_mode);
162 net_log_observer_->StartObserving(main_context_->net_log(), std::move(file),
163 nullptr, main_context_.get());
164 LOG(WARNING) << "Started NetLog to " << full_path.value();
165 }
166
167 void CronetEnvironment::StopNetLog() {
168 PostToNetworkThread(FROM_HERE,
169 base::Bind(&CronetEnvironment::StopNetLogInternal,
170 base::Unretained(this)));
171 }
172
173 void CronetEnvironment::StopNetLogInternal() {
xunjieli 2016/04/08 17:46:15 StopNetLogOnNetworkThread?
mef 2016/04/08 20:40:43 Done.
174 if (net_log_observer_) {
175 DLOG(WARNING) << "Stopped NetLog.";
176 net_log_observer_->StopObserving(main_context_.get());
177 net_log_observer_.reset();
178 }
179 }
180
181 net::HttpNetworkSession* CronetEnvironment::GetHttpNetworkSession(
182 net::URLRequestContext* context) {
183 DCHECK(context);
184 if (!context->http_transaction_factory())
185 return nullptr;
186
187 return context->http_transaction_factory()->GetSession();
188 }
189
190 void CronetEnvironment::AddQuicHint(const std::string& host,
191 int port,
192 int alternate_port) {
193 DCHECK(port == alternate_port);
194 quic_hints_.push_back(net::HostPortPair(host, port));
195 }
196
197 CronetEnvironment::CronetEnvironment(const std::string& user_agent_product_name)
198 : http2_enabled_(false),
199 quic_enabled_(false),
200 user_agent_product_name_(user_agent_product_name),
201 net_log_(new net::NetLog) {}
202
203 void CronetEnvironment::Install() {
204 // TODO(mef): Remove this and FakeCertVerifier after GRPC testing.
205 set_cert_verifier(scoped_ptr<net::CertVerifier>(new FakeCertVerifier()));
206
207 // Threads setup.
208 network_cache_thread_.reset(new base::Thread("Chrome Network Cache Thread"));
209 network_cache_thread_->StartWithOptions(
210 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
211 network_io_thread_.reset(new base::Thread("Chrome Network IO Thread"));
212 network_io_thread_->StartWithOptions(
213 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
214 file_thread_.reset(new base::Thread("Chrome File Thread"));
215 file_thread_->StartWithOptions(
216 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
217 file_user_blocking_thread_.reset(
218 new base::Thread("Chrome File User Blocking Thread"));
219 file_user_blocking_thread_->StartWithOptions(
220 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
221
222 static bool ssl_key_log_file_set = false;
223 if (!ssl_key_log_file_set && !ssl_key_log_file_name_.empty()) {
224 ssl_key_log_file_set = true;
225 base::FilePath ssl_key_log_file;
226 if (!PathService::Get(base::DIR_HOME, &ssl_key_log_file))
227 return;
228 net::SSLClientSocket::SetSSLKeyLogFile(
229 ssl_key_log_file.Append(ssl_key_log_file_name_),
230 file_thread_->task_runner());
231 }
232
233 proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
234 network_io_thread_->task_runner(), nullptr);
235
236 #if defined(USE_NSS_VERIFIER)
237 net::SetURLRequestContextForNSSHttpIO(main_context_.get());
238 #endif
239 base::subtle::MemoryBarrier();
240 PostToNetworkThread(FROM_HERE,
241 base::Bind(&CronetEnvironment::InitializeOnNetworkThread,
242 base::Unretained(this)));
243 }
244
245 CronetEnvironment::~CronetEnvironment() {
246 // net::HTTPProtocolHandlerDelegate::SetInstance(nullptr);
247 #if defined(USE_NSS_VERIFIER)
248 net::SetURLRequestContextForNSSHttpIO(nullptr);
249 #endif
250 }
251
252 void CronetEnvironment::InitializeOnNetworkThread() {
253 DCHECK(network_io_thread_->task_runner()->BelongsToCurrentThread());
254 main_context_.reset(new net::URLRequestContext);
255 main_context_->set_net_log(net_log_.get());
256 std::string user_agent(user_agent_product_name_ +
257 " (iOS); Cronet/" CRONET_VERSION);
258 main_context_->set_http_user_agent_settings(
259 new net::StaticHttpUserAgentSettings("en", user_agent));
260
261 main_context_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
262 main_context_->set_transport_security_state(
263 new net::TransportSecurityState());
264 http_server_properties_.reset(new net::HttpServerPropertiesImpl());
265 main_context_->set_http_server_properties(
266 http_server_properties_->GetWeakPtr());
267
268 // TODO(rdsmith): Note that the ".release()" calls below are leaking
269 // the objects in question; this should be fixed by having an object
270 // corresponding to URLRequestContextStorage that actually owns those
271 // objects. See http://crbug.com/523858.
xunjieli 2016/04/08 17:46:15 I still feel we should convert to using net::URLRe
mef 2016/04/08 20:40:43 I agree, however I would like to unify CronetEngin
272 scoped_ptr<net::MappedHostResolver> mapped_host_resolver(
273 new net::MappedHostResolver(
274 net::HostResolver::CreateDefaultResolver(nullptr)));
275
276 mapped_host_resolver->SetRulesFromString(host_resolver_rules_);
277 main_context_->set_host_resolver(mapped_host_resolver.release());
278
279 if (!cert_verifier_)
280 cert_verifier_ = net::CertVerifier::CreateDefault();
281 main_context_->set_cert_verifier(cert_verifier_.get());
282
283 main_context_->set_http_auth_handler_factory(
284 net::HttpAuthHandlerRegistryFactory::CreateDefault(
285 main_context_->host_resolver())
286 .release());
287 main_context_->set_proxy_service(
288 net::ProxyService::CreateUsingSystemProxyResolver(
289 std::move(proxy_config_service_), 0, nullptr)
290 .release());
291
292 // Cache
293 base::FilePath cache_path;
294 if (!PathService::Get(base::DIR_CACHE, &cache_path))
295 return;
296 cache_path = cache_path.Append(FILE_PATH_LITERAL("cronet"));
297 scoped_ptr<net::HttpCache::DefaultBackend> main_backend(
298 new net::HttpCache::DefaultBackend(net::DISK_CACHE,
299 net::CACHE_BACKEND_SIMPLE, cache_path,
300 0, // Default cache size.
301 network_cache_thread_->task_runner()));
302
303 net::HttpNetworkSession::Params params;
304
305 params.host_resolver = main_context_->host_resolver();
306 params.cert_verifier = main_context_->cert_verifier();
307 params.channel_id_service = main_context_->channel_id_service();
308 params.transport_security_state = main_context_->transport_security_state();
309 params.proxy_service = main_context_->proxy_service();
310 params.ssl_config_service = main_context_->ssl_config_service();
311 params.http_auth_handler_factory = main_context_->http_auth_handler_factory();
312 params.http_server_properties = main_context_->http_server_properties();
313 params.net_log = main_context_->net_log();
314 params.enable_http2 = http2_enabled();
315 params.parse_alternative_services = false;
316 params.enable_quic = quic_enabled();
317
318 for (auto quic_hint : quic_hints_) {
xunjieli 2016/04/08 17:46:15 const auto& ?
mef 2016/04/08 20:40:43 Done.
319 net::AlternativeService alternative_service(net::AlternateProtocol::QUIC,
320 "", quic_hint.port());
321
322 main_context_->http_server_properties()->SetAlternativeService(
323 quic_hint, alternative_service, base::Time::Max());
324 params.quic_host_whitelist.insert(quic_hint.host());
325 }
326
327 if (!params.channel_id_service) {
328 // The main context may not have a ChannelIDService, since it is lazily
329 // constructed. If not, build an ephemeral ChannelIDService with no backing
330 // disk store.
331 // TODO(ellyjones): support persisting ChannelID.
332 params.channel_id_service =
333 new net::ChannelIDService(new net::DefaultChannelIDStore(NULL),
334 base::WorkerPool::GetTaskRunner(true));
335 }
336
337 // TODO(mmenke): These really shouldn't be leaked.
338 // See https://crbug.com/523858.
xunjieli 2016/04/08 17:46:15 I think we should fix these leaky objects. Does co
mef 2016/04/08 20:40:43 Yes, and I don't know. I'll try it out when/if I h
339 net::HttpNetworkSession* http_network_session =
340 new net::HttpNetworkSession(params);
341 net::HttpCache* main_cache =
342 new net::HttpCache(http_network_session, std::move(main_backend),
343 true /* set_up_quic_server_info */);
344 main_context_->set_http_transaction_factory(main_cache);
345
346 net::URLRequestJobFactoryImpl* job_factory =
347 new net::URLRequestJobFactoryImpl;
348 main_context_->set_job_factory(job_factory);
349 main_context_->set_net_log(net_log_.get());
350 }
351
352 std::string CronetEnvironment::user_agent() {
353 const net::HttpUserAgentSettings* user_agent_settings =
354 main_context_->http_user_agent_settings();
355 if (!user_agent_settings) {
356 return nullptr;
357 }
358
359 return user_agent_settings->GetUserAgent();
360 }
361
362 } // namespace cronet
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698