1 // Copyright 2015 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/shell/network_fetcher.h"
8 #include "base/command_line.h"
9 #include "base/files/file.h"
10 #include "base/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/process/process.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/trace_event/trace_event.h"
20 #include "crypto/secure_hash.h"
21 #include "crypto/sha2.h"
22 #include "mojo/common/common_type_converters.h"
23 #include "mojo/common/data_pipe_utils.h"
24 #include "mojo/common/url_type_converters.h"
25 #include "mojo/services/network/public/interfaces/url_loader_factory.mojom.h"
26 #include "mojo/shell/data_pipe_peek.h"
27 #include "mojo/shell/switches.h"
32 NetworkFetcher::NetworkFetcher(bool disable_cache
,
33 mojo::URLRequestPtr request
,
34 URLLoaderFactory
* url_loader_factory
,
35 const FetchCallback
& loader_callback
)
36 : Fetcher(loader_callback
),
37 disable_cache_(false),
38 url_(request
->url
.To
<GURL
>()),
39 weak_ptr_factory_(this) {
40 StartNetworkRequest(request
.Pass(), url_loader_factory
);
43 NetworkFetcher::~NetworkFetcher() {
46 const GURL
& NetworkFetcher::GetURL() const {
50 GURL
NetworkFetcher::GetRedirectURL() const {
52 return GURL::EmptyGURL();
54 if (response_
->redirect_url
.is_null())
55 return GURL::EmptyGURL();
57 return GURL(response_
->redirect_url
);
60 GURL
NetworkFetcher::GetRedirectReferer() const {
62 return GURL::EmptyGURL();
64 if (response_
->redirect_referrer
.is_null())
65 return GURL::EmptyGURL();
67 return GURL(response_
->redirect_referrer
);
69 URLResponsePtr
NetworkFetcher::AsURLResponse(base::TaskRunner
* task_runner
,
72 MojoResult result
= ReadDataRaw(
73 response_
->body
.get(), nullptr, &skip
,
74 MOJO_READ_DATA_FLAG_ALL_OR_NONE
| MOJO_READ_DATA_FLAG_DISCARD
);
75 DCHECK_EQ(result
, MOJO_RESULT_OK
);
77 return response_
.Pass();
80 void NetworkFetcher::RecordCacheToURLMapping(const base::FilePath
& path
,
82 // This is used to extract symbols on android.
83 // TODO(eseidel): All users of this log should move to using the map file.
84 VLOG(1) << "Caching mojo app " << url
<< " at " << path
.value();
86 base::FilePath temp_dir
;
87 base::GetTempDir(&temp_dir
);
88 base::ProcessId pid
= base::Process::Current().Pid();
89 std::string map_name
= base::StringPrintf("mojo_shell.%d.maps", pid
);
90 base::FilePath map_path
= temp_dir
.AppendASCII(map_name
);
92 // TODO(eseidel): Paths or URLs with spaces will need quoting.
93 std::string map_entry
=
94 base::StringPrintf("%s %s\n", path
.value().c_str(), url
.spec().c_str());
95 // TODO(eseidel): AppendToFile is missing O_CREAT, crbug.com/450696
96 if (!PathExists(map_path
)) {
97 base::WriteFile(map_path
, map_entry
.data(),
98 static_cast<int>(map_entry
.length()));
100 base::AppendToFile(map_path
, map_entry
.data(),
101 static_cast<int>(map_entry
.length()));
105 // For remote debugging, GDB needs to be, a apriori, aware of the filename a
106 // library will be loaded from. AppIds should be be both predictable and unique,
107 // but any hash would work. Currently we use sha256 from crypto/secure_hash.h
108 bool NetworkFetcher::ComputeAppId(const base::FilePath
& path
,
109 std::string
* digest_string
) {
110 scoped_ptr
<crypto::SecureHash
> ctx(
111 crypto::SecureHash::Create(crypto::SecureHash::SHA256
));
112 base::File
file(path
, base::File::FLAG_OPEN
| base::File::FLAG_READ
);
113 if (!file
.IsValid()) {
114 LOG(ERROR
) << "Failed to open " << path
.value() << " for computing AppId";
118 while (file
.IsValid()) {
119 int bytes_read
= file
.ReadAtCurrentPos(buf
, sizeof(buf
));
122 ctx
->Update(buf
, bytes_read
);
124 if (!file
.IsValid()) {
125 LOG(ERROR
) << "Error reading " << path
.value();
128 // The output is really a vector of unit8, we're cheating by using a string.
129 std::string
output(crypto::kSHA256Length
, 0);
130 ctx
->Finish(string_as_array(&output
), output
.size());
131 output
= base::HexEncode(output
.c_str(), output
.size());
132 // Using lowercase for compatiblity with sha256sum output.
133 *digest_string
= base::ToLowerASCII(output
);
137 bool NetworkFetcher::RenameToAppId(const GURL
& url
,
138 const base::FilePath
& old_path
,
139 base::FilePath
* new_path
) {
141 if (!ComputeAppId(old_path
, &app_id
))
144 // Using a hash of the url as a directory to prevent a race when the same
145 // bytes are downloaded from 2 different urls. In particular, if the same
146 // application is connected to twice concurrently with different query
147 // parameters, the directory will be different, which will prevent the
149 std::string dirname
= base::HexEncode(
150 crypto::SHA256HashString(url
.spec()).data(), crypto::kSHA256Length
);
152 base::FilePath temp_dir
;
153 base::GetTempDir(&temp_dir
);
154 base::FilePath app_dir
= temp_dir
.AppendASCII(dirname
);
155 // The directory is leaked, because it can be reused at any time if the same
156 // application is downloaded. Deleting it would be racy. This is only
157 // happening when --predictable-app-filenames is used.
158 bool result
= base::CreateDirectoryAndGetError(app_dir
, nullptr);
160 std::string unique_name
= base::StringPrintf("%s.mojo", app_id
.c_str());
161 *new_path
= app_dir
.AppendASCII(unique_name
);
162 return base::Move(old_path
, *new_path
);
165 void NetworkFetcher::CopyCompleted(
166 base::Callback
<void(const base::FilePath
&, bool)> callback
,
169 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
170 switches::kPredictableAppFilenames
)) {
171 // The copy completed, now move to $TMP/$APP_ID.mojo before the dlopen.
173 base::FilePath new_path
;
174 if (RenameToAppId(url_
, path_
, &new_path
)) {
175 if (base::PathExists(new_path
)) {
184 RecordCacheToURLMapping(path_
, url_
);
186 base::MessageLoop::current()->PostTask(FROM_HERE
,
187 base::Bind(callback
, path_
, success
));
190 void NetworkFetcher::AsPath(
191 base::TaskRunner
* task_runner
,
192 base::Callback
<void(const base::FilePath
&, bool)> callback
) {
193 if (!path_
.empty() || !response_
) {
194 base::MessageLoop::current()->PostTask(
195 FROM_HERE
, base::Bind(callback
, path_
, base::PathExists(path_
)));
199 base::CreateTemporaryFile(&path_
);
200 common::CopyToFile(response_
->body
.Pass(), path_
, task_runner
,
201 base::Bind(&NetworkFetcher::CopyCompleted
,
202 weak_ptr_factory_
.GetWeakPtr(), callback
));
205 std::string
NetworkFetcher::MimeType() {
206 return response_
->mime_type
;
209 bool NetworkFetcher::HasMojoMagic() {
211 return BlockingPeekNBytes(response_
->body
.get(), &magic
, strlen(kMojoMagic
),
216 bool NetworkFetcher::PeekFirstLine(std::string
* line
) {
217 return BlockingPeekLine(response_
->body
.get(), line
, kMaxShebangLength
,
221 void NetworkFetcher::StartNetworkRequest(mojo::URLRequestPtr request
,
222 URLLoaderFactory
* url_loader_factory
) {
223 TRACE_EVENT_ASYNC_BEGIN1("mojo_shell", "NetworkFetcher::NetworkRequest", this,
224 "url", request
->url
.To
<std::string
>());
225 request
->auto_follow_redirects
= false;
226 request
->bypass_cache
= disable_cache_
;
228 url_loader_factory
->CreateURLLoader(GetProxy(&url_loader_
));
229 url_loader_
->Start(request
.Pass(),
230 base::Bind(&NetworkFetcher::OnLoadComplete
,
231 weak_ptr_factory_
.GetWeakPtr()));
234 void NetworkFetcher::OnLoadComplete(URLResponsePtr response
) {
235 TRACE_EVENT_ASYNC_END0("mojo_shell", "NetworkFetcher::NetworkRequest", this);
236 scoped_ptr
<Fetcher
> owner(this);
237 if (response
->error
) {
238 LOG(ERROR
) << "Error (" << response
->error
->code
<< ": "
239 << response
->error
->description
<< ") while fetching "
241 loader_callback_
.Run(nullptr);
245 if (response
->status_code
>= 400 && response
->status_code
< 600) {
246 LOG(ERROR
) << "Error (" << response
->status_code
<< ": "
247 << response
->status_line
<< "): "
248 << "while fetching " << response
->url
;
249 loader_callback_
.Run(nullptr);
253 response_
= response
.Pass();
254 loader_callback_
.Run(owner
.Pass());