Upstream version 11.40.271.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / xmlhttprequest / XMLHttpRequest.h
1 /*
2  *  Copyright (C) 2003, 2006, 2008 Apple Inc. All rights reserved.
3  *  Copyright (C) 2005, 2006 Alexey Proskuryakov <ap@nypop.com>
4  *  Copyright (C) 2011 Google Inc. All rights reserved.
5  *  Copyright (C) 2012 Intel Corporation
6  *
7  *  This library is free software; you can redistribute it and/or
8  *  modify it under the terms of the GNU Lesser General Public
9  *  License as published by the Free Software Foundation; either
10  *  version 2 of the License, or (at your option) any later version.
11  *
12  *  This library is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *  Lesser General Public License for more details.
16  *
17  *  You should have received a copy of the GNU Lesser General Public
18  *  License along with this library; if not, write to the Free Software
19  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #ifndef XMLHttpRequest_h
23 #define XMLHttpRequest_h
24
25 #include "bindings/core/v8/ScriptString.h"
26 #include "core/dom/ActiveDOMObject.h"
27 #include "core/dom/DocumentParserClient.h"
28 #include "core/events/EventListener.h"
29 #include "core/loader/ThreadableLoaderClient.h"
30 #include "core/streams/ReadableStreamImpl.h"
31 #include "core/xmlhttprequest/XMLHttpRequestEventTarget.h"
32 #include "core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.h"
33 #include "platform/heap/Handle.h"
34 #include "platform/network/FormData.h"
35 #include "platform/network/ResourceResponse.h"
36 #include "platform/weborigin/SecurityOrigin.h"
37 #include "wtf/Forward.h"
38 #include "wtf/OwnPtr.h"
39 #include "wtf/text/AtomicStringHash.h"
40 #include "wtf/text/StringBuilder.h"
41
42 namespace blink {
43
44 class Blob;
45 class BlobDataHandle;
46 class DOMArrayBuffer;
47 class DOMFormData;
48 class Document;
49 class DocumentParser;
50 class ExceptionState;
51 class ResourceRequest;
52 class SecurityOrigin;
53 class SharedBuffer;
54 class Stream;
55 class TextResourceDecoder;
56 class ThreadableLoader;
57 class UnderlyingSource;
58 class XMLHttpRequestUpload;
59
60 typedef int ExceptionCode;
61
62 class XMLHttpRequest final
63     : public RefCountedWillBeGarbageCollectedFinalized<XMLHttpRequest>
64     , public XMLHttpRequestEventTarget
65     , private ThreadableLoaderClient
66     , public DocumentParserClient
67     , public ActiveDOMObject {
68     DEFINE_WRAPPERTYPEINFO();
69     REFCOUNTED_EVENT_TARGET(XMLHttpRequest);
70     WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(XMLHttpRequest);
71     WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
72 public:
73     static PassRefPtrWillBeRawPtr<XMLHttpRequest> create(ExecutionContext*, PassRefPtr<SecurityOrigin> = nullptr);
74     virtual ~XMLHttpRequest();
75
76     // These exact numeric values are important because JS expects them.
77     enum State {
78         UNSENT = 0,
79         OPENED = 1,
80         HEADERS_RECEIVED = 2,
81         LOADING = 3,
82         DONE = 4
83     };
84
85     enum ResponseTypeCode {
86         ResponseTypeDefault,
87         ResponseTypeText,
88         ResponseTypeJSON,
89         ResponseTypeDocument,
90         ResponseTypeBlob,
91         ResponseTypeArrayBuffer,
92         ResponseTypeLegacyStream,
93         ResponseTypeStream,
94     };
95
96     // ActiveDOMObject
97     virtual void contextDestroyed() override;
98     virtual ExecutionContext* executionContext() const override;
99     virtual bool hasPendingActivity() const override;
100     virtual void suspend() override;
101     virtual void resume() override;
102     virtual void stop() override;
103
104     // XMLHttpRequestEventTarget
105     virtual const AtomicString& interfaceName() const override;
106
107     // JavaScript attributes and methods
108     const KURL& url() const { return m_url; }
109     String statusText() const;
110     int status() const;
111     State readyState() const;
112     bool withCredentials() const { return m_includeCredentials; }
113     void setWithCredentials(bool, ExceptionState&);
114     void open(const AtomicString& method, const KURL&, ExceptionState&);
115     void open(const AtomicString& method, const KURL&, bool async, ExceptionState&);
116     void open(const AtomicString& method, const KURL&, bool async, const String& user, ExceptionState&);
117     void open(const AtomicString& method, const KURL&, bool async, const String& user, const String& password, ExceptionState&);
118     void send(ExceptionState&);
119     void send(Document*, ExceptionState&);
120     void send(const String&, ExceptionState&);
121     void send(Blob*, ExceptionState&);
122     void send(DOMFormData*, ExceptionState&);
123     void send(ArrayBuffer*, ExceptionState&);
124     void send(ArrayBufferView*, ExceptionState&);
125     void abort();
126     void setRequestHeader(const AtomicString& name, const AtomicString& value, ExceptionState&);
127     void overrideMimeType(const AtomicString& override, ExceptionState&);
128     String getAllResponseHeaders() const;
129     const AtomicString& getResponseHeader(const AtomicString&) const;
130     ScriptString responseText(ExceptionState&);
131     ScriptString responseJSONSource();
132     Document* responseXML(ExceptionState&);
133     Blob* responseBlob();
134     DOMArrayBuffer* responseArrayBuffer();
135     Stream* responseLegacyStream();
136     ReadableStream* responseStream();
137     unsigned long timeout() const { return m_timeoutMilliseconds; }
138     void setTimeout(unsigned long timeout, ExceptionState&);
139     ResponseTypeCode responseTypeCode() const { return m_responseTypeCode; }
140     String responseType();
141     void setResponseType(const String&, ExceptionState&);
142     String responseURL();
143
144     // For Inspector.
145     void sendForInspectorXHRReplay(PassRefPtr<FormData>, ExceptionState&);
146
147     XMLHttpRequestUpload* upload();
148
149     DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
150
151     virtual void trace(Visitor*) override;
152
153 private:
154     class BlobLoader;
155     XMLHttpRequest(ExecutionContext*, PassRefPtr<SecurityOrigin>);
156
157     Document* document() const;
158     SecurityOrigin* securityOrigin() const;
159
160     virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) override;
161     virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>) override;
162     virtual void didReceiveData(const char* data, unsigned dataLength) override;
163     // When responseType is set to "blob", didDownloadData() is called instead
164     // of didReceiveData().
165     virtual void didDownloadData(int dataLength) override;
166     virtual void didFinishLoading(unsigned long identifier, double finishTime) override;
167     virtual void didFail(const ResourceError&) override;
168     virtual void didFailRedirectCheck() override;
169
170     // BlobLoader notifications.
171     void didFinishLoadingInternal();
172     void didFinishLoadingFromBlob();
173     void didFailLoadingFromBlob();
174
175     PassRefPtr<BlobDataHandle> createBlobDataHandleFromResponse();
176
177     // DocumentParserClient
178     virtual void notifyParserStopped() override;
179
180     void endLoading();
181
182     // Returns the MIME type part of m_mimeTypeOverride if present and
183     // successfully parsed, or returns one of the "Content-Type" header value
184     // of the received response.
185     //
186     // This method is named after the term "final MIME type" defined in the
187     // spec but doesn't convert the result to ASCII lowercase as specified in
188     // the spec. Must be lowered later or compared using case insensitive
189     // comparison functions if required.
190     AtomicString finalResponseMIMEType() const;
191     // The same as finalResponseMIMEType() but fallbacks to "text/xml" if
192     // finalResponseMIMEType() returns an empty string.
193     AtomicString finalResponseMIMETypeWithFallback() const;
194     bool responseIsXML() const;
195     bool responseIsHTML() const;
196
197     PassOwnPtr<TextResourceDecoder> createDecoder() const;
198
199     void initResponseDocument();
200     void parseDocumentChunk(const char* data, unsigned dataLength);
201
202     bool areMethodAndURLValidForSend();
203
204     bool initSend(ExceptionState&);
205     void sendBytesData(const void*, size_t, ExceptionState&);
206
207     const AtomicString& getRequestHeader(const AtomicString& name) const;
208     void setRequestHeaderInternal(const AtomicString& name, const AtomicString& value);
209
210     void trackProgress(long long dataLength);
211     // Changes m_state and dispatches a readyStateChange event if new m_state
212     // value is different from last one.
213     void changeState(State newState);
214     void dispatchReadyStateChangeEvent();
215
216     // Clears variables used only while the resource is being loaded.
217     void clearVariablesForLoading();
218     // Returns false iff reentry happened and a new load is started.
219     //
220     // This method may invoke V8 GC with m_loader unset. If you touch the
221     // XMLHttpRequest instance after internalAbort() call, you must hold a
222     // refcount on it to prevent it from destroyed.
223     bool internalAbort();
224     // Clears variables holding response header and body data.
225     void clearResponse();
226     void clearRequest();
227
228     void createRequest(PassRefPtr<FormData>, ExceptionState&);
229
230     // Dispatches a response ProgressEvent.
231     void dispatchProgressEvent(const AtomicString&, long long, long long);
232     // Dispatches a response ProgressEvent using values sampled from
233     // m_receivedLength and m_response.
234     void dispatchProgressEventFromSnapshot(const AtomicString&);
235
236     // Handles didFail() call not caused by cancellation or timeout.
237     void handleNetworkError();
238     // Handles didFail() call for cancellations. For example, the
239     // ResourceLoader handling the load notifies m_loader of an error
240     // cancellation when the frame containing the XHR navigates away.
241     void handleDidCancel();
242     // Handles didFail() call for timeout.
243     void handleDidTimeout();
244
245     void handleRequestError(ExceptionCode, const AtomicString&, long long, long long);
246
247     OwnPtrWillBeMember<XMLHttpRequestUpload> m_upload;
248
249     KURL m_url;
250     AtomicString m_method;
251     HTTPHeaderMap m_requestHeaders;
252     // Not converted to ASCII lowercase. Must be lowered later or compared
253     // using case insensitive comparison functions if needed.
254     AtomicString m_mimeTypeOverride;
255     unsigned long m_timeoutMilliseconds;
256     PersistentWillBeMember<Blob> m_responseBlob;
257     RefPtrWillBeMember<Stream> m_responseLegacyStream;
258     PersistentWillBeMember<ReadableStreamImpl<ReadableStreamChunkTypeTraits<DOMArrayBuffer> > > m_responseStream;
259     PersistentWillBeMember<UnderlyingSource> m_streamSource;
260
261     RefPtr<ThreadableLoader> m_loader;
262     unsigned long m_loaderIdentifier;
263     State m_state;
264
265     ResourceResponse m_response;
266     String m_finalResponseCharset;
267
268     OwnPtr<TextResourceDecoder> m_decoder;
269
270     ScriptString m_responseText;
271     RefPtrWillBeMember<Document> m_responseDocument;
272     RefPtrWillBeMember<DocumentParser> m_responseDocumentParser;
273
274     RefPtr<SharedBuffer> m_binaryResponseBuilder;
275     long long m_lengthDownloadedToFile;
276
277     RefPtr<DOMArrayBuffer> m_responseArrayBuffer;
278
279     // Used for onprogress tracking
280     long long m_receivedLength;
281
282     // An exception to throw in synchronous mode. It's set when failure
283     // notification is received from m_loader and thrown at the end of send() if
284     // any.
285     ExceptionCode m_exceptionCode;
286
287     XMLHttpRequestProgressEventThrottle m_progressEventThrottle;
288
289     // An enum corresponding to the allowed string values for the responseType attribute.
290     ResponseTypeCode m_responseTypeCode;
291     RefPtr<SecurityOrigin> m_securityOrigin;
292
293     // This blob loader will be used if |m_downloadingToFile| is true and
294     // |m_responseTypeCode| is NOT ResponseTypeBlob.
295     OwnPtrWillBeMember<BlobLoader> m_blobLoader;
296
297     bool m_async;
298     bool m_includeCredentials;
299     // Used to skip m_responseDocument creation if it's done previously. We need
300     // this separate flag since m_responseDocument can be 0 for some cases.
301     bool m_parsedResponse;
302     bool m_error;
303     bool m_uploadEventsAllowed;
304     bool m_uploadComplete;
305     bool m_sameOriginRequest;
306     // True iff the ongoing resource loading is using the downloadToFile
307     // option.
308     bool m_downloadingToFile;
309 };
310
311 } // namespace blink
312
313 #endif // XMLHttpRequest_h