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
3 // found in the LICENSE file.
5 // For loading files, we make use of overlapped i/o to ensure that reading from
6 // the filesystem (e.g., a network filesystem) does not block the calling
7 // thread. An alternative approach would be to use a background thread or pool
8 // of threads, but it seems better to leverage the operating system's ability
9 // to do background file reads for us.
11 // Since overlapped reads require a 'static' buffer for the duration of the
12 // asynchronous read, the URLRequestFileJob keeps a buffer as a member var. In
13 // URLRequestFileJob::Read, data is simply copied from the object's buffer into
14 // the given buffer. If there is no data to copy, the URLRequestFileJob
15 // attempts to read more from the file to fill its buffer. If reading from the
16 // file does not complete synchronously, then the URLRequestFileJob waits for a
17 // signal from the OS that the overlapped read has completed. It does so by
18 // leveraging the MessageLoop::WatchObject API.
20 #include "net/url_request/url_request_file_job.h"
22 #include "base/bind.h"
23 #include "base/compiler_specific.h"
24 #include "base/files/file_util.h"
25 #include "base/message_loop/message_loop.h"
26 #include "base/profiler/scoped_tracker.h"
27 #include "base/strings/string_util.h"
28 #include "base/synchronization/lock.h"
29 #include "base/task_runner.h"
30 #include "base/threading/thread_restrictions.h"
31 #include "build/build_config.h"
32 #include "net/base/file_stream.h"
33 #include "net/base/filename_util.h"
34 #include "net/base/io_buffer.h"
35 #include "net/base/load_flags.h"
36 #include "net/base/mime_util.h"
37 #include "net/base/net_errors.h"
38 #include "net/filter/filter.h"
39 #include "net/http/http_util.h"
40 #include "net/url_request/url_request_error_job.h"
41 #include "net/url_request/url_request_file_dir_job.h"
45 #include "base/win/shortcut.h"
50 URLRequestFileJob::FileMetaInfo::FileMetaInfo()
52 mime_type_result(false),
57 URLRequestFileJob::URLRequestFileJob(
59 NetworkDelegate
* network_delegate
,
60 const base::FilePath
& file_path
,
61 const scoped_refptr
<base::TaskRunner
>& file_task_runner
)
62 : URLRequestJob(request
, network_delegate
),
63 file_path_(file_path
),
64 stream_(new FileStream(file_task_runner
)),
65 file_task_runner_(file_task_runner
),
67 weak_ptr_factory_(this) {}
69 void URLRequestFileJob::Start() {
70 FileMetaInfo
* meta_info
= new FileMetaInfo();
71 file_task_runner_
->PostTaskAndReply(
73 base::Bind(&URLRequestFileJob::FetchMetaInfo
, file_path_
,
74 base::Unretained(meta_info
)),
75 base::Bind(&URLRequestFileJob::DidFetchMetaInfo
,
76 weak_ptr_factory_
.GetWeakPtr(),
77 base::Owned(meta_info
)));
80 void URLRequestFileJob::Kill() {
82 weak_ptr_factory_
.InvalidateWeakPtrs();
84 URLRequestJob::Kill();
87 bool URLRequestFileJob::ReadRawData(IOBuffer
* dest
,
90 DCHECK_NE(dest_size
, 0);
92 DCHECK_GE(remaining_bytes_
, 0);
94 if (remaining_bytes_
< dest_size
)
95 dest_size
= static_cast<int>(remaining_bytes_
);
97 // If we should copy zero bytes because |remaining_bytes_| is zero, short
104 int rv
= stream_
->Read(dest
,
106 base::Bind(&URLRequestFileJob::DidRead
,
107 weak_ptr_factory_
.GetWeakPtr(),
108 make_scoped_refptr(dest
)));
110 // Data is immediately available.
112 remaining_bytes_
-= rv
;
113 DCHECK_GE(remaining_bytes_
, 0);
117 // Otherwise, a read error occured. We may just need to wait...
118 if (rv
== ERR_IO_PENDING
) {
119 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
121 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, rv
));
126 bool URLRequestFileJob::IsRedirectResponse(GURL
* location
,
127 int* http_status_code
) {
128 if (meta_info_
.is_directory
) {
129 // This happens when we discovered the file is a directory, so needs a
130 // slash at the end of the path.
131 std::string new_path
= request_
->url().path();
132 new_path
.push_back('/');
133 GURL::Replacements replacements
;
134 replacements
.SetPathStr(new_path
);
136 *location
= request_
->url().ReplaceComponents(replacements
);
137 *http_status_code
= 301; // simulate a permanent redirect
142 // Follow a Windows shortcut.
143 // We just resolve .lnk file, ignore others.
144 if (!LowerCaseEqualsASCII(file_path_
.Extension(), ".lnk"))
147 base::FilePath new_path
= file_path_
;
149 resolved
= base::win::ResolveShortcut(new_path
, &new_path
, NULL
);
151 // If shortcut is not resolved succesfully, do not redirect.
155 *location
= FilePathToFileURL(new_path
);
156 *http_status_code
= 301;
163 Filter
* URLRequestFileJob::SetupFilter() const {
164 // Bug 9936 - .svgz files needs to be decompressed.
165 return LowerCaseEqualsASCII(file_path_
.Extension(), ".svgz")
166 ? Filter::GZipFactory() : NULL
;
169 bool URLRequestFileJob::GetMimeType(std::string
* mime_type
) const {
171 if (meta_info_
.mime_type_result
) {
172 *mime_type
= meta_info_
.mime_type
;
178 void URLRequestFileJob::SetExtraRequestHeaders(
179 const HttpRequestHeaders
& headers
) {
180 std::string range_header
;
181 if (headers
.GetHeader(HttpRequestHeaders::kRange
, &range_header
)) {
182 // We only care about "Range" header here.
183 std::vector
<HttpByteRange
> ranges
;
184 if (HttpUtil::ParseRangeHeader(range_header
, &ranges
)) {
185 if (ranges
.size() == 1) {
186 byte_range_
= ranges
[0];
188 // We don't support multiple range requests in one single URL request,
189 // because we need to do multipart encoding here.
190 // TODO(hclam): decide whether we want to support multiple range
192 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
,
193 ERR_REQUEST_RANGE_NOT_SATISFIABLE
));
199 void URLRequestFileJob::OnSeekComplete(int64 result
) {
202 void URLRequestFileJob::OnReadComplete(net::IOBuffer
* buf
, int result
) {
205 URLRequestFileJob::~URLRequestFileJob() {
208 void URLRequestFileJob::FetchMetaInfo(const base::FilePath
& file_path
,
209 FileMetaInfo
* meta_info
) {
210 base::File::Info file_info
;
211 meta_info
->file_exists
= base::GetFileInfo(file_path
, &file_info
);
212 if (meta_info
->file_exists
) {
213 meta_info
->file_size
= file_info
.size
;
214 meta_info
->is_directory
= file_info
.is_directory
;
216 // On Windows GetMimeTypeFromFile() goes to the registry. Thus it should be
217 // done in WorkerPool.
218 meta_info
->mime_type_result
= GetMimeTypeFromFile(file_path
,
219 &meta_info
->mime_type
);
222 void URLRequestFileJob::DidFetchMetaInfo(const FileMetaInfo
* meta_info
) {
223 meta_info_
= *meta_info
;
225 // We use URLRequestFileJob to handle files as well as directories without
227 // If a directory does not exist, we return ERR_FILE_NOT_FOUND. Otherwise,
228 // we will append trailing slash and redirect to FileDirJob.
229 // A special case is "\" on Windows. We should resolve as invalid.
230 // However, Windows resolves "\" to "C:\", thus reports it as existent.
231 // So what happens is we append it with trailing slash and redirect it to
232 // FileDirJob where it is resolved as invalid.
233 if (!meta_info_
.file_exists
) {
234 DidOpen(ERR_FILE_NOT_FOUND
);
237 if (meta_info_
.is_directory
) {
242 int flags
= base::File::FLAG_OPEN
|
243 base::File::FLAG_READ
|
244 base::File::FLAG_ASYNC
;
245 int rv
= stream_
->Open(file_path_
, flags
,
246 base::Bind(&URLRequestFileJob::DidOpen
,
247 weak_ptr_factory_
.GetWeakPtr()));
248 if (rv
!= ERR_IO_PENDING
)
252 void URLRequestFileJob::DidOpen(int result
) {
253 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
254 tracked_objects::ScopedTracker
tracking_profile(
255 FROM_HERE_WITH_EXPLICIT_FUNCTION("423948 URLRequestFileJob::DidOpen"));
258 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, result
));
262 if (!byte_range_
.ComputeBounds(meta_info_
.file_size
)) {
263 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
,
264 ERR_REQUEST_RANGE_NOT_SATISFIABLE
));
268 remaining_bytes_
= byte_range_
.last_byte_position() -
269 byte_range_
.first_byte_position() + 1;
270 DCHECK_GE(remaining_bytes_
, 0);
272 if (remaining_bytes_
> 0 && byte_range_
.first_byte_position() != 0) {
273 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
274 tracked_objects::ScopedTracker
tracking_profile1(
275 FROM_HERE_WITH_EXPLICIT_FUNCTION(
276 "423948 URLRequestFileJob::DidOpen 1"));
278 int rv
= stream_
->Seek(base::File::FROM_BEGIN
,
279 byte_range_
.first_byte_position(),
280 base::Bind(&URLRequestFileJob::DidSeek
,
281 weak_ptr_factory_
.GetWeakPtr()));
282 if (rv
!= ERR_IO_PENDING
) {
283 // stream_->Seek() failed, so pass an intentionally erroneous value
288 // We didn't need to call stream_->Seek() at all, so we pass to DidSeek()
289 // the value that would mean seek success. This way we skip the code
290 // handling seek failure.
291 DidSeek(byte_range_
.first_byte_position());
295 void URLRequestFileJob::DidSeek(int64 result
) {
296 OnSeekComplete(result
);
297 if (result
!= byte_range_
.first_byte_position()) {
298 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
,
299 ERR_REQUEST_RANGE_NOT_SATISFIABLE
));
303 set_expected_content_size(remaining_bytes_
);
304 NotifyHeadersComplete();
307 void URLRequestFileJob::DidRead(scoped_refptr
<net::IOBuffer
> buf
, int result
) {
309 SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
310 remaining_bytes_
-= result
;
311 DCHECK_GE(remaining_bytes_
, 0);
314 OnReadComplete(buf
.get(), result
);
318 NotifyDone(URLRequestStatus());
319 } else if (result
< 0) {
320 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, result
));
323 NotifyReadComplete(result
);