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