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