de8c1fd919531ee4fc6f2bad0c9834f36c5a3773
[platform/framework/web/crosswalk-tizen.git] /
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,
20  *  MA 02110-1301 USA
21  */
22
23 #ifndef XMLHttpRequest_h
24 #define XMLHttpRequest_h
25
26 #include "bindings/core/v8/ActiveScriptWrappable.h"
27 #include "bindings/core/v8/ScriptString.h"
28 #include "bindings/core/v8/ScriptWrappable.h"
29 #include "bindings/core/v8/TraceWrapperMember.h"
30 #include "core/dom/ActiveDOMObject.h"
31 #include "core/dom/DocumentParserClient.h"
32 #include "core/loader/ThreadableLoaderClient.h"
33 #include "core/xmlhttprequest/XMLHttpRequestEventTarget.h"
34 #include "core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.h"
35 #include "platform/heap/Handle.h"
36 #include "platform/network/EncodedFormData.h"
37 #include "platform/network/HTTPHeaderMap.h"
38 #include "platform/network/ResourceResponse.h"
39 #include "platform/weborigin/KURL.h"
40 #include "platform/weborigin/SecurityOrigin.h"
41 #include "wtf/Forward.h"
42 #include "wtf/PassRefPtr.h"
43 #include "wtf/RefPtr.h"
44 #include "wtf/text/AtomicString.h"
45 #include "wtf/text/StringBuilder.h"
46 #include "wtf/text/WTFString.h"
47 #include <memory>
48
49 namespace blink {
50
51 class ArrayBufferOrArrayBufferViewOrBlobOrDocumentOrStringOrFormData;
52 class Blob;
53 class BlobDataHandle;
54 class DOMArrayBuffer;
55 class DOMArrayBufferView;
56 class Document;
57 class DocumentParser;
58 class ExceptionState;
59 class ExecutionContext;
60 class FormData;
61 class ScriptState;
62 class SharedBuffer;
63 class TextResourceDecoder;
64 class ThreadableLoader;
65 class WebDataConsumerHandle;
66 class XMLHttpRequestUpload;
67
68 typedef int ExceptionCode;
69
70 class XMLHttpRequest final : public XMLHttpRequestEventTarget,
71                              private ThreadableLoaderClient,
72                              public DocumentParserClient,
73                              public ActiveScriptWrappable,
74                              public ActiveDOMObject {
75   DEFINE_WRAPPERTYPEINFO();
76   USING_GARBAGE_COLLECTED_MIXIN(XMLHttpRequest);
77
78  public:
79   static XMLHttpRequest* create(ScriptState*);
80   static XMLHttpRequest* create(ExecutionContext*);
81   ~XMLHttpRequest() override;
82
83   // These exact numeric values are important because JS expects them.
84   enum State {
85     kUnsent = 0,
86     kOpened = 1,
87     kHeadersReceived = 2,
88     kLoading = 3,
89     kDone = 4
90   };
91
92   enum ResponseTypeCode {
93     ResponseTypeDefault,
94     ResponseTypeText,
95     ResponseTypeJSON,
96     ResponseTypeDocument,
97     ResponseTypeBlob,
98     ResponseTypeArrayBuffer,
99   };
100
101   // ActiveDOMObject
102   void contextDestroyed() override;
103   ExecutionContext* getExecutionContext() const override;
104   void suspend() override;
105   void resume() override;
106
107   // ScriptWrappable
108   bool hasPendingActivity() const final;
109
110   // XMLHttpRequestEventTarget
111   const AtomicString& interfaceName() const override;
112
113   // JavaScript attributes and methods
114   const KURL& url() const { return m_url; }
115   String statusText() const;
116   int status() const;
117   State readyState() const;
118   bool withCredentials() const { return m_includeCredentials; }
119   void setWithCredentials(bool, ExceptionState&);
120   void open(const AtomicString& method, const String& url, ExceptionState&);
121   void open(const AtomicString& method,
122             const String& url,
123             bool async,
124             const String& username,
125             const String& password,
126             ExceptionState&);
127   void open(const AtomicString& method,
128             const KURL&,
129             bool async,
130             ExceptionState&);
131   void send(
132       const ArrayBufferOrArrayBufferViewOrBlobOrDocumentOrStringOrFormData&,
133       ExceptionState&);
134   void abort();
135   void setRequestHeader(const AtomicString& name,
136                         const AtomicString& value,
137                         ExceptionState&);
138   void overrideMimeType(const AtomicString& override, ExceptionState&);
139   String getAllResponseHeaders() const;
140   const AtomicString& getResponseHeader(const AtomicString&) const;
141   ScriptString responseText(ExceptionState&);
142   ScriptString responseJSONSource();
143   Document* responseXML(ExceptionState&);
144   Blob* responseBlob();
145   DOMArrayBuffer* responseArrayBuffer();
146   unsigned timeout() const { return m_timeoutMilliseconds; }
147   void setTimeout(unsigned timeout, ExceptionState&);
148   ResponseTypeCode getResponseTypeCode() const { return m_responseTypeCode; }
149   String responseType();
150   void setResponseType(const String&, ExceptionState&);
151   String responseURL();
152
153   // For Inspector.
154   void sendForInspectorXHRReplay(PassRefPtr<EncodedFormData>, ExceptionState&);
155
156   XMLHttpRequestUpload* upload();
157   bool isAsync() { return m_async; }
158
159   DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
160
161   // (Also) eagerly finalized so as to prevent access to the eagerly finalized
162   // progress event throttle.
163   EAGERLY_FINALIZE();
164   DECLARE_VIRTUAL_TRACE();
165   DECLARE_TRACE_WRAPPERS();
166
167  private:
168   class BlobLoader;
169   XMLHttpRequest(ExecutionContext*, PassRefPtr<SecurityOrigin>);
170
171   Document* document() const;
172   SecurityOrigin* getSecurityOrigin() const;
173
174   void didSendData(unsigned long long bytesSent,
175                    unsigned long long totalBytesToBeSent) override;
176   void didReceiveResponse(unsigned long identifier,
177                           const ResourceResponse&,
178                           std::unique_ptr<WebDataConsumerHandle>) override;
179   void didReceiveData(const char* data, unsigned dataLength) override;
180   // When responseType is set to "blob", didDownloadData() is called instead
181   // of didReceiveData().
182   void didDownloadData(int dataLength) override;
183   void didFinishLoading(unsigned long identifier, double finishTime) override;
184   void didFail(const ResourceError&) override;
185   void didFailRedirectCheck() override;
186
187   // BlobLoader notifications.
188   void didFinishLoadingInternal();
189   void didFinishLoadingFromBlob();
190   void didFailLoadingFromBlob();
191
192   PassRefPtr<BlobDataHandle> createBlobDataHandleFromResponse();
193
194   // DocumentParserClient
195   void notifyParserStopped() override;
196
197   void endLoading();
198
199   // Returns the MIME type part of m_mimeTypeOverride if present and
200   // successfully parsed, or returns one of the "Content-Type" header value
201   // of the received response.
202   //
203   // This method is named after the term "final MIME type" defined in the
204   // spec but doesn't convert the result to ASCII lowercase as specified in
205   // the spec. Must be lowered later or compared using case insensitive
206   // comparison functions if required.
207   AtomicString finalResponseMIMEType() const;
208   // The same as finalResponseMIMEType() but fallbacks to "text/xml" if
209   // finalResponseMIMEType() returns an empty string.
210   AtomicString finalResponseMIMETypeWithFallback() const;
211   bool responseIsXML() const;
212   bool responseIsHTML() const;
213
214   std::unique_ptr<TextResourceDecoder> createDecoder() const;
215
216   void initResponseDocument();
217   void parseDocumentChunk(const char* data, unsigned dataLength);
218
219   bool areMethodAndURLValidForSend();
220
221   void throwForLoadFailureIfNeeded(ExceptionState&, const String&);
222
223   bool initSend(ExceptionState&);
224   void sendBytesData(const void*, size_t, ExceptionState&);
225   void send(Document*, ExceptionState&);
226   void send(const String&, ExceptionState&);
227   void send(Blob*, ExceptionState&);
228   void send(FormData*, ExceptionState&);
229   void send(DOMArrayBuffer*, ExceptionState&);
230   void send(DOMArrayBufferView*, ExceptionState&);
231
232   const AtomicString& getRequestHeader(const AtomicString& name) const;
233   void setRequestHeaderInternal(const AtomicString& name,
234                                 const AtomicString& value);
235
236   void trackProgress(long long dataLength);
237   // Changes m_state and dispatches a readyStateChange event if new m_state
238   // value is different from last one.
239   void changeState(State newState);
240   void dispatchReadyStateChangeEvent();
241
242   // Clears variables used only while the resource is being loaded.
243   void clearVariablesForLoading();
244   // Returns false iff reentry happened and a new load is started.
245   bool internalAbort();
246   // Clears variables holding response header and body data.
247   void clearResponse();
248   void clearRequest();
249
250   void createRequest(PassRefPtr<EncodedFormData>, ExceptionState&);
251
252   // Dispatches a response ProgressEvent.
253   void dispatchProgressEvent(const AtomicString&, long long, long long);
254   // Dispatches a response ProgressEvent using values sampled from
255   // m_receivedLength and m_response.
256   void dispatchProgressEventFromSnapshot(const AtomicString&);
257
258   // Handles didFail() call not caused by cancellation or timeout.
259   void handleNetworkError();
260   // Handles didFail() call for cancellations. For example, the
261   // ResourceLoader handling the load notifies m_loader of an error
262   // cancellation when the frame containing the XHR navigates away.
263   void handleDidCancel();
264   // Handles didFail() call for timeout.
265   void handleDidTimeout();
266
267   void handleRequestError(ExceptionCode,
268                           const AtomicString&,
269                           long long,
270                           long long);
271
272   XMLHttpRequestProgressEventThrottle& progressEventThrottle();
273
274   Member<XMLHttpRequestUpload> m_upload;
275
276   KURL m_url;
277   AtomicString m_method;
278   HTTPHeaderMap m_requestHeaders;
279   // Not converted to ASCII lowercase. Must be lowered later or compared
280   // using case insensitive comparison functions if needed.
281   AtomicString m_mimeTypeOverride;
282   unsigned long m_timeoutMilliseconds;
283   TraceWrapperMember<Blob> m_responseBlob;
284
285   Member<ThreadableLoader> m_loader;
286   State m_state;
287
288   ResourceResponse m_response;
289   String m_finalResponseCharset;
290
291   std::unique_ptr<TextResourceDecoder> m_decoder;
292
293   ScriptString m_responseText;
294   TraceWrapperMember<Document> m_responseDocument;
295   Member<DocumentParser> m_responseDocumentParser;
296
297   RefPtr<SharedBuffer> m_binaryResponseBuilder;
298   long long m_lengthDownloadedToFile;
299
300   TraceWrapperMember<DOMArrayBuffer> m_responseArrayBuffer;
301
302   // Used for onprogress tracking
303   long long m_receivedLength;
304
305   // An exception to throw in synchronous mode. It's set when failure
306   // notification is received from m_loader and thrown at the end of send() if
307   // any.
308   ExceptionCode m_exceptionCode;
309
310   Member<XMLHttpRequestProgressEventThrottle> m_progressEventThrottle;
311
312   // An enum corresponding to the allowed string values for the responseType
313   // attribute.
314   ResponseTypeCode m_responseTypeCode;
315   RefPtr<SecurityOrigin> m_isolatedWorldSecurityOrigin;
316
317   // This blob loader will be used if |m_downloadingToFile| is true and
318   // |m_responseTypeCode| is NOT ResponseTypeBlob.
319   Member<BlobLoader> m_blobLoader;
320
321   // Positive if we are dispatching events.
322   // This is an integer specifying the recursion level rather than a boolean
323   // because in some cases we have recursive dispatching.
324   int m_eventDispatchRecursionLevel;
325
326   bool m_async;
327   bool m_includeCredentials;
328   // Used to skip m_responseDocument creation if it's done previously. We need
329   // this separate flag since m_responseDocument can be 0 for some cases.
330   bool m_parsedResponse;
331   bool m_error;
332   bool m_uploadEventsAllowed;
333   bool m_uploadComplete;
334   bool m_sameOriginRequest;
335   // True iff the ongoing resource loading is using the downloadToFile
336   // option.
337   bool m_downloadingToFile;
338   bool m_responseTextOverflow;
339   bool m_sendFlag;
340 };
341
342 std::ostream& operator<<(std::ostream&, const XMLHttpRequest*);
343
344 }  // namespace blink
345
346 #endif  // XMLHttpRequest_h