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 "FetchInitiatorTypeNames.h"
36 #include "core/dom/ExecutionContext.h"
37 #include "core/fileapi/Blob.h"
38 #include "core/fileapi/FileReaderLoaderClient.h"
39 #include "core/fileapi/Stream.h"
40 #include "core/html/parser/TextResourceDecoder.h"
41 #include "core/loader/ThreadableLoader.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 "wtf/PassOwnPtr.h"
47 #include "wtf/PassRefPtr.h"
48 #include "wtf/RefPtr.h"
49 #include "wtf/Vector.h"
50 #include "wtf/text/Base64.h"
51 #include "wtf/text/StringBuilder.h"
57 FileReaderLoader::FileReaderLoader(ReadType readType, FileReaderLoaderClient* client)
58 : m_readType(readType)
60 , m_urlForReadingIsStream(false)
61 , m_isRawDataConverted(false)
63 , m_finishedLoading(false)
69 , m_errorCode(FileError::OK)
73 FileReaderLoader::~FileReaderLoader()
76 if (!m_urlForReading.isEmpty()) {
77 if (m_urlForReadingIsStream)
78 BlobRegistry::unregisterStreamURL(m_urlForReading);
80 BlobRegistry::revokePublicBlobURL(m_urlForReading);
84 void FileReaderLoader::startInternal(ExecutionContext& executionContext, const Stream* stream, PassRefPtr<BlobDataHandle> blobData)
86 // The blob is read by routing through the request handling layer given a temporary public url.
87 m_urlForReading = BlobURL::createPublicURL(executionContext.securityOrigin());
88 if (m_urlForReading.isEmpty()) {
89 failed(FileError::SECURITY_ERR);
95 BlobRegistry::registerPublicBlobURL(executionContext.securityOrigin(), m_urlForReading, blobData);
98 BlobRegistry::registerStreamURL(executionContext.securityOrigin(), m_urlForReading, stream->url());
101 // Construct and load the request.
102 ResourceRequest request(m_urlForReading);
103 request.setHTTPMethod("GET");
105 request.setHTTPHeaderField("Range", AtomicString(String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd)));
107 ThreadableLoaderOptions options;
108 options.sniffContent = DoNotSniffContent;
109 options.preflightPolicy = ConsiderPreflight;
110 options.allowCredentials = AllowStoredCredentials;
111 options.crossOriginRequestPolicy = DenyCrossOriginRequests;
112 // FIXME: Is there a directive to which this load should be subject?
113 options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
114 // Use special initiator to hide the request from the inspector.
115 options.initiator = FetchInitiatorTypeNames::internal;
118 m_loader = ThreadableLoader::create(executionContext, this, request, options);
120 ThreadableLoader::loadResourceSynchronously(executionContext, request, *this, options);
123 void FileReaderLoader::start(ExecutionContext* executionContext, PassRefPtr<BlobDataHandle> blobData)
125 ASSERT(executionContext);
126 m_urlForReadingIsStream = false;
127 startInternal(*executionContext, 0, blobData);
130 void FileReaderLoader::start(ExecutionContext* executionContext, const Stream& stream, unsigned readSize)
132 ASSERT(executionContext);
136 m_rangeEnd = readSize - 1; // End is inclusive so (0,0) is a 1-byte read.
139 m_urlForReadingIsStream = true;
140 startInternal(*executionContext, &stream, nullptr);
143 void FileReaderLoader::cancel()
145 m_errorCode = FileError::ABORT_ERR;
149 void FileReaderLoader::terminate()
157 void FileReaderLoader::cleanup()
161 // If we get any error, we do not need to keep a buffer around.
165 m_isRawDataConverted = true;
170 void FileReaderLoader::didReceiveResponse(unsigned long, const ResourceResponse& response)
172 if (response.httpStatusCode() != 200) {
173 failed(httpStatusCodeToErrorCode(response.httpStatusCode()));
177 // A negative value means that the content length wasn't specified.
178 m_totalBytes = response.expectedContentLength();
180 long long initialBufferLength = -1;
182 if (m_totalBytes >= 0) {
183 initialBufferLength = m_totalBytes;
184 } else if (m_hasRange) {
185 // Set m_totalBytes and allocate a buffer based on the specified range.
186 m_totalBytes = 1LL + m_rangeEnd - m_rangeStart;
187 initialBufferLength = m_totalBytes;
189 // Nothing is known about the size of the resource. Normalize
190 // m_totalBytes to -1 and initialize the buffer for receiving with the
197 if (m_readType != ReadByClient) {
198 // Check that we can cast to unsigned since we have to do
199 // so to call ArrayBuffer's create function.
200 // FIXME: Support reading more than the current size limit of ArrayBuffer.
201 if (initialBufferLength > numeric_limits<unsigned>::max()) {
202 failed(FileError::NOT_READABLE_ERR);
206 if (initialBufferLength < 0)
207 m_rawData = adoptPtr(new ArrayBufferBuilder());
209 m_rawData = adoptPtr(new ArrayBufferBuilder(static_cast<unsigned>(initialBufferLength)));
211 if (!m_rawData || !m_rawData->isValid()) {
212 failed(FileError::NOT_READABLE_ERR);
216 if (initialBufferLength >= 0) {
217 // Total size is known. Set m_rawData to ignore overflowed data.
218 m_rawData->setVariableCapacity(false);
223 m_client->didStartLoading();
226 void FileReaderLoader::didReceiveData(const char* data, int dataLength)
229 ASSERT(dataLength > 0);
231 // Bail out if we already encountered an error.
235 if (m_readType == ReadByClient) {
236 m_bytesLoaded += dataLength;
239 m_client->didReceiveDataForClient(data, dataLength);
243 unsigned bytesAppended = m_rawData->append(data, static_cast<unsigned>(dataLength));
244 if (!bytesAppended) {
247 failed(FileError::NOT_READABLE_ERR);
250 m_bytesLoaded += bytesAppended;
251 m_isRawDataConverted = false;
254 m_client->didReceiveData();
257 void FileReaderLoader::didFinishLoading(unsigned long, double)
259 if (m_readType != ReadByClient && m_rawData) {
260 m_rawData->shrinkToFit();
261 m_isRawDataConverted = false;
264 if (m_totalBytes == -1) {
265 // Update m_totalBytes only when in dynamic buffer grow mode.
266 m_totalBytes = m_bytesLoaded;
269 m_finishedLoading = true;
273 m_client->didFinishLoading();
276 void FileReaderLoader::didFail(const ResourceError&)
278 // If we're aborting, do not proceed with normal error handling since it is covered in aborting code.
279 if (m_errorCode == FileError::ABORT_ERR)
282 failed(FileError::NOT_READABLE_ERR);
285 void FileReaderLoader::failed(FileError::ErrorCode errorCode)
287 m_errorCode = errorCode;
290 m_client->didFail(m_errorCode);
293 FileError::ErrorCode FileReaderLoader::httpStatusCodeToErrorCode(int httpStatusCode)
295 switch (httpStatusCode) {
297 return FileError::SECURITY_ERR;
299 return FileError::NOT_FOUND_ERR;
301 return FileError::NOT_READABLE_ERR;
305 PassRefPtr<ArrayBuffer> FileReaderLoader::arrayBufferResult() const
307 ASSERT(m_readType == ReadAsArrayBuffer);
309 // If the loading is not started or an error occurs, return an empty result.
310 if (!m_rawData || m_errorCode)
313 return m_rawData->toArrayBuffer();
316 String FileReaderLoader::stringResult()
318 ASSERT(m_readType != ReadAsArrayBuffer && m_readType != ReadAsBlob && m_readType != ReadByClient);
320 // If the loading is not started or an error occurs, return an empty result.
321 if (!m_rawData || m_errorCode)
322 return m_stringResult;
324 // If already converted from the raw data, return the result now.
325 if (m_isRawDataConverted)
326 return m_stringResult;
328 switch (m_readType) {
329 case ReadAsArrayBuffer:
330 // No conversion is needed.
332 case ReadAsBinaryString:
333 m_stringResult = m_rawData->toString();
334 m_isRawDataConverted = true;
340 // Partial data is not supported when reading as data URL.
341 if (m_finishedLoading)
345 ASSERT_NOT_REACHED();
348 return m_stringResult;
351 void FileReaderLoader::convertToText()
353 m_isRawDataConverted = true;
355 if (!m_bytesLoaded) {
361 // The File API spec says that we should use the supplied encoding if it is valid. However, we choose to ignore this
362 // requirement in order to be consistent with how WebKit decodes the web content: always has the BOM override the
363 // provided encoding.
364 // FIXME: consider supporting incremental decoding to improve the perf.
365 StringBuilder builder;
367 m_decoder = TextResourceDecoder::create("text/plain", m_encoding.isValid() ? m_encoding : UTF8Encoding());
368 builder.append(m_decoder->decode(static_cast<const char*>(m_rawData->data()), m_rawData->byteLength()));
370 if (m_finishedLoading)
371 builder.append(m_decoder->flush());
373 m_stringResult = builder.toString();
376 void FileReaderLoader::convertToDataURL()
378 m_isRawDataConverted = true;
380 StringBuilder builder;
381 builder.append("data:");
383 if (!m_bytesLoaded) {
384 m_stringResult = builder.toString();
388 builder.append(m_dataType);
389 builder.append(";base64,");
392 base64Encode(static_cast<const char*>(m_rawData->data()), m_rawData->byteLength(), out);
394 builder.append(out.data());
396 m_stringResult = builder.toString();
399 void FileReaderLoader::setEncoding(const String& encoding)
401 if (!encoding.isEmpty())
402 m_encoding = WTF::TextEncoding(encoding);
405 } // namespace WebCore