OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2017 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 "content/browser/blob_storage/blob_url_loader_factory.h" | |
6 | |
7 #include <stddef.h> | |
8 #include "base/bind.h" | |
9 #include "base/logging.h" | |
10 #include "base/macros.h" | |
11 #include "base/memory/weak_ptr.h" | |
12 #include "base/threading/thread_task_runner_handle.h" | |
13 #include "content/browser/blob_storage/chrome_blob_storage_context.h" | |
14 #include "content/browser/storage_partition_impl.h" | |
15 #include "content/common/net_adapters.h" | |
16 #include "content/common/url_loader.mojom.h" | |
17 #include "content/public/browser/browser_thread.h" | |
18 #include "mojo/public/cpp/system/simple_watcher.h" | |
19 #include "net/base/io_buffer.h" | |
20 #include "net/http/http_byte_range.h" | |
21 #include "net/http/http_request_headers.h" | |
22 #include "net/http/http_response_headers.h" | |
23 #include "net/http/http_status_code.h" | |
24 #include "net/http/http_util.h" | |
25 #include "storage/browser/blob/blob_data_handle.h" | |
26 #include "storage/browser/blob/blob_reader.h" | |
27 #include "storage/browser/blob/blob_storage_context.h" | |
28 #include "storage/browser/blob/blob_url_request_job.h" | |
29 #include "storage/browser/fileapi/file_system_context.h" | |
30 | |
31 namespace content { | |
32 | |
33 namespace { | |
34 constexpr size_t kDefaultAllocationSize = 512 * 1024; | |
35 | |
36 // Note: some of this code is duplicated from storage::BlobURLRequestJob. | |
kinuko
2017/05/30 06:27:32
Could you also add a short comment about the lifet
jam
2017/05/30 15:54:18
Done.
| |
37 class BlobURLLoader : public mojom::URLLoader { | |
38 public: | |
39 BlobURLLoader(mojom::URLLoaderRequest url_loader_request, | |
40 const ResourceRequest& request, | |
41 mojom::URLLoaderClientPtr client, | |
42 storage::BlobStorageContext* blob_storage_context, | |
43 storage::FileSystemContext* file_system_context) | |
44 : binding_(this, std::move(url_loader_request)), | |
45 request_(request), | |
46 client_(std::move(client)), | |
47 byte_range_set_(false), | |
48 writable_handle_watcher_(FROM_HERE, | |
49 mojo::SimpleWatcher::ArmingPolicy::MANUAL), | |
50 peer_closed_handle_watcher_(FROM_HERE, | |
51 mojo::SimpleWatcher::ArmingPolicy::MANUAL), | |
52 weak_factory_(this) { | |
53 DCHECK_CURRENTLY_ON(BrowserThread::IO); | |
54 blob_handle_ = blob_storage_context->GetBlobDataFromPublicURL(request.url); | |
55 | |
56 // PostTask since it might destruct. | |
57 base::ThreadTaskRunnerHandle::Get()->PostTask( | |
58 FROM_HERE, | |
59 base::Bind(&BlobURLLoader::Start, weak_factory_.GetWeakPtr(), request, | |
60 make_scoped_refptr(file_system_context))); | |
61 } | |
62 | |
63 void Start(const ResourceRequest& request, | |
64 scoped_refptr<storage::FileSystemContext> file_system_context) { | |
65 if (!blob_handle_) { | |
66 NotifyCompleted(net::ERR_FILE_NOT_FOUND); | |
67 return; | |
68 } | |
69 | |
70 base::SequencedTaskRunner* file_task_runner = | |
71 BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get(); | |
72 blob_reader_ = | |
73 blob_handle_->CreateReader(file_system_context.get(), file_task_runner); | |
74 | |
75 // We only support GET request per the spec. | |
76 if (request.method != "GET") { | |
77 NotifyCompleted(net::ERR_METHOD_NOT_SUPPORTED); | |
78 return; | |
79 } | |
80 | |
81 if (blob_reader_->net_error()) { | |
82 NotifyCompleted(blob_reader_->net_error()); | |
83 return; | |
84 } | |
85 | |
86 net::HttpRequestHeaders request_headers; | |
87 request_headers.AddHeadersFromString(request.headers); | |
88 std::string range_header; | |
89 if (request_headers.GetHeader(net::HttpRequestHeaders::kRange, | |
90 &range_header)) { | |
91 // We only care about "Range" header here. | |
92 std::vector<net::HttpByteRange> ranges; | |
93 if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) { | |
94 if (ranges.size() == 1) { | |
95 byte_range_set_ = true; | |
96 byte_range_ = ranges[0]; | |
97 } else { | |
98 // We don't support multiple range requests in one single URL request, | |
99 // because we need to do multipart encoding here. | |
100 // TODO(jianli): Support multipart byte range requests. | |
101 NotifyCompleted(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE); | |
102 } | |
103 } | |
104 } | |
105 | |
106 storage::BlobReader::Status size_status = | |
107 blob_reader_->CalculateSize(base::Bind(&BlobURLLoader::DidCalculateSize, | |
108 weak_factory_.GetWeakPtr())); | |
109 switch (size_status) { | |
110 case storage::BlobReader::Status::NET_ERROR: | |
111 NotifyCompleted(blob_reader_->net_error()); | |
112 return; | |
113 case storage::BlobReader::Status::IO_PENDING: | |
114 return; | |
115 case storage::BlobReader::Status::DONE: | |
116 DidCalculateSize(net::OK); | |
117 return; | |
118 } | |
kinuko
2017/05/30 06:27:32
nit: NOTREACHED() here
jam
2017/05/30 15:54:18
Done.
| |
119 } | |
120 | |
121 ~BlobURLLoader() override {} | |
122 | |
123 private: | |
124 // mojom::URLLoader implementation: | |
125 void FollowRedirect() override { NOTREACHED(); } | |
126 | |
127 void SetPriority(net::RequestPriority priority, | |
128 int32_t intra_priority_value) override {} | |
129 | |
130 void NotifyCompleted(int error_code) { | |
131 ResourceRequestCompletionStatus request_complete_data; | |
132 request_complete_data.error_code = error_code; | |
133 client_->OnComplete(request_complete_data); | |
134 | |
135 DeleteIfNeeded(); | |
136 } | |
137 | |
138 void DidCalculateSize(int result) { | |
139 if (result != net::OK) { | |
140 NotifyCompleted(result); | |
141 return; | |
142 } | |
143 | |
144 // Apply the range requirement. | |
145 if (!byte_range_.ComputeBounds(blob_reader_->total_size())) { | |
146 NotifyCompleted(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE); | |
147 return; | |
148 } | |
149 | |
150 DCHECK_LE(byte_range_.first_byte_position(), | |
151 byte_range_.last_byte_position() + 1); | |
152 uint64_t length = | |
153 base::checked_cast<uint64_t>(byte_range_.last_byte_position() - | |
154 byte_range_.first_byte_position() + 1); | |
155 | |
156 if (byte_range_set_) | |
157 blob_reader_->SetReadRange(byte_range_.first_byte_position(), length); | |
158 | |
159 net::HttpStatusCode status_code = net::HTTP_OK; | |
160 if (byte_range_set_ && byte_range_.IsValid()) { | |
161 status_code = net::HTTP_PARTIAL_CONTENT; | |
162 } else { | |
163 // TODO(horo): When the requester doesn't need the side data | |
164 // (ex:FileReader) we should skip reading the side data. | |
165 if (blob_reader_->has_side_data() && | |
166 blob_reader_->ReadSideData(base::Bind(&BlobURLLoader::DidReadMetadata, | |
167 weak_factory_.GetWeakPtr())) == | |
168 storage::BlobReader::Status::IO_PENDING) { | |
169 return; | |
170 } | |
171 } | |
172 | |
173 HeadersCompleted(status_code); | |
174 } | |
175 | |
176 void DidReadMetadata(storage::BlobReader::Status result) { | |
177 if (result != storage::BlobReader::Status::DONE) { | |
178 NotifyCompleted(blob_reader_->net_error()); | |
179 return; | |
180 } | |
181 HeadersCompleted(net::HTTP_OK); | |
182 } | |
183 | |
184 void HeadersCompleted(net::HttpStatusCode status_code) { | |
185 ResourceResponseHead response; | |
186 response.content_length = 0; | |
187 response.headers = storage::BlobURLRequestJob::GenerateHeaders( | |
188 status_code, blob_handle_.get(), blob_reader_.get(), &byte_range_, | |
189 &response.content_length); | |
190 | |
191 std::string mime_type; | |
192 response.headers->GetMimeType(&mime_type); | |
193 // Match logic in StreamURLRequestJob::HeadersCompleted. | |
194 if (mime_type.empty()) | |
195 mime_type = "text/plain"; | |
196 response.mime_type = mime_type; | |
197 | |
198 // TODO(jam): some of this code can be shared with | |
199 // content/network/url_loader_impl.h | |
200 client_->OnReceiveResponse(response, base::nullopt, nullptr); | |
201 | |
202 net::IOBufferWithSize* metadata = blob_reader_->side_data(); | |
203 if (metadata) { | |
204 const uint8_t* data = reinterpret_cast<const uint8_t*>(metadata->data()); | |
205 client_->OnReceiveCachedMetadata( | |
206 std::vector<uint8_t>(data, data + metadata->size())); | |
207 } | |
208 | |
209 mojo::DataPipe data_pipe(kDefaultAllocationSize); | |
210 response_body_stream_ = std::move(data_pipe.producer_handle); | |
211 response_body_consumer_handle_ = std::move(data_pipe.consumer_handle); | |
212 peer_closed_handle_watcher_.Watch( | |
213 response_body_stream_.get(), MOJO_HANDLE_SIGNAL_PEER_CLOSED, | |
214 base::Bind(&BlobURLLoader::OnResponseBodyStreamClosed, | |
215 base::Unretained(this))); | |
216 peer_closed_handle_watcher_.ArmOrNotify(); | |
217 | |
218 writable_handle_watcher_.Watch( | |
219 response_body_stream_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, | |
220 base::Bind(&BlobURLLoader::OnResponseBodyStreamReady, | |
221 base::Unretained(this))); | |
222 | |
223 // Start reading... | |
224 ReadMore(); | |
225 } | |
226 | |
227 void ReadMore() { | |
228 DCHECK(!pending_write_.get()); | |
229 | |
230 uint32_t num_bytes; | |
231 // TODO: we should use the abstractions in MojoAsyncResourceHandler. | |
232 MojoResult result = NetToMojoPendingBuffer::BeginWrite( | |
233 &response_body_stream_, &pending_write_, &num_bytes); | |
234 if (result == MOJO_RESULT_SHOULD_WAIT) { | |
235 // The pipe is full. We need to wait for it to have more space. | |
236 writable_handle_watcher_.ArmOrNotify(); | |
237 return; | |
238 } else if (result != MOJO_RESULT_OK) { | |
239 // The response body stream is in a bad state. Bail. | |
240 writable_handle_watcher_.Cancel(); | |
241 response_body_stream_.reset(); | |
242 NotifyCompleted(net::ERR_UNEXPECTED); | |
kinuko
2017/05/30 06:27:32
return here
jam
2017/05/30 15:54:18
Done.
| |
243 } | |
244 | |
245 CHECK_GT(static_cast<uint32_t>(std::numeric_limits<int>::max()), num_bytes); | |
246 scoped_refptr<net::IOBuffer> buf( | |
247 new NetToMojoIOBuffer(pending_write_.get())); | |
248 int bytes_read; | |
249 storage::BlobReader::Status read_status = blob_reader_->Read( | |
250 buf.get(), static_cast<int>(num_bytes), &bytes_read, | |
251 base::Bind(&BlobURLLoader::DidRead, weak_factory_.GetWeakPtr(), false)); | |
252 switch (read_status) { | |
253 case storage::BlobReader::Status::NET_ERROR: | |
254 NotifyCompleted(blob_reader_->net_error()); | |
255 return; | |
256 case storage::BlobReader::Status::IO_PENDING: | |
257 // Wait for DidRead. | |
258 return; | |
259 case storage::BlobReader::Status::DONE: | |
260 if (bytes_read > 0) { | |
261 DidRead(true, bytes_read); | |
262 } else { | |
263 writable_handle_watcher_.Cancel(); | |
264 pending_write_->Complete(0); | |
265 pending_write_ = nullptr; // This closes the data pipe. | |
266 NotifyCompleted(net::OK); | |
267 return; | |
268 } | |
269 } | |
270 } | |
271 | |
272 void DidRead(bool completed_synchronously, int num_bytes) { | |
273 if (response_body_consumer_handle_.is_valid()) { | |
274 // Send the data pipe on the first OnReadCompleted call. | |
275 client_->OnStartLoadingResponseBody( | |
276 std::move(response_body_consumer_handle_)); | |
277 } | |
278 response_body_stream_ = pending_write_->Complete(num_bytes); | |
279 pending_write_ = nullptr; | |
280 if (completed_synchronously) { | |
281 base::ThreadTaskRunnerHandle::Get()->PostTask( | |
282 FROM_HERE, | |
283 base::Bind(&BlobURLLoader::ReadMore, weak_factory_.GetWeakPtr())); | |
284 } else { | |
285 ReadMore(); | |
286 } | |
287 } | |
288 | |
289 void OnResponseBodyStreamClosed(MojoResult result) { | |
290 response_body_stream_.reset(); | |
291 pending_write_ = nullptr; | |
292 DeleteIfNeeded(); | |
293 } | |
294 | |
295 void OnResponseBodyStreamReady(MojoResult result) { | |
296 // TODO: Handle a bad |result| value. | |
297 DCHECK_EQ(result, MOJO_RESULT_OK); | |
298 ReadMore(); | |
299 } | |
300 | |
301 void DeleteIfNeeded() { | |
302 bool has_data_pipe = | |
303 pending_write_.get() || response_body_stream_.is_valid(); | |
304 if (!has_data_pipe) | |
305 delete this; | |
306 } | |
307 | |
308 mojo::Binding<mojom::URLLoader> binding_; | |
309 ResourceRequest request_; | |
310 mojom::URLLoaderClientPtr client_; | |
311 | |
312 bool byte_range_set_; | |
313 net::HttpByteRange byte_range_; | |
314 | |
315 std::unique_ptr<storage::BlobDataHandle> blob_handle_; | |
316 std::unique_ptr<storage::BlobReader> blob_reader_; | |
317 | |
318 // TODO(jam): share with URLLoaderImpl | |
319 mojo::ScopedDataPipeProducerHandle response_body_stream_; | |
320 mojo::ScopedDataPipeConsumerHandle response_body_consumer_handle_; | |
321 scoped_refptr<NetToMojoPendingBuffer> pending_write_; | |
322 mojo::SimpleWatcher writable_handle_watcher_; | |
323 mojo::SimpleWatcher peer_closed_handle_watcher_; | |
324 | |
325 base::WeakPtrFactory<BlobURLLoader> weak_factory_; | |
326 | |
327 DISALLOW_COPY_AND_ASSIGN(BlobURLLoader); | |
328 }; | |
329 | |
330 } // namespace | |
331 | |
332 BlobURLLoaderFactory::BlobURLLoaderFactory( | |
333 StoragePartitionImpl* storage_partition) | |
334 : blob_storage_context_(ChromeBlobStorageContext::GetFor( | |
335 storage_partition->browser_context())), | |
336 file_system_context_(storage_partition->GetFileSystemContext()) { | |
337 DCHECK_CURRENTLY_ON(BrowserThread::UI); | |
338 } | |
339 | |
340 mojom::URLLoaderFactoryPtr BlobURLLoaderFactory::CreateFactory() { | |
341 DCHECK_CURRENTLY_ON(BrowserThread::UI); | |
342 mojom::URLLoaderFactoryPtr factory; | |
343 mojom::URLLoaderFactoryRequest request = mojo::MakeRequest(&factory); | |
344 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, | |
345 base::BindOnce(&BlobURLLoaderFactory::BindOnIO, this, | |
346 std::move(request))); | |
347 | |
348 return factory; | |
349 } | |
350 | |
351 BlobURLLoaderFactory::~BlobURLLoaderFactory() {} | |
352 | |
353 void BlobURLLoaderFactory::BindOnIO(mojom::URLLoaderFactoryRequest request) { | |
354 DCHECK_CURRENTLY_ON(BrowserThread::IO); | |
355 | |
356 loader_factory_bindings_.AddBinding(this, std::move(request)); | |
357 } | |
358 | |
359 void BlobURLLoaderFactory::CreateLoaderAndStart( | |
360 mojom::URLLoaderRequest loader, | |
361 int32_t routing_id, | |
362 int32_t request_id, | |
363 uint32_t options, | |
364 const ResourceRequest& request, | |
365 mojom::URLLoaderClientPtr client) { | |
366 DCHECK_CURRENTLY_ON(BrowserThread::IO); | |
367 new BlobURLLoader(std::move(loader), request, std::move(client), | |
368 blob_storage_context_->context(), | |
369 file_system_context_.get()); | |
370 } | |
371 | |
372 void BlobURLLoaderFactory::SyncLoad(int32_t routing_id, | |
373 int32_t request_id, | |
374 const ResourceRequest& request, | |
375 SyncLoadCallback callback) { | |
376 NOTREACHED(); | |
377 } | |
378 | |
379 } // namespace content | |
OLD | NEW |