Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(642)

Side by Side Diff: content/browser/loader/redirect_to_file_resource_handler.cc

Issue 82273002: Fix various issues in RedirectToFileResourceHandler. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase, address mmenke comments. Created 6 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
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
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 object to manage the lifetime of the net::FileStream and the
55 // 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 write_callback_pending_(false),
67 deletable_file_(deletable_file) {
68 }
69
70 bool write_callback_pending() const { return write_callback_pending_; }
71 const base::FilePath& path() const { return deletable_file_->path(); }
72
73 int Write(net::IOBuffer* buf, int buf_len) {
74 DCHECK(!write_callback_pending_);
75 DCHECK(handler_);
76 int result = file_stream_->Write(
77 buf, buf_len,
78 base::Bind(&Writer::DidWriteToFile, base::Unretained(this)));
79 if (result == net::ERR_IO_PENDING)
80 write_callback_pending_ = true;
81 return result;
82 }
83
84 void Close() {
85 handler_ = NULL;
86 if (!write_callback_pending_)
87 CloseAndDelete();
88 }
89
90 private:
91 // Only DidClose can delete this.
92 ~Writer() {
93 }
94
95 void DidWriteToFile(int result) {
96 DCHECK(write_callback_pending_);
97 write_callback_pending_ = false;
98 if (handler_) {
99 handler_->DidWriteToFile(result);
100 } else {
101 CloseAndDelete();
102 }
103 }
104
105 void CloseAndDelete() {
106 DCHECK(!write_callback_pending_);
107 int result = file_stream_->Close(base::Bind(&Writer::DidClose,
108 base::Unretained(this)));
109 if (result != net::ERR_IO_PENDING)
110 DidClose(result);
111 }
112
113 void DidClose(int result) {
114 delete this;
115 }
116
117 RedirectToFileResourceHandler* handler_;
118
119 scoped_ptr<net::FileStream> file_stream_;
120 bool write_callback_pending_;
121
122 // We create a ShareableFileReference that's deletable for the temp file
123 // created as a result of the download.
124 scoped_refptr<webkit_blob::ShareableFileReference> deletable_file_;
125
126 DISALLOW_COPY_AND_ASSIGN(Writer);
127 };
128
56 RedirectToFileResourceHandler::RedirectToFileResourceHandler( 129 RedirectToFileResourceHandler::RedirectToFileResourceHandler(
57 scoped_ptr<ResourceHandler> next_handler, 130 scoped_ptr<ResourceHandler> next_handler,
58 net::URLRequest* request, 131 net::URLRequest* request)
59 ResourceDispatcherHostImpl* host)
60 : LayeredResourceHandler(request, next_handler.Pass()), 132 : LayeredResourceHandler(request, next_handler.Pass()),
61 weak_factory_(this),
62 host_(host),
63 buf_(new net::GrowableIOBuffer()), 133 buf_(new net::GrowableIOBuffer()),
64 buf_write_pending_(false), 134 buf_write_pending_(false),
65 write_cursor_(0), 135 write_cursor_(0),
66 write_callback_pending_(false), 136 writer_(NULL),
67 next_buffer_size_(kInitialReadBufSize), 137 next_buffer_size_(kInitialReadBufSize),
68 did_defer_(false), 138 did_defer_(false),
69 completed_during_write_(false) { 139 completed_during_write_(false),
140 weak_factory_(this) {
70 } 141 }
71 142
72 RedirectToFileResourceHandler::~RedirectToFileResourceHandler() { 143 RedirectToFileResourceHandler::~RedirectToFileResourceHandler() {
144 // Orphan the writer to asynchronously close and release the temporary file.
145 if (writer_) {
146 writer_->Close();
147 writer_ = NULL;
148 }
149 }
150
151 void RedirectToFileResourceHandler::
152 SetCreateTemporaryFileStreamFunctionForTesting(
153 const CreateTemporaryFileStreamFunction& create_temporary_file_stream) {
154 create_temporary_file_stream_ = create_temporary_file_stream;
73 } 155 }
74 156
75 bool RedirectToFileResourceHandler::OnResponseStarted( 157 bool RedirectToFileResourceHandler::OnResponseStarted(
76 int request_id, 158 int request_id,
77 ResourceResponse* response, 159 ResourceResponse* response,
78 bool* defer) { 160 bool* defer) {
79 if (response->head.error_code == net::OK || 161 if (response->head.error_code == net::OK ||
80 response->head.error_code == net::ERR_IO_PENDING) { 162 response->head.error_code == net::ERR_IO_PENDING) {
81 DCHECK(deletable_file_.get() && !deletable_file_->path().empty()); 163 DCHECK(writer_);
82 response->head.download_file_path = deletable_file_->path(); 164 DCHECK(!writer_->path().empty());
mmenke 2014/02/14 21:52:49 Random comment: Fine to leave as-is, but it's kin
davidben 2014/02/25 20:03:07 Done.
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
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_->write_callback_pending()) {
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 bool defer = false;
179 info->GetChildID(), info->GetRequestID(), deletable_file_.get()); 266 if (!next_handler_->OnWillStart(GetRequestID(), will_start_url_, &defer)) {
180 ResumeIfDeferred(); 267 controller()->Cancel();
268 } else if (!defer) {
269 ResumeIfDeferred();
270 }
mmenke 2014/02/14 21:52:49 Erm...Shouldn't did_defer_ also be set to false if
davidben 2014/02/25 20:03:07 Yeah, I don't think this ResumeIfDeferred() patter
271 will_start_url_ = GURL();
181 } 272 }
182 273
183 void RedirectToFileResourceHandler::DidWriteToFile(int result) { 274 void RedirectToFileResourceHandler::DidWriteToFile(int result) {
184 write_callback_pending_ = false;
185 int request_id = GetRequestID(); 275 int request_id = GetRequestID();
186 276
187 bool failed = false; 277 bool failed = false;
188 if (result > 0) { 278 if (result > 0) {
189 next_handler_->OnDataDownloaded(request_id, result); 279 next_handler_->OnDataDownloaded(request_id, result);
190 write_cursor_ += result; 280 write_cursor_ += result;
191 failed = !WriteMore(); 281 failed = !WriteMore();
192 } else { 282 } else {
193 failed = true; 283 failed = true;
194 } 284 }
195 285
196 if (failed) { 286 if (failed) {
197 ResumeIfDeferred(); 287 DCHECK(!writer_->write_callback_pending());
198 } else if (completed_during_write_) { 288 // TODO(davidben): Recover the error code from WriteMore or |result|, as
289 // appropriate.
290 if (completed_during_write_ && completed_status_.is_success()) {
291 // If the request successfully completed mid-write, but the write failed,
292 // convert the status to a failure for downstream.
293 completed_status_.set_status(net::URLRequestStatus::CANCELED);
294 completed_status_.set_error(net::ERR_FAILED);
295 }
296 controller()->CancelWithError(net::ERR_FAILED);
mmenke 2014/02/14 21:52:49 Hmm... Should we really be cancelling with an err
davidben 2014/02/25 20:03:07 I don't think it especially matters? I've gone and
297 }
298
299 if (completed_during_write_ && !writer_->write_callback_pending()) {
300 // Resume shutdown now that all data has been written to disk. Note that
301 // this should run even in the |failed| case above, otherwise a failed write
302 // leaves the handler stuck.
199 bool defer = false; 303 bool defer = false;
200 next_handler_->OnResponseCompleted(request_id, 304 next_handler_->OnResponseCompleted(request_id,
201 completed_status_, 305 completed_status_,
202 completed_security_info_, 306 completed_security_info_,
203 &defer); 307 &defer);
204 if (!defer) 308 if (!defer)
205 ResumeIfDeferred(); 309 ResumeIfDeferred();
206 } 310 }
207 } 311 }
208 312
209 bool RedirectToFileResourceHandler::WriteMore() { 313 bool RedirectToFileResourceHandler::WriteMore() {
210 DCHECK(file_stream_.get()); 314 DCHECK(writer_);
211 for (;;) { 315 for (;;) {
212 if (write_cursor_ == buf_->offset()) { 316 if (write_cursor_ == buf_->offset()) {
213 // We've caught up to the network load, but it may be in the process of 317 // We've caught up to the network load, but it may be in the process of
214 // appending more data to the buffer. 318 // appending more data to the buffer.
215 if (!buf_write_pending_) { 319 if (!buf_write_pending_) {
216 if (BufIsFull()) 320 if (BufIsFull())
217 ResumeIfDeferred(); 321 ResumeIfDeferred();
218 buf_->set_offset(0); 322 buf_->set_offset(0);
219 write_cursor_ = 0; 323 write_cursor_ = 0;
220 } 324 }
221 return true; 325 return true;
222 } 326 }
223 if (write_callback_pending_) 327 if (writer_->write_callback_pending())
224 return true; 328 return true;
225 DCHECK(write_cursor_ < buf_->offset()); 329 DCHECK(write_cursor_ < buf_->offset());
226 330
227 // Create a temporary buffer pointing to a subsection of the data buffer so 331 // 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 332 // that it can be passed to Write. This code makes some crazy scary
229 // assumptions about object lifetimes, thread sharing, and that buf_ will 333 // 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 334 // not realloc durring the write due to how the state machine in this class
231 // works. 335 // works.
232 // Note that buf_ is also shared with the code that writes data into the 336 // 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: 337 // cache, so modifying it can cause some pretty subtle race conditions:
234 // https://code.google.com/p/chromium/issues/detail?id=152076 338 // https://code.google.com/p/chromium/issues/detail?id=152076
235 // We're using DependentIOBuffer instead of DrainableIOBuffer to dodge some 339 // We're using DependentIOBuffer instead of DrainableIOBuffer to dodge some
236 // of these issues, for the moment. 340 // of these issues, for the moment.
237 // TODO(ncbray) make this code less crazy scary. 341 // TODO(ncbray) make this code less crazy scary.
238 // Also note that Write may increase the refcount of "wrapped" deep in the 342 // 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 343 // bowels of its implementation, the use of scoped_refptr here is not
240 // spurious. 344 // spurious.
241 scoped_refptr<DependentIOBuffer> wrapped = new DependentIOBuffer( 345 scoped_refptr<DependentIOBuffer> wrapped = new DependentIOBuffer(
242 buf_.get(), buf_->StartOfBuffer() + write_cursor_); 346 buf_.get(), buf_->StartOfBuffer() + write_cursor_);
243 int write_len = buf_->offset() - write_cursor_; 347 int write_len = buf_->offset() - write_cursor_;
244 348
245 int rv = file_stream_->Write( 349 int rv = writer_->Write(wrapped.get(), write_len);
246 wrapped.get(), 350 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; 351 return true;
253 }
254 if (rv <= 0) 352 if (rv <= 0)
255 return false; 353 return false;
256 next_handler_->OnDataDownloaded(GetRequestID(), rv); 354 next_handler_->OnDataDownloaded(GetRequestID(), rv);
257 write_cursor_ += rv; 355 write_cursor_ += rv;
258 } 356 }
259 } 357 }
260 358
261 bool RedirectToFileResourceHandler::BufIsFull() const { 359 bool RedirectToFileResourceHandler::BufIsFull() const {
262 // This is a hack to workaround BufferedResourceHandler's inability to 360 // This is a hack to workaround BufferedResourceHandler's inability to
263 // deal with a ResourceHandler that returns a buffer size of less than 361 // deal with a ResourceHandler that returns a buffer size of less than
264 // 2 * net::kMaxBytesToSniff from its OnWillRead method. 362 // 2 * net::kMaxBytesToSniff from its OnWillRead method.
265 // TODO(darin): Fix this retardation! 363 // TODO(darin): Fix this retardation!
266 return buf_->RemainingCapacity() <= (2 * net::kMaxBytesToSniff); 364 return buf_->RemainingCapacity() <= (2 * net::kMaxBytesToSniff);
267 } 365 }
268 366
269 void RedirectToFileResourceHandler::ResumeIfDeferred() { 367 void RedirectToFileResourceHandler::ResumeIfDeferred() {
270 if (did_defer_) { 368 if (did_defer_) {
271 did_defer_ = false; 369 did_defer_ = false;
272 controller()->Resume(); 370 controller()->Resume();
273 } 371 }
274 } 372 }
275 373
276 } // namespace content 374 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698