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 "mojo/services/network/network_context.h"
10 #include "base/base_paths.h"
11 #include "base/path_service.h"
12 #include "mojo/services/network/url_loader_impl.h"
13 #include "net/proxy/proxy_service.h"
14 #include "net/url_request/url_request_context.h"
15 #include "net/url_request/url_request_context_builder.h"
19 NetworkContext::NetworkContext(
20 scoped_ptr
<net::URLRequestContext
> url_request_context
)
21 : url_request_context_(url_request_context
.Pass()),
25 NetworkContext::NetworkContext(const base::FilePath
& base_path
)
26 : NetworkContext(MakeURLRequestContext(base_path
)) {
29 NetworkContext::~NetworkContext() {
31 // TODO(darin): Be careful about destruction order of member variables?
33 // Call each URLLoaderImpl and ask it to release its net::URLRequest, as the
34 // corresponding net::URLRequestContext is going away with this
35 // NetworkContext. The loaders can be deregistering themselves in Cleanup(),
36 // so iterate over a copy.
37 for (auto& url_loader
: url_loaders_
) {
38 url_loader
->Cleanup();
42 void NetworkContext::RegisterURLLoader(URLLoaderImpl
* url_loader
) {
43 DCHECK(url_loaders_
.count(url_loader
) == 0);
44 url_loaders_
.insert(url_loader
);
47 void NetworkContext::DeregisterURLLoader(URLLoaderImpl
* url_loader
) {
49 size_t removed_count
= url_loaders_
.erase(url_loader
);
50 DCHECK(removed_count
);
54 size_t NetworkContext::GetURLLoaderCountForTesting() {
55 return url_loaders_
.size();
59 scoped_ptr
<net::URLRequestContext
> NetworkContext::MakeURLRequestContext(
60 const base::FilePath
& base_path
) {
61 net::URLRequestContextBuilder builder
;
62 builder
.set_accept_language("en-us,en");
63 // TODO(darin): This is surely the wrong UA string.
64 builder
.set_user_agent("Mojo/0.1");
65 builder
.set_proxy_service(net::ProxyService::CreateDirect());
66 builder
.set_transport_security_persister_path(base_path
);
68 net::URLRequestContextBuilder::HttpCacheParams cache_params
;
69 #if defined(OS_ANDROID)
70 // On Android, we store the cache on disk becase we can run only a single
71 // instance of the shell at a time.
72 cache_params
.type
= net::URLRequestContextBuilder::HttpCacheParams::DISK
;
73 cache_params
.path
= base_path
.Append(FILE_PATH_LITERAL("Cache"));
75 // On desktop, we store the cache in memory so we can run many shells
76 // in parallel when running tests, otherwise the network services in each
77 // shell will corrupt the disk cache.
78 cache_params
.type
= net::URLRequestContextBuilder::HttpCacheParams::IN_MEMORY
;
81 builder
.EnableHttpCache(cache_params
);
82 builder
.set_file_enabled(true);
83 return make_scoped_ptr(builder
.Build());