OLD | NEW |
---|---|
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "content/browser/loader/redirect_to_file_resource_handler.h" | 5 #include "content/browser/loader/redirect_to_file_resource_handler.h" |
6 | 6 |
7 #include "base/bind.h" | 7 #include "base/bind.h" |
8 #include "base/files/file_util_proxy.h" | |
9 #include "base/logging.h" | 8 #include "base/logging.h" |
10 #include "base/message_loop/message_loop_proxy.h" | |
11 #include "base/platform_file.h" | 9 #include "base/platform_file.h" |
12 #include "base/threading/thread_restrictions.h" | 10 #include "base/threading/thread_restrictions.h" |
13 #include "content/browser/loader/resource_dispatcher_host_impl.h" | |
14 #include "content/browser/loader/resource_request_info_impl.h" | 11 #include "content/browser/loader/resource_request_info_impl.h" |
15 #include "content/public/browser/browser_thread.h" | 12 #include "content/public/browser/resource_controller.h" |
16 #include "content/public/common/resource_response.h" | 13 #include "content/public/common/resource_response.h" |
17 #include "net/base/file_stream.h" | 14 #include "net/base/file_stream.h" |
18 #include "net/base/io_buffer.h" | 15 #include "net/base/io_buffer.h" |
19 #include "net/base/mime_sniffer.h" | 16 #include "net/base/mime_sniffer.h" |
20 #include "net/base/net_errors.h" | 17 #include "net/base/net_errors.h" |
21 #include "webkit/common/blob/shareable_file_reference.h" | 18 #include "webkit/common/blob/shareable_file_reference.h" |
22 | 19 |
23 using webkit_blob::ShareableFileReference; | 20 using webkit_blob::ShareableFileReference; |
24 | 21 |
25 namespace { | 22 namespace { |
(...skipping 20 matching lines...) Expand all Loading... | |
46 scoped_refptr<net::IOBuffer> backing_; | 43 scoped_refptr<net::IOBuffer> backing_; |
47 }; | 44 }; |
48 | 45 |
49 } // namespace | 46 } // namespace |
50 | 47 |
51 namespace content { | 48 namespace content { |
52 | 49 |
53 static const int kInitialReadBufSize = 32768; | 50 static const int kInitialReadBufSize = 32768; |
54 static const int kMaxReadBufSize = 524288; | 51 static const int kMaxReadBufSize = 524288; |
55 | 52 |
53 // A separate object to manage the lifetime of the net::FileStream and the | |
54 // ShareableFileReference. When the handler is destroyed, it asynchronously | |
55 // closes net::FileStream after all pending writes complete. Only after the | |
56 // stream is closed is the ShareableFileReference released, to ensure the | |
57 // temporary is not deleted before it is closed. | |
58 class RedirectToFileResourceHandler::Writer { | |
59 public: | |
60 Writer(RedirectToFileResourceHandler* handler, | |
61 scoped_ptr<net::FileStream> file_stream, | |
62 ShareableFileReference* deletable_file) | |
63 : handler_(handler), | |
64 file_stream_(file_stream.Pass()), | |
65 write_callback_pending_(false), | |
66 deletable_file_(deletable_file) { | |
67 } | |
68 | |
69 bool write_callback_pending() const { return write_callback_pending_; } | |
70 const base::FilePath& path() const { return deletable_file_->path(); } | |
71 | |
72 int Write(net::IOBuffer* buf, int buf_len) { | |
73 DCHECK(!write_callback_pending_); | |
74 DCHECK(handler_); | |
75 int result = file_stream_->Write( | |
76 buf, buf_len, | |
77 base::Bind(&Writer::DidWriteToFile, base::Unretained(this))); | |
78 if (result == net::ERR_IO_PENDING) | |
79 write_callback_pending_ = true; | |
80 return result; | |
81 } | |
82 | |
83 void Close() { | |
84 handler_ = NULL; | |
85 if (!write_callback_pending_) | |
86 CloseAndDelete(); | |
87 } | |
88 | |
89 private: | |
90 // Only DidClose can delete this. | |
91 ~Writer() { | |
92 } | |
93 | |
94 void DidWriteToFile(int result) { | |
95 DCHECK(write_callback_pending_); | |
96 write_callback_pending_ = false; | |
97 if (handler_) { | |
98 handler_->DidWriteToFile(result); | |
99 } else { | |
100 CloseAndDelete(); | |
101 } | |
102 } | |
103 | |
104 void CloseAndDelete() { | |
105 DCHECK(!write_callback_pending_); | |
106 int result = file_stream_->Close(base::Bind(&Writer::DidClose, | |
107 base::Unretained(this))); | |
108 if (result != net::ERR_IO_PENDING) | |
109 DidClose(result); | |
110 } | |
111 | |
112 void DidClose(int result) { | |
113 delete this; | |
114 } | |
115 | |
116 RedirectToFileResourceHandler* handler_; | |
117 | |
118 scoped_ptr<net::FileStream> file_stream_; | |
119 bool write_callback_pending_; | |
120 | |
121 // We create a ShareableFileReference that's deletable for the temp file | |
122 // created as a result of the download. | |
123 scoped_refptr<webkit_blob::ShareableFileReference> deletable_file_; | |
124 | |
125 DISALLOW_COPY_AND_ASSIGN(Writer); | |
126 }; | |
127 | |
56 RedirectToFileResourceHandler::RedirectToFileResourceHandler( | 128 RedirectToFileResourceHandler::RedirectToFileResourceHandler( |
57 scoped_ptr<ResourceHandler> next_handler, | 129 scoped_ptr<ResourceHandler> next_handler, |
58 net::URLRequest* request, | 130 net::URLRequest* request, |
59 ResourceDispatcherHostImpl* host) | 131 const RedirectToFileResourceHandler::CreateTemporaryCB& create_temporary_cb) |
60 : LayeredResourceHandler(request, next_handler.Pass()), | 132 : LayeredResourceHandler(request, next_handler.Pass()), |
61 weak_factory_(this), | 133 create_temporary_cb_(create_temporary_cb), |
62 host_(host), | |
63 buf_(new net::GrowableIOBuffer()), | 134 buf_(new net::GrowableIOBuffer()), |
64 buf_write_pending_(false), | 135 buf_write_pending_(false), |
65 write_cursor_(0), | 136 write_cursor_(0), |
66 write_callback_pending_(false), | 137 writer_(NULL), |
67 next_buffer_size_(kInitialReadBufSize), | 138 next_buffer_size_(kInitialReadBufSize), |
68 did_defer_(false), | 139 did_defer_(false), |
69 completed_during_write_(false) { | 140 completed_during_write_(false), |
141 weak_factory_(this) { | |
70 } | 142 } |
71 | 143 |
72 RedirectToFileResourceHandler::~RedirectToFileResourceHandler() { | 144 RedirectToFileResourceHandler::~RedirectToFileResourceHandler() { |
145 // Orphan the writer to asynchronously close and release the temporary file. | |
146 if (writer_) { | |
147 writer_->Close(); | |
148 writer_ = NULL; | |
149 } | |
73 } | 150 } |
74 | 151 |
75 bool RedirectToFileResourceHandler::OnResponseStarted( | 152 bool RedirectToFileResourceHandler::OnResponseStarted( |
76 int request_id, | 153 int request_id, |
77 ResourceResponse* response, | 154 ResourceResponse* response, |
78 bool* defer) { | 155 bool* defer) { |
79 if (response->head.error_code == net::OK || | 156 if (response->head.error_code == net::OK || |
80 response->head.error_code == net::ERR_IO_PENDING) { | 157 response->head.error_code == net::ERR_IO_PENDING) { |
81 DCHECK(deletable_file_.get() && !deletable_file_->path().empty()); | 158 DCHECK(writer_); |
82 response->head.download_file_path = deletable_file_->path(); | 159 DCHECK(!writer_->path().empty()); |
160 response->head.download_file_path = writer_->path(); | |
83 } | 161 } |
84 return next_handler_->OnResponseStarted(request_id, response, defer); | 162 return next_handler_->OnResponseStarted(request_id, response, defer); |
85 } | 163 } |
86 | 164 |
87 bool RedirectToFileResourceHandler::OnWillStart(int request_id, | 165 bool RedirectToFileResourceHandler::OnWillStart(int request_id, |
88 const GURL& url, | 166 const GURL& url, |
89 bool* defer) { | 167 bool* defer) { |
90 if (!deletable_file_.get()) { | 168 DCHECK(!writer_); |
91 // Defer starting the request until we have created the temporary file. | 169 |
92 // TODO(darin): This is sub-optimal. We should not delay starting the | 170 // Defer starting the request until we have created the temporary file. |
93 // network request like this. | 171 // TODO(darin): This is sub-optimal. We should not delay starting the |
94 did_defer_ = *defer = true; | 172 // network request like this. |
95 base::FileUtilProxy::CreateTemporary( | 173 will_start_url_ = url; |
96 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get(), | 174 did_defer_ = *defer = true; |
97 base::PLATFORM_FILE_ASYNC, | 175 create_temporary_cb_.Run( |
98 base::Bind(&RedirectToFileResourceHandler::DidCreateTemporaryFile, | 176 base::Bind(&RedirectToFileResourceHandler::DidCreateTemporaryFile, |
99 weak_factory_.GetWeakPtr())); | 177 weak_factory_.GetWeakPtr())); |
100 return true; | 178 return true; |
101 } | |
102 return next_handler_->OnWillStart(request_id, url, defer); | |
103 } | 179 } |
104 | 180 |
105 bool RedirectToFileResourceHandler::OnWillRead( | 181 bool RedirectToFileResourceHandler::OnWillRead( |
106 int request_id, | 182 int request_id, |
107 scoped_refptr<net::IOBuffer>* buf, | 183 scoped_refptr<net::IOBuffer>* buf, |
108 int* buf_size, | 184 int* buf_size, |
109 int min_size) { | 185 int min_size) { |
110 DCHECK_EQ(-1, min_size); | 186 DCHECK_EQ(-1, min_size); |
111 | 187 |
112 if (buf_->capacity() < next_buffer_size_) | 188 if (buf_->capacity() < next_buffer_size_) |
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
144 } | 220 } |
145 | 221 |
146 return WriteMore(); | 222 return WriteMore(); |
147 } | 223 } |
148 | 224 |
149 void RedirectToFileResourceHandler::OnResponseCompleted( | 225 void RedirectToFileResourceHandler::OnResponseCompleted( |
150 int request_id, | 226 int request_id, |
151 const net::URLRequestStatus& status, | 227 const net::URLRequestStatus& status, |
152 const std::string& security_info, | 228 const std::string& security_info, |
153 bool* defer) { | 229 bool* defer) { |
154 if (write_callback_pending_) { | 230 if (writer_ && writer_->write_callback_pending()) { |
mmenke
2014/01/16 16:43:26
How can writer be NULL here? Cancellation while w
davidben
2014/01/29 21:41:50
Yeah, that's the NULL case. The temporary in this
| |
155 completed_during_write_ = true; | 231 completed_during_write_ = true; |
156 completed_status_ = status; | 232 completed_status_ = status; |
157 completed_security_info_ = security_info; | 233 completed_security_info_ = security_info; |
158 did_defer_ = true; | 234 did_defer_ = true; |
159 *defer = true; | 235 *defer = true; |
160 return; | 236 return; |
161 } | 237 } |
162 next_handler_->OnResponseCompleted(request_id, status, security_info, defer); | 238 next_handler_->OnResponseCompleted(request_id, status, security_info, defer); |
163 } | 239 } |
164 | 240 |
165 void RedirectToFileResourceHandler::DidCreateTemporaryFile( | 241 void RedirectToFileResourceHandler::DidCreateTemporaryFile( |
166 base::PlatformFileError /*error_code*/, | 242 base::PlatformFileError error_code, |
167 base::PassPlatformFile file_handle, | 243 scoped_ptr<net::FileStream> file_stream, |
168 const base::FilePath& file_path) { | 244 ShareableFileReference* deletable_file) { |
169 deletable_file_ = ShareableFileReference::GetOrCreate( | 245 DCHECK(!writer_); |
170 file_path, | 246 if (error_code != base::PLATFORM_FILE_OK) { |
171 ShareableFileReference::DELETE_ON_FINAL_RELEASE, | 247 controller()->CancelWithError(net::PlatformFileErrorToNetError(error_code)); |
172 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get()); | 248 return; |
173 file_stream_.reset( | 249 } |
174 new net::FileStream(file_handle.ReleaseValue(), | 250 |
175 base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_ASYNC, | 251 writer_ = new Writer(this, file_stream.Pass(), deletable_file); |
176 NULL)); | 252 |
177 const ResourceRequestInfo* info = GetRequestInfo(); | 253 // Resume the request. |
178 host_->RegisterDownloadedTempFile( | 254 bool defer = false; |
179 info->GetChildID(), info->GetRequestID(), deletable_file_.get()); | 255 if (!next_handler_->OnWillStart(GetRequestID(), will_start_url_, &defer)) { |
180 ResumeIfDeferred(); | 256 controller()->Cancel(); |
257 } else if (!defer) { | |
258 ResumeIfDeferred(); | |
259 } | |
260 will_start_url_ = GURL(); | |
181 } | 261 } |
182 | 262 |
183 void RedirectToFileResourceHandler::DidWriteToFile(int result) { | 263 void RedirectToFileResourceHandler::DidWriteToFile(int result) { |
184 write_callback_pending_ = false; | |
185 int request_id = GetRequestID(); | 264 int request_id = GetRequestID(); |
186 | 265 |
187 bool failed = false; | 266 bool failed = false; |
188 if (result > 0) { | 267 if (result > 0) { |
189 next_handler_->OnDataDownloaded(request_id, result); | 268 next_handler_->OnDataDownloaded(request_id, result); |
190 write_cursor_ += result; | 269 write_cursor_ += result; |
191 failed = !WriteMore(); | 270 failed = !WriteMore(); |
192 } else { | 271 } else { |
193 failed = true; | 272 failed = true; |
194 } | 273 } |
195 | 274 |
196 if (failed) { | 275 if (failed) { |
mmenke
2014/01/16 16:43:26
Maybe throw in a "DCHECK(!writer_->write_callback_
davidben
2014/01/29 21:41:50
Done.
| |
197 ResumeIfDeferred(); | 276 // TODO(davidben): Recover the error code from WriteMore or |result|, as |
198 } else if (completed_during_write_) { | 277 // appropriate. |
278 if (completed_during_write_ && completed_status_.is_success()) { | |
279 // If the request successfully completed mid-write, but the write failed, | |
280 // convert the status to a failure for downstream. | |
281 completed_status_.set_status(net::URLRequestStatus::CANCELED); | |
282 completed_status_.set_error(net::ERR_FAILED); | |
283 } | |
284 controller()->CancelWithError(net::ERR_FAILED); | |
285 } | |
286 | |
287 if (completed_during_write_ && !writer_->write_callback_pending()) { | |
288 // Resume shutdown now that all data has been written to disk. Note that | |
289 // this should run even in the |failed| case above, otherwise a failed write | |
290 // leaves the handler stuck. | |
199 bool defer = false; | 291 bool defer = false; |
200 next_handler_->OnResponseCompleted(request_id, | 292 next_handler_->OnResponseCompleted(request_id, |
201 completed_status_, | 293 completed_status_, |
202 completed_security_info_, | 294 completed_security_info_, |
203 &defer); | 295 &defer); |
204 if (!defer) | 296 if (!defer) |
205 ResumeIfDeferred(); | 297 ResumeIfDeferred(); |
206 } | 298 } |
207 } | 299 } |
208 | 300 |
209 bool RedirectToFileResourceHandler::WriteMore() { | 301 bool RedirectToFileResourceHandler::WriteMore() { |
210 DCHECK(file_stream_.get()); | 302 DCHECK(writer_); |
211 for (;;) { | 303 for (;;) { |
212 if (write_cursor_ == buf_->offset()) { | 304 if (write_cursor_ == buf_->offset()) { |
213 // We've caught up to the network load, but it may be in the process of | 305 // We've caught up to the network load, but it may be in the process of |
214 // appending more data to the buffer. | 306 // appending more data to the buffer. |
215 if (!buf_write_pending_) { | 307 if (!buf_write_pending_) { |
216 if (BufIsFull()) | 308 if (BufIsFull()) |
217 ResumeIfDeferred(); | 309 ResumeIfDeferred(); |
218 buf_->set_offset(0); | 310 buf_->set_offset(0); |
219 write_cursor_ = 0; | 311 write_cursor_ = 0; |
mmenke
2014/01/16 16:43:26
Random comment: Is it just me, or does this seem
davidben
2014/01/29 21:41:50
Hrm. Well, the assumption is true right now. I sup
| |
220 } | 312 } |
221 return true; | 313 return true; |
222 } | 314 } |
223 if (write_callback_pending_) | 315 if (writer_->write_callback_pending()) |
224 return true; | 316 return true; |
225 DCHECK(write_cursor_ < buf_->offset()); | 317 DCHECK(write_cursor_ < buf_->offset()); |
226 | 318 |
227 // Create a temporary buffer pointing to a subsection of the data buffer so | 319 // Create a temporary buffer pointing to a subsection of the data buffer so |
228 // that it can be passed to Write. This code makes some crazy scary | 320 // that it can be passed to Write. This code makes some crazy scary |
229 // assumptions about object lifetimes, thread sharing, and that buf_ will | 321 // assumptions about object lifetimes, thread sharing, and that buf_ will |
230 // not realloc durring the write due to how the state machine in this class | 322 // not realloc durring the write due to how the state machine in this class |
231 // works. | 323 // works. |
232 // Note that buf_ is also shared with the code that writes data into the | 324 // Note that buf_ is also shared with the code that writes data into the |
233 // cache, so modifying it can cause some pretty subtle race conditions: | 325 // cache, so modifying it can cause some pretty subtle race conditions: |
234 // https://code.google.com/p/chromium/issues/detail?id=152076 | 326 // https://code.google.com/p/chromium/issues/detail?id=152076 |
235 // We're using DependentIOBuffer instead of DrainableIOBuffer to dodge some | 327 // We're using DependentIOBuffer instead of DrainableIOBuffer to dodge some |
236 // of these issues, for the moment. | 328 // of these issues, for the moment. |
237 // TODO(ncbray) make this code less crazy scary. | 329 // TODO(ncbray) make this code less crazy scary. |
238 // Also note that Write may increase the refcount of "wrapped" deep in the | 330 // Also note that Write may increase the refcount of "wrapped" deep in the |
239 // bowels of its implementation, the use of scoped_refptr here is not | 331 // bowels of its implementation, the use of scoped_refptr here is not |
240 // spurious. | 332 // spurious. |
241 scoped_refptr<DependentIOBuffer> wrapped = new DependentIOBuffer( | 333 scoped_refptr<DependentIOBuffer> wrapped = new DependentIOBuffer( |
242 buf_.get(), buf_->StartOfBuffer() + write_cursor_); | 334 buf_.get(), buf_->StartOfBuffer() + write_cursor_); |
243 int write_len = buf_->offset() - write_cursor_; | 335 int write_len = buf_->offset() - write_cursor_; |
244 | 336 |
245 int rv = file_stream_->Write( | 337 int rv = writer_->Write(wrapped.get(), write_len); |
246 wrapped.get(), | 338 if (rv == net::ERR_IO_PENDING) |
247 write_len, | |
248 base::Bind(&RedirectToFileResourceHandler::DidWriteToFile, | |
249 base::Unretained(this))); | |
250 if (rv == net::ERR_IO_PENDING) { | |
251 write_callback_pending_ = true; | |
252 return true; | 339 return true; |
253 } | |
254 if (rv <= 0) | 340 if (rv <= 0) |
255 return false; | 341 return false; |
256 next_handler_->OnDataDownloaded(GetRequestID(), rv); | 342 next_handler_->OnDataDownloaded(GetRequestID(), rv); |
257 write_cursor_ += rv; | 343 write_cursor_ += rv; |
258 } | 344 } |
259 } | 345 } |
260 | 346 |
261 bool RedirectToFileResourceHandler::BufIsFull() const { | 347 bool RedirectToFileResourceHandler::BufIsFull() const { |
262 // This is a hack to workaround BufferedResourceHandler's inability to | 348 // This is a hack to workaround BufferedResourceHandler's inability to |
263 // deal with a ResourceHandler that returns a buffer size of less than | 349 // deal with a ResourceHandler that returns a buffer size of less than |
264 // 2 * net::kMaxBytesToSniff from its OnWillRead method. | 350 // 2 * net::kMaxBytesToSniff from its OnWillRead method. |
265 // TODO(darin): Fix this retardation! | 351 // TODO(darin): Fix this retardation! |
266 return buf_->RemainingCapacity() <= (2 * net::kMaxBytesToSniff); | 352 return buf_->RemainingCapacity() <= (2 * net::kMaxBytesToSniff); |
267 } | 353 } |
268 | 354 |
269 void RedirectToFileResourceHandler::ResumeIfDeferred() { | 355 void RedirectToFileResourceHandler::ResumeIfDeferred() { |
270 if (did_defer_) { | 356 if (did_defer_) { |
271 did_defer_ = false; | 357 did_defer_ = false; |
272 controller()->Resume(); | 358 controller()->Resume(); |
273 } | 359 } |
274 } | 360 } |
275 | 361 |
276 } // namespace content | 362 } // namespace content |
OLD | NEW |