2 * Copyright (C) 2010 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "core/fileapi/FileReaderLoader.h"
35 #include "core/FetchInitiatorTypeNames.h"
36 #include "core/dom/ExecutionContext.h"
37 #include "core/fileapi/Blob.h"
38 #include "core/fileapi/FileReaderLoaderClient.h"
39 #include "core/html/parser/TextResourceDecoder.h"
40 #include "core/loader/ThreadableLoader.h"
41 #include "core/streams/Stream.h"
42 #include "platform/blob/BlobRegistry.h"
43 #include "platform/blob/BlobURL.h"
44 #include "platform/network/ResourceRequest.h"
45 #include "platform/network/ResourceResponse.h"
46 #include "public/platform/WebURLRequest.h"
47 #include "wtf/PassOwnPtr.h"
48 #include "wtf/PassRefPtr.h"
49 #include "wtf/RefPtr.h"
50 #include "wtf/Vector.h"
51 #include "wtf/text/Base64.h"
52 #include "wtf/text/StringBuilder.h"
56 FileReaderLoader::FileReaderLoader(ReadType readType, FileReaderLoaderClient* client)
57 : m_readType(readType)
59 , m_urlForReadingIsStream(false)
60 , m_isRawDataConverted(false)
62 , m_finishedLoading(false)
68 , m_errorCode(FileError::OK)
72 FileReaderLoader::~FileReaderLoader()
75 if (!m_urlForReading.isEmpty()) {
76 if (m_urlForReadingIsStream)
77 BlobRegistry::unregisterStreamURL(m_urlForReading);
79 BlobRegistry::revokePublicBlobURL(m_urlForReading);
83 void FileReaderLoader::startInternal(ExecutionContext& executionContext, const Stream* stream, PassRefPtr<BlobDataHandle> blobData)
85 // The blob is read by routing through the request handling layer given a temporary public url.
86 m_urlForReading = BlobURL::createPublicURL(executionContext.securityOrigin());
87 if (m_urlForReading.isEmpty()) {
88 failed(FileError::SECURITY_ERR);
94 BlobRegistry::registerPublicBlobURL(executionContext.securityOrigin(), m_urlForReading, blobData);
97 BlobRegistry::registerStreamURL(executionContext.securityOrigin(), m_urlForReading, stream->url());
100 // Construct and load the request.
101 ResourceRequest request(m_urlForReading);
103 // FIXME: Should this really be 'internal'? Do we know anything about the actual request that generated this fetch?
104 request.setRequestContext(WebURLRequest::RequestContextInternal);
106 request.setHTTPMethod("GET");
108 request.setHTTPHeaderField("Range", AtomicString(String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd)));
110 ThreadableLoaderOptions options;
111 options.preflightPolicy = ConsiderPreflight;
112 options.crossOriginRequestPolicy = DenyCrossOriginRequests;
113 // FIXME: Is there a directive to which this load should be subject?
114 options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
115 // Use special initiator to hide the request from the inspector.
116 options.initiator = FetchInitiatorTypeNames::internal;
118 ResourceLoaderOptions resourceLoaderOptions;
119 resourceLoaderOptions.allowCredentials = AllowStoredCredentials;
122 m_loader = ThreadableLoader::create(executionContext, this, request, options, resourceLoaderOptions);
124 ThreadableLoader::loadResourceSynchronously(executionContext, request, *this, options, resourceLoaderOptions);
127 void FileReaderLoader::start(ExecutionContext* executionContext, PassRefPtr<BlobDataHandle> blobData)
129 ASSERT(executionContext);
130 m_urlForReadingIsStream = false;
131 startInternal(*executionContext, 0, blobData);
134 void FileReaderLoader::start(ExecutionContext* executionContext, const Stream& stream, unsigned readSize)
136 ASSERT(executionContext);
140 m_rangeEnd = readSize - 1; // End is inclusive so (0,0) is a 1-byte read.
143 m_urlForReadingIsStream = true;
144 startInternal(*executionContext, &stream, nullptr);
147 void FileReaderLoader::cancel()
149 m_errorCode = FileError::ABORT_ERR;
153 void FileReaderLoader::terminate()
161 void FileReaderLoader::cleanup()
165 // If we get any error, we do not need to keep a buffer around.
169 m_isRawDataConverted = true;
174 void FileReaderLoader::didReceiveResponse(unsigned long, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
176 ASSERT_UNUSED(handle, !handle);
177 if (response.httpStatusCode() != 200) {
178 failed(httpStatusCodeToErrorCode(response.httpStatusCode()));
182 // A negative value means that the content length wasn't specified.
183 m_totalBytes = response.expectedContentLength();
185 long long initialBufferLength = -1;
187 if (m_totalBytes >= 0) {
188 initialBufferLength = m_totalBytes;
189 } else if (m_hasRange) {
190 // Set m_totalBytes and allocate a buffer based on the specified range.
191 m_totalBytes = 1LL + m_rangeEnd - m_rangeStart;
192 initialBufferLength = m_totalBytes;
194 // Nothing is known about the size of the resource. Normalize
195 // m_totalBytes to -1 and initialize the buffer for receiving with the
202 if (m_readType != ReadByClient) {
203 // Check that we can cast to unsigned since we have to do
204 // so to call ArrayBuffer's create function.
205 // FIXME: Support reading more than the current size limit of ArrayBuffer.
206 if (initialBufferLength > std::numeric_limits<unsigned>::max()) {
207 failed(FileError::NOT_READABLE_ERR);
211 if (initialBufferLength < 0)
212 m_rawData = adoptPtr(new ArrayBufferBuilder());
214 m_rawData = adoptPtr(new ArrayBufferBuilder(static_cast<unsigned>(initialBufferLength)));
216 if (!m_rawData || !m_rawData->isValid()) {
217 failed(FileError::NOT_READABLE_ERR);
221 if (initialBufferLength >= 0) {
222 // Total size is known. Set m_rawData to ignore overflowed data.
223 m_rawData->setVariableCapacity(false);
228 m_client->didStartLoading();
231 void FileReaderLoader::didReceiveData(const char* data, unsigned dataLength)
235 // Bail out if we already encountered an error.
239 if (m_readType == ReadByClient) {
240 m_bytesLoaded += dataLength;
243 m_client->didReceiveDataForClient(data, dataLength);
247 unsigned bytesAppended = m_rawData->append(data, dataLength);
248 if (!bytesAppended) {
251 failed(FileError::NOT_READABLE_ERR);
254 m_bytesLoaded += bytesAppended;
255 m_isRawDataConverted = false;
258 m_client->didReceiveData();
261 void FileReaderLoader::didFinishLoading(unsigned long, double)
263 if (m_readType != ReadByClient && m_rawData) {
264 m_rawData->shrinkToFit();
265 m_isRawDataConverted = false;
268 if (m_totalBytes == -1) {
269 // Update m_totalBytes only when in dynamic buffer grow mode.
270 m_totalBytes = m_bytesLoaded;
273 m_finishedLoading = true;
277 m_client->didFinishLoading();
280 void FileReaderLoader::didFail(const ResourceError&)
282 // If we're aborting, do not proceed with normal error handling since it is covered in aborting code.
283 if (m_errorCode == FileError::ABORT_ERR)
286 failed(FileError::NOT_READABLE_ERR);
289 void FileReaderLoader::failed(FileError::ErrorCode errorCode)
291 m_errorCode = errorCode;
294 m_client->didFail(m_errorCode);
297 FileError::ErrorCode FileReaderLoader::httpStatusCodeToErrorCode(int httpStatusCode)
299 switch (httpStatusCode) {
301 return FileError::SECURITY_ERR;
303 return FileError::NOT_FOUND_ERR;
305 return FileError::NOT_READABLE_ERR;
309 PassRefPtr<ArrayBuffer> FileReaderLoader::arrayBufferResult() const
311 ASSERT(m_readType == ReadAsArrayBuffer);
313 // If the loading is not started or an error occurs, return an empty result.
314 if (!m_rawData || m_errorCode)
317 return m_rawData->toArrayBuffer();
320 String FileReaderLoader::stringResult()
322 ASSERT(m_readType != ReadAsArrayBuffer && m_readType != ReadAsBlob && m_readType != ReadByClient);
324 // If the loading is not started or an error occurs, return an empty result.
325 if (!m_rawData || m_errorCode)
326 return m_stringResult;
328 // If already converted from the raw data, return the result now.
329 if (m_isRawDataConverted)
330 return m_stringResult;
332 switch (m_readType) {
333 case ReadAsArrayBuffer:
334 // No conversion is needed.
336 case ReadAsBinaryString:
337 m_stringResult = m_rawData->toString();
338 m_isRawDataConverted = true;
344 // Partial data is not supported when reading as data URL.
345 if (m_finishedLoading)
349 ASSERT_NOT_REACHED();
352 return m_stringResult;
355 void FileReaderLoader::convertToText()
357 m_isRawDataConverted = true;
359 if (!m_bytesLoaded) {
365 // The File API spec says that we should use the supplied encoding if it is valid. However, we choose to ignore this
366 // requirement in order to be consistent with how WebKit decodes the web content: always has the BOM override the
367 // provided encoding.
368 // FIXME: consider supporting incremental decoding to improve the perf.
369 StringBuilder builder;
371 m_decoder = TextResourceDecoder::create("text/plain", m_encoding.isValid() ? m_encoding : UTF8Encoding());
372 builder.append(m_decoder->decode(static_cast<const char*>(m_rawData->data()), m_rawData->byteLength()));
374 if (m_finishedLoading)
375 builder.append(m_decoder->flush());
377 m_stringResult = builder.toString();
380 void FileReaderLoader::convertToDataURL()
382 m_isRawDataConverted = true;
384 StringBuilder builder;
385 builder.appendLiteral("data:");
387 if (!m_bytesLoaded) {
388 m_stringResult = builder.toString();
392 builder.append(m_dataType);
393 builder.appendLiteral(";base64,");
396 base64Encode(static_cast<const char*>(m_rawData->data()), m_rawData->byteLength(), out);
398 builder.append(out.data());
400 m_stringResult = builder.toString();
403 void FileReaderLoader::setEncoding(const String& encoding)
405 if (!encoding.isEmpty())
406 m_encoding = WTF::TextEncoding(encoding);