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
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.
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.
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,
23 #ifndef XMLHttpRequest_h
24 #define XMLHttpRequest_h
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"
51 class ArrayBufferOrArrayBufferViewOrBlobOrDocumentOrStringOrFormData;
55 class DOMArrayBufferView;
59 class ExecutionContext;
63 class TextResourceDecoder;
64 class ThreadableLoader;
65 class WebDataConsumerHandle;
66 class XMLHttpRequestUpload;
68 typedef int ExceptionCode;
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);
79 static XMLHttpRequest* create(ScriptState*);
80 static XMLHttpRequest* create(ExecutionContext*);
81 ~XMLHttpRequest() override;
83 // These exact numeric values are important because JS expects them.
92 enum ResponseTypeCode {
98 ResponseTypeArrayBuffer,
102 void contextDestroyed() override;
103 ExecutionContext* getExecutionContext() const override;
104 void suspend() override;
105 void resume() override;
108 bool hasPendingActivity() const final;
110 // XMLHttpRequestEventTarget
111 const AtomicString& interfaceName() const override;
113 // JavaScript attributes and methods
114 const KURL& url() const { return m_url; }
115 String statusText() 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,
124 const String& username,
125 const String& password,
127 void open(const AtomicString& method,
132 const ArrayBufferOrArrayBufferViewOrBlobOrDocumentOrStringOrFormData&,
135 void setRequestHeader(const AtomicString& name,
136 const AtomicString& value,
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();
154 void sendForInspectorXHRReplay(PassRefPtr<EncodedFormData>, ExceptionState&);
156 XMLHttpRequestUpload* upload();
157 bool isAsync() { return m_async; }
159 DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
161 // (Also) eagerly finalized so as to prevent access to the eagerly finalized
162 // progress event throttle.
164 DECLARE_VIRTUAL_TRACE();
165 DECLARE_TRACE_WRAPPERS();
169 XMLHttpRequest(ExecutionContext*, PassRefPtr<SecurityOrigin>);
171 Document* document() const;
172 SecurityOrigin* getSecurityOrigin() const;
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;
187 // BlobLoader notifications.
188 void didFinishLoadingInternal();
189 void didFinishLoadingFromBlob();
190 void didFailLoadingFromBlob();
192 PassRefPtr<BlobDataHandle> createBlobDataHandleFromResponse();
194 // DocumentParserClient
195 void notifyParserStopped() override;
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.
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;
214 std::unique_ptr<TextResourceDecoder> createDecoder() const;
216 void initResponseDocument();
217 void parseDocumentChunk(const char* data, unsigned dataLength);
219 bool areMethodAndURLValidForSend();
221 void throwForLoadFailureIfNeeded(ExceptionState&, const String&);
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&);
232 const AtomicString& getRequestHeader(const AtomicString& name) const;
233 void setRequestHeaderInternal(const AtomicString& name,
234 const AtomicString& value);
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();
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();
250 void createRequest(PassRefPtr<EncodedFormData>, ExceptionState&);
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&);
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();
267 void handleRequestError(ExceptionCode,
272 XMLHttpRequestProgressEventThrottle& progressEventThrottle();
274 Member<XMLHttpRequestUpload> m_upload;
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;
285 Member<ThreadableLoader> m_loader;
288 ResourceResponse m_response;
289 String m_finalResponseCharset;
291 std::unique_ptr<TextResourceDecoder> m_decoder;
293 ScriptString m_responseText;
294 TraceWrapperMember<Document> m_responseDocument;
295 Member<DocumentParser> m_responseDocumentParser;
297 RefPtr<SharedBuffer> m_binaryResponseBuilder;
298 long long m_lengthDownloadedToFile;
300 TraceWrapperMember<DOMArrayBuffer> m_responseArrayBuffer;
302 // Used for onprogress tracking
303 long long m_receivedLength;
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
308 ExceptionCode m_exceptionCode;
310 Member<XMLHttpRequestProgressEventThrottle> m_progressEventThrottle;
312 // An enum corresponding to the allowed string values for the responseType
314 ResponseTypeCode m_responseTypeCode;
315 RefPtr<SecurityOrigin> m_isolatedWorldSecurityOrigin;
317 // This blob loader will be used if |m_downloadingToFile| is true and
318 // |m_responseTypeCode| is NOT ResponseTypeBlob.
319 Member<BlobLoader> m_blobLoader;
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;
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;
332 bool m_uploadEventsAllowed;
333 bool m_uploadComplete;
334 bool m_sameOriginRequest;
335 // True iff the ongoing resource loading is using the downloadToFile
337 bool m_downloadingToFile;
338 bool m_responseTextOverflow;
342 std::ostream& operator<<(std::ostream&, const XMLHttpRequest*);
346 #endif // XMLHttpRequest_h