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