Coverage Report

Created: 2025-08-28 06:26

/src/serenity/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
3
 * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
4
 * Copyright (c) 2022-2023, Luke Wilde <lukew@serenityos.org>
5
 * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
6
 * Copyright (c) 2022-2024, Kenneth Myhra <kennethmyhra@serenityos.org>
7
 *
8
 * SPDX-License-Identifier: BSD-2-Clause
9
 */
10
11
#include <AK/ByteBuffer.h>
12
#include <AK/Debug.h>
13
#include <AK/GenericLexer.h>
14
#include <AK/QuickSort.h>
15
#include <LibJS/Runtime/ArrayBuffer.h>
16
#include <LibJS/Runtime/Completion.h>
17
#include <LibJS/Runtime/FunctionObject.h>
18
#include <LibJS/Runtime/GlobalObject.h>
19
#include <LibTextCodec/Decoder.h>
20
#include <LibURL/Origin.h>
21
#include <LibWeb/Bindings/XMLHttpRequestPrototype.h>
22
#include <LibWeb/DOM/Document.h>
23
#include <LibWeb/DOM/DocumentLoading.h>
24
#include <LibWeb/DOM/Event.h>
25
#include <LibWeb/DOM/EventDispatcher.h>
26
#include <LibWeb/DOM/IDLEventListener.h>
27
#include <LibWeb/DOM/XMLDocument.h>
28
#include <LibWeb/DOMURL/DOMURL.h>
29
#include <LibWeb/Fetch/BodyInit.h>
30
#include <LibWeb/Fetch/Fetching/Fetching.h>
31
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
32
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
33
#include <LibWeb/Fetch/Infrastructure/HTTP.h>
34
#include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
35
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
36
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
37
#include <LibWeb/FileAPI/Blob.h>
38
#include <LibWeb/HTML/EventHandler.h>
39
#include <LibWeb/HTML/EventNames.h>
40
#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>
41
#include <LibWeb/HTML/Parser/HTMLParser.h>
42
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
43
#include <LibWeb/HTML/Window.h>
44
#include <LibWeb/Infra/ByteSequences.h>
45
#include <LibWeb/Infra/JSON.h>
46
#include <LibWeb/Infra/Strings.h>
47
#include <LibWeb/Loader/ResourceLoader.h>
48
#include <LibWeb/Page/Page.h>
49
#include <LibWeb/Platform/EventLoopPlugin.h>
50
#include <LibWeb/WebIDL/DOMException.h>
51
#include <LibWeb/WebIDL/ExceptionOr.h>
52
#include <LibWeb/XHR/EventNames.h>
53
#include <LibWeb/XHR/ProgressEvent.h>
54
#include <LibWeb/XHR/XMLHttpRequest.h>
55
#include <LibWeb/XHR/XMLHttpRequestUpload.h>
56
57
namespace Web::XHR {
58
59
JS_DEFINE_ALLOCATOR(XMLHttpRequest);
60
61
WebIDL::ExceptionOr<JS::NonnullGCPtr<XMLHttpRequest>> XMLHttpRequest::construct_impl(JS::Realm& realm)
62
0
{
63
0
    auto upload_object = realm.heap().allocate<XMLHttpRequestUpload>(realm, realm);
64
0
    auto author_request_headers = Fetch::Infrastructure::HeaderList::create(realm.vm());
65
0
    auto response = Fetch::Infrastructure::Response::network_error(realm.vm(), "Not sent yet"sv);
66
0
    auto fetch_controller = Fetch::Infrastructure::FetchController::create(realm.vm());
67
0
    return realm.heap().allocate<XMLHttpRequest>(realm, realm, *upload_object, *author_request_headers, *response, *fetch_controller);
68
0
}
69
70
XMLHttpRequest::XMLHttpRequest(JS::Realm& realm, XMLHttpRequestUpload& upload_object, Fetch::Infrastructure::HeaderList& author_request_headers, Fetch::Infrastructure::Response& response, Fetch::Infrastructure::FetchController& fetch_controller)
71
0
    : XMLHttpRequestEventTarget(realm)
72
0
    , m_upload_object(upload_object)
73
0
    , m_author_request_headers(author_request_headers)
74
0
    , m_response(response)
75
0
    , m_response_type(Bindings::XMLHttpRequestResponseType::Empty)
76
0
    , m_fetch_controller(fetch_controller)
77
0
{
78
0
    set_overrides_must_survive_garbage_collection(true);
79
0
}
80
81
0
XMLHttpRequest::~XMLHttpRequest() = default;
82
83
void XMLHttpRequest::initialize(JS::Realm& realm)
84
0
{
85
0
    Base::initialize(realm);
86
0
    WEB_SET_PROTOTYPE_FOR_INTERFACE(XMLHttpRequest);
87
0
}
88
89
void XMLHttpRequest::visit_edges(Cell::Visitor& visitor)
90
0
{
91
0
    Base::visit_edges(visitor);
92
0
    visitor.visit(m_upload_object);
93
0
    visitor.visit(m_author_request_headers);
94
0
    visitor.visit(m_request_body);
95
0
    visitor.visit(m_response);
96
0
    visitor.visit(m_fetch_controller);
97
98
0
    if (auto* value = m_response_object.get_pointer<JS::NonnullGCPtr<JS::Object>>())
99
0
        visitor.visit(*value);
100
0
}
101
102
// https://xhr.spec.whatwg.org/#concept-event-fire-progress
103
static void fire_progress_event(XMLHttpRequestEventTarget& target, FlyString const& event_name, u64 transmitted, u64 length)
104
0
{
105
    // To fire a progress event named e at target, given transmitted and length, means to fire an event named e at target, using ProgressEvent,
106
    // with the loaded attribute initialized to transmitted, and if length is not 0, with the lengthComputable attribute initialized to true
107
    // and the total attribute initialized to length.
108
0
    ProgressEventInit event_init {};
109
0
    event_init.length_computable = length;
110
0
    event_init.loaded = transmitted;
111
0
    event_init.total = length;
112
    // FIXME: If we're in an async context, this will propagate to a callback context which can't propagate it anywhere else and does not expect this to fail.
113
0
    target.dispatch_event(*ProgressEvent::create(target.realm(), event_name, event_init));
114
0
}
115
116
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext
117
WebIDL::ExceptionOr<String> XMLHttpRequest::response_text() const
118
0
{
119
    // 1. If this’s response type is not the empty string or "text", then throw an "InvalidStateError" DOMException.
120
0
    if (m_response_type != Bindings::XMLHttpRequestResponseType::Empty && m_response_type != Bindings::XMLHttpRequestResponseType::Text)
121
0
        return WebIDL::InvalidStateError::create(realm(), "XHR responseText can only be used for responseType \"\" or \"text\""_string);
122
123
    // 2. If this’s state is not loading or done, then return the empty string.
124
0
    if (m_state != State::Loading && m_state != State::Done)
125
0
        return String {};
126
127
    // 3. Return the result of getting a text response for this.
128
0
    return get_text_response();
129
0
}
130
131
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsexml
132
WebIDL::ExceptionOr<JS::GCPtr<DOM::Document>> XMLHttpRequest::response_xml()
133
0
{
134
    // 1. If this’s response type is not the empty string or "document", then throw an "InvalidStateError" DOMException.
135
0
    if (m_response_type != Bindings::XMLHttpRequestResponseType::Empty && m_response_type != Bindings::XMLHttpRequestResponseType::Document)
136
0
        return WebIDL::InvalidStateError::create(realm(), "XHR responseXML can only be used for responseXML \"\" or \"document\""_string);
137
138
    // 2. If this’s state is not done, then return null.
139
0
    if (m_state != State::Done)
140
0
        return nullptr;
141
142
    // 3. Assert: this’s response object is not failure.
143
0
    VERIFY(!m_response_object.has<Failure>());
144
145
    // 4. If this’s response object is non-null, then return it.
146
0
    if (!m_response_object.has<Empty>())
147
0
        return &verify_cast<DOM::Document>(*m_response_object.get<JS::NonnullGCPtr<JS::Object>>());
148
149
    // 5. Set a document response for this.
150
0
    set_document_response();
151
152
    // 6. Return this’s response object.
153
0
    if (m_response_object.has<Empty>())
154
0
        return nullptr;
155
0
    return &verify_cast<DOM::Document>(*m_response_object.get<JS::NonnullGCPtr<JS::Object>>());
156
0
}
157
158
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype
159
WebIDL::ExceptionOr<void> XMLHttpRequest::set_response_type(Bindings::XMLHttpRequestResponseType response_type)
160
0
{
161
    // 1. If the current global object is not a Window object and the given value is "document", then return.
162
0
    if (!is<HTML::Window>(HTML::current_global_object()) && response_type == Bindings::XMLHttpRequestResponseType::Document)
163
0
        return {};
164
165
    // 2. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
166
0
    if (m_state == State::Loading || m_state == State::Done)
167
0
        return WebIDL::InvalidStateError::create(realm(), "Can't readyState when XHR is loading or done"_string);
168
169
    // 3. If the current global object is a Window object and this’s synchronous flag is set, then throw an "InvalidAccessError" DOMException.
170
0
    if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
171
0
        return WebIDL::InvalidAccessError::create(realm(), "Can't set readyState on synchronous XHR in Window environment"_string);
172
173
    // 4. Set this’s response type to the given value.
174
0
    m_response_type = response_type;
175
0
    return {};
176
0
}
177
178
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-response
179
WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response()
180
0
{
181
0
    auto& vm = this->vm();
182
183
    // 1. If this’s response type is the empty string or "text", then:
184
0
    if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty || m_response_type == Bindings::XMLHttpRequestResponseType::Text) {
185
        // 1. If this’s state is not loading or done, then return the empty string.
186
0
        if (m_state != State::Loading && m_state != State::Done)
187
0
            return JS::PrimitiveString::create(vm, String {});
188
189
        // 2. Return the result of getting a text response for this.
190
0
        return JS::PrimitiveString::create(vm, get_text_response());
191
0
    }
192
    // 2. If this’s state is not done, then return null.
193
0
    if (m_state != State::Done)
194
0
        return JS::js_null();
195
196
    // 3. If this’s response object is failure, then return null.
197
0
    if (m_response_object.has<Failure>())
198
0
        return JS::js_null();
199
200
    // 4. If this’s response object is non-null, then return it.
201
0
    if (!m_response_object.has<Empty>())
202
0
        return m_response_object.get<JS::NonnullGCPtr<JS::Object>>();
203
204
    // 5. If this’s response type is "arraybuffer",
205
0
    if (m_response_type == Bindings::XMLHttpRequestResponseType::Arraybuffer) {
206
        // then set this’s response object to a new ArrayBuffer object representing this’s received bytes. If this throws an exception, then set this’s response object to failure and return null.
207
0
        auto buffer_result = JS::ArrayBuffer::create(realm(), m_received_bytes.size());
208
0
        if (buffer_result.is_error()) {
209
0
            m_response_object = Failure();
210
0
            return JS::js_null();
211
0
        }
212
213
0
        auto buffer = buffer_result.release_value();
214
0
        buffer->buffer().overwrite(0, m_received_bytes.data(), m_received_bytes.size());
215
0
        m_response_object = JS::NonnullGCPtr<JS::Object> { buffer };
216
0
    }
217
    // 6. Otherwise, if this’s response type is "blob", set this’s response object to a new Blob object representing this’s received bytes with type set to the result of get a final MIME type for this.
218
0
    else if (m_response_type == Bindings::XMLHttpRequestResponseType::Blob) {
219
0
        auto mime_type_as_string = get_final_mime_type().serialized();
220
0
        auto blob_part = FileAPI::Blob::create(realm(), m_received_bytes, move(mime_type_as_string));
221
0
        auto blob = FileAPI::Blob::create(realm(), Vector<FileAPI::BlobPart> { JS::make_handle(*blob_part) });
222
0
        m_response_object = JS::NonnullGCPtr<JS::Object> { blob };
223
0
    }
224
    // 7. Otherwise, if this’s response type is "document", set a document response for this.
225
0
    else if (m_response_type == Bindings::XMLHttpRequestResponseType::Document) {
226
0
        set_document_response();
227
0
    }
228
    // 8. Otherwise:
229
0
    else {
230
        // 1. Assert: this’s response type is "json".
231
        // Note: Automatically done by the layers above us.
232
233
        // 2. If this’s response’s body is null, then return null.
234
0
        if (!m_response->body())
235
0
            return JS::js_null();
236
237
        // 3. Let jsonObject be the result of running parse JSON from bytes on this’s received bytes. If that threw an exception, then return null.
238
0
        auto json_object_result = Infra::parse_json_bytes_to_javascript_value(realm(), m_received_bytes);
239
0
        if (json_object_result.is_error())
240
0
            return JS::js_null();
241
242
        // 4. Set this’s response object to jsonObject.
243
0
        if (json_object_result.value().is_object())
244
0
            m_response_object = JS::NonnullGCPtr<JS::Object> { json_object_result.release_value().as_object() };
245
0
        else
246
0
            m_response_object = Empty {};
247
0
    }
248
249
    // 9. Return this’s response object.
250
0
    return m_response_object.visit(
251
0
        [](JS::NonnullGCPtr<JS::Object> object) -> JS::Value { return object; },
252
0
        [](auto const&) -> JS::Value { return JS::js_null(); });
Unexecuted instantiation: XMLHttpRequest.cpp:JS::Value Web::XHR::XMLHttpRequest::response()::$_1::operator()<Web::XHR::XMLHttpRequest::Failure>(Web::XHR::XMLHttpRequest::Failure const&) const
Unexecuted instantiation: XMLHttpRequest.cpp:JS::Value Web::XHR::XMLHttpRequest::response()::$_1::operator()<AK::Empty>(AK::Empty const&) const
253
0
}
254
255
// https://xhr.spec.whatwg.org/#text-response
256
String XMLHttpRequest::get_text_response() const
257
0
{
258
    // 1. If xhr’s response’s body is null, then return the empty string.
259
0
    if (!m_response->body())
260
0
        return String {};
261
262
    // 2. Let charset be the result of get a final encoding for xhr.
263
0
    auto charset = get_final_encoding();
264
265
    // 3. If xhr’s response type is the empty string, charset is null, and the result of get a final MIME type for xhr is an XML MIME type,
266
0
    if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty && !charset.has_value() && get_final_mime_type().is_xml()) {
267
        // FIXME: then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
268
0
    }
269
270
    // 4. If charset is null, then set charset to UTF-8.
271
0
    if (!charset.has_value())
272
0
        charset = "UTF-8"sv;
273
274
    // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.
275
0
    auto decoder = TextCodec::decoder_for(charset.value());
276
277
    // If we don't support the decoder yet, let's crash instead of attempting to return something, as the result would be incorrect and create obscure bugs.
278
0
    VERIFY(decoder.has_value());
279
280
0
    return TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, m_received_bytes).release_value_but_fixme_should_propagate_errors();
281
0
}
282
283
// https://xhr.spec.whatwg.org/#document-response
284
void XMLHttpRequest::set_document_response()
285
0
{
286
    // 1. If xhr’s response’s body is null, then return.
287
0
    if (!m_response->body())
288
0
        return;
289
290
    // 2. Let finalMIME be the result of get a final MIME type for xhr.
291
0
    auto final_mime = get_final_mime_type();
292
293
    // 3. If finalMIME is not an HTML MIME type or an XML MIME type, then return.
294
0
    if (!final_mime.is_html() && !final_mime.is_xml())
295
0
        return;
296
297
    // 4. If xhr’s response type is the empty string and finalMIME is an HTML MIME type, then return.
298
0
    if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty && final_mime.is_html())
299
0
        return;
300
301
    // 5. If finalMIME is an HTML MIME type, then:
302
0
    Optional<String> charset;
303
0
    JS::GCPtr<DOM::Document> document;
304
0
    if (final_mime.is_html()) {
305
        // 5.1. Let charset be the result of get a final encoding for xhr.
306
0
        if (auto final_encoding = get_final_encoding(); final_encoding.has_value())
307
0
            charset = MUST(String::from_utf8(*final_encoding));
308
309
        // 5.2. If charset is null, prescan the first 1024 bytes of xhr’s received bytes and if that does not terminate unsuccessfully then let charset be the return value.
310
0
        document = DOM::Document::create(realm());
311
0
        if (!charset.has_value())
312
0
            if (auto found_charset = HTML::run_prescan_byte_stream_algorithm(*document, m_received_bytes); found_charset.has_value())
313
0
                charset = MUST(String::from_byte_string(found_charset.value()));
314
315
        // 5.3. If charset is null, then set charset to UTF-8.
316
0
        if (!charset.has_value())
317
0
            charset = "UTF-8"_string;
318
319
        // 5.4. Let document be a document that represents the result parsing xhr’s received bytes following the rules set forth in the HTML Standard for an HTML parser with scripting disabled and a known definite encoding charset.
320
0
        auto parser = HTML::HTMLParser::create(*document, m_received_bytes, charset.value());
321
0
        parser->run(document->url());
322
323
        // 5.5. Flag document as an HTML document.
324
0
        document->set_document_type(DOM::Document::Type::HTML);
325
0
    }
326
327
    // 6. Otherwise, let document be a document that represents the result of running the XML parser with XML scripting support disabled on xhr’s received bytes. If that fails (unsupported character encoding, namespace well-formedness error, etc.), then return null.
328
0
    else {
329
0
        document = DOM::XMLDocument::create(realm(), m_response->url().value_or({}));
330
0
        if (!Web::build_xml_document(*document, m_received_bytes, {})) {
331
0
            m_response_object = Empty {};
332
0
            return;
333
0
        }
334
0
    }
335
336
    // 7. If charset is null, then set charset to UTF-8.
337
0
    if (!charset.has_value())
338
0
        charset = "UTF-8"_string;
339
340
    // 8. Set document’s encoding to charset.
341
0
    document->set_encoding(move(charset));
342
343
    // 9. Set document’s content type to finalMIME.
344
0
    document->set_content_type(final_mime.serialized());
345
346
    // 10. Set document’s URL to xhr’s response’s URL.
347
0
    document->set_url(m_response->url().value_or({}));
348
349
    // 11. Set document’s origin to xhr’s relevant settings object’s origin.
350
0
    document->set_origin(HTML::relevant_settings_object(*this).origin());
351
352
    // 12. Set xhr’s response object to document.
353
0
    m_response_object = JS::NonnullGCPtr<JS::Object> { *document };
354
0
}
355
356
// https://xhr.spec.whatwg.org/#final-mime-type
357
MimeSniff::MimeType XMLHttpRequest::get_final_mime_type() const
358
0
{
359
    // 1. If xhr’s override MIME type is null, return the result of get a response MIME type for xhr.
360
0
    if (!m_override_mime_type.has_value())
361
0
        return get_response_mime_type();
362
363
    // 2. Return xhr’s override MIME type.
364
0
    return *m_override_mime_type;
365
0
}
366
367
// https://xhr.spec.whatwg.org/#response-mime-type
368
MimeSniff::MimeType XMLHttpRequest::get_response_mime_type() const
369
0
{
370
    // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.
371
0
    auto mime_type = m_response->header_list()->extract_mime_type();
372
373
    // 2. If mimeType is failure, then set mimeType to text/xml.
374
0
    if (!mime_type.has_value())
375
0
        return MimeSniff::MimeType::create("text"_string, "xml"_string);
376
377
    // 3. Return mimeType.
378
0
    return mime_type.release_value();
379
0
}
380
381
// https://xhr.spec.whatwg.org/#final-charset
382
Optional<StringView> XMLHttpRequest::get_final_encoding() const
383
0
{
384
    // 1. Let label be null.
385
0
    Optional<String> label;
386
387
    // 2. Let responseMIME be the result of get a response MIME type for xhr.
388
0
    auto response_mime = get_response_mime_type();
389
390
    // 3. If responseMIME’s parameters["charset"] exists, then set label to it.
391
0
    auto response_mime_charset_it = response_mime.parameters().find("charset"sv);
392
0
    if (response_mime_charset_it != response_mime.parameters().end())
393
0
        label = response_mime_charset_it->value;
394
395
    // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
396
0
    if (m_override_mime_type.has_value()) {
397
0
        auto override_mime_charset_it = m_override_mime_type->parameters().find("charset"sv);
398
0
        if (override_mime_charset_it != m_override_mime_type->parameters().end())
399
0
            label = override_mime_charset_it->value;
400
0
    }
401
402
    // 5. If label is null, then return null.
403
0
    if (!label.has_value())
404
0
        return OptionalNone {};
405
406
    // 6. Let encoding be the result of getting an encoding from label.
407
0
    auto encoding = TextCodec::get_standardized_encoding(label.value());
408
409
    // 7. If encoding is failure, then return null.
410
    // 8. Return encoding.
411
0
    return encoding;
412
0
}
413
414
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
415
WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(String const& name_string, String const& value_string)
416
0
{
417
0
    auto& realm = this->realm();
418
419
0
    auto name = name_string.bytes();
420
0
    auto value = value_string.bytes();
421
422
    // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
423
0
    if (m_state != State::Opened)
424
0
        return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED"_string);
425
426
    // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
427
0
    if (m_send)
428
0
        return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set"_string);
429
430
    // 3. Normalize value.
431
0
    auto normalized_value = Fetch::Infrastructure::normalize_header_value(value);
432
433
    // 4. If name is not a header name or value is not a header value, then throw a "SyntaxError" DOMException.
434
0
    if (!Fetch::Infrastructure::is_header_name(name))
435
0
        return WebIDL::SyntaxError::create(realm, "Header name contains invalid characters."_string);
436
0
    if (!Fetch::Infrastructure::is_header_value(value))
437
0
        return WebIDL::SyntaxError::create(realm, "Header value contains invalid characters."_string);
438
439
0
    auto header = Fetch::Infrastructure::Header {
440
0
        .name = MUST(ByteBuffer::copy(name)),
441
0
        .value = move(normalized_value),
442
0
    };
443
444
    // 5. If (name, value) is a forbidden request-header, then return.
445
0
    if (Fetch::Infrastructure::is_forbidden_request_header(header))
446
0
        return {};
447
448
    // 6. Combine (name, value) in this’s author request headers.
449
0
    m_author_request_headers->combine(move(header));
450
451
0
    return {};
452
0
}
453
454
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
455
WebIDL::ExceptionOr<void> XMLHttpRequest::open(String const& method_string, String const& url)
456
0
{
457
    // 7. If the async argument is omitted, set async to true, and set username and password to null.
458
0
    return open(method_string, url, true, Optional<String> {}, Optional<String> {});
459
0
}
460
461
WebIDL::ExceptionOr<void> XMLHttpRequest::open(String const& method_string, String const& url, bool async, Optional<String> const& username, Optional<String> const& password)
462
0
{
463
0
    auto method = method_string.bytes();
464
465
    // 1. If this’s relevant global object is a Window object and its associated Document is not fully active, then throw an "InvalidStateError" DOMException.
466
0
    if (is<HTML::Window>(HTML::relevant_global_object(*this))) {
467
0
        auto const& window = static_cast<HTML::Window const&>(HTML::relevant_global_object(*this));
468
0
        if (!window.associated_document().is_fully_active())
469
0
            return WebIDL::InvalidStateError::create(realm(), "Invalid state: Window's associated document is not fully active."_string);
470
0
    }
471
472
    // 2. If method is not a method, then throw a "SyntaxError" DOMException.
473
0
    if (!Fetch::Infrastructure::is_method(method))
474
0
        return WebIDL::SyntaxError::create(realm(), "An invalid or illegal string was specified."_string);
475
476
    // 3. If method is a forbidden method, then throw a "SecurityError" DOMException.
477
0
    if (Fetch::Infrastructure::is_forbidden_method(method))
478
0
        return WebIDL::SecurityError::create(realm(), "Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'"_string);
479
480
    // 4. Normalize method.
481
0
    auto normalized_method = Fetch::Infrastructure::normalize_method(method);
482
483
    // 5. Let parsedURL be the result of parsing url with this’s relevant settings object’s API base URL and this’s relevant settings object’s API URL character encoding.
484
0
    auto& relevant_settings_object = HTML::relevant_settings_object(*this);
485
0
    auto api_base_url = relevant_settings_object.api_base_url();
486
0
    auto api_url_character_encoding = relevant_settings_object.api_url_character_encoding();
487
0
    auto parsed_url = DOMURL::parse(url, api_base_url, api_url_character_encoding);
488
489
    // 6. If parsedURL is failure, then throw a "SyntaxError" DOMException.
490
0
    if (!parsed_url.is_valid())
491
0
        return WebIDL::SyntaxError::create(realm(), "Invalid URL"_string);
492
493
    // 7. If the async argument is omitted, set async to true, and set username and password to null.
494
    // NOTE: This is handled in the overload lacking the async argument.
495
496
    // 8. If parsedURL’s host is non-null, then:
497
0
    if (!parsed_url.host().has<Empty>()) {
498
        // 1. If the username argument is not null, set the username given parsedURL and username.
499
0
        if (username.has_value())
500
0
            parsed_url.set_username(username.value());
501
        // 2. If the password argument is not null, set the password given parsedURL and password.
502
0
        if (password.has_value())
503
0
            parsed_url.set_password(password.value());
504
0
    }
505
506
    // 9. If async is false, the current global object is a Window object, and either this’s timeout is
507
    //     not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
508
0
    if (!async
509
0
        && is<HTML::Window>(HTML::current_global_object())
510
0
        && (m_timeout != 0 || m_response_type != Bindings::XMLHttpRequestResponseType::Empty)) {
511
0
        return WebIDL::InvalidAccessError::create(realm(), "Synchronous XMLHttpRequests in a Window context do not support timeout or a non-empty responseType"_string);
512
0
    }
513
514
    // 10. Terminate this’s fetch controller.
515
    // Spec Note: A fetch can be ongoing at this point.
516
0
    m_fetch_controller->terminate();
517
518
    // 11. Set variables associated with the object as follows:
519
    // Unset this’s send() flag.
520
0
    m_send = false;
521
    // Unset this’s upload listener flag.
522
0
    m_upload_listener = false;
523
    // Set this’s request method to method.
524
0
    m_request_method = normalized_method.span();
525
    // Set this’s request URL to parsedURL.
526
0
    m_request_url = parsed_url;
527
    // Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
528
0
    m_synchronous = !async;
529
    // Empty this’s author request headers.
530
0
    m_author_request_headers->clear();
531
    // Set this’s response to a network error.
532
0
    m_response = Fetch::Infrastructure::Response::network_error(realm().vm(), "Not yet sent"sv);
533
    // Set this’s received bytes to the empty byte sequence.
534
0
    m_received_bytes = {};
535
    // Set this’s response object to null.
536
0
    m_response_object = {};
537
    // Spec Note: Override MIME type is not overridden here as the overrideMimeType() method can be invoked before the open() method.
538
539
    // 12. If this’s state is not opened, then:
540
0
    if (m_state != State::Opened) {
541
        // 1. Set this’s state to opened.
542
0
        m_state = State::Opened;
543
544
        // 2. Fire an event named readystatechange at this.
545
0
        dispatch_event(DOM::Event::create(realm(), EventNames::readystatechange));
546
0
    }
547
548
0
    return {};
549
0
}
550
551
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
552
WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequestBodyInit> body)
553
0
{
554
0
    auto& vm = this->vm();
555
0
    auto& realm = *vm.current_realm();
556
557
    // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
558
0
    if (m_state != State::Opened)
559
0
        return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED"_string);
560
561
    // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
562
0
    if (m_send)
563
0
        return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set"_string);
564
565
    // 3. If this’s request method is `GET` or `HEAD`, then set body to null.
566
0
    if (m_request_method.is_one_of("GET"sv, "HEAD"sv))
567
0
        body = {};
568
569
    // 4. If body is not null, then:
570
0
    if (body.has_value()) {
571
        // 1. Let extractedContentType be null.
572
0
        Optional<ByteBuffer> extracted_content_type;
573
574
        // 2. If body is a Document, then set this’s request body to body, serialized, converted, and UTF-8 encoded.
575
0
        if (body->has<JS::Handle<DOM::Document>>()) {
576
0
            auto string_serialized_document = TRY(body->get<JS::Handle<DOM::Document>>().cell()->serialize_fragment(DOMParsing::RequireWellFormed::No));
577
0
            m_request_body = TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, string_serialized_document.bytes()));
578
0
        }
579
        // 3. Otherwise:
580
0
        else {
581
            // 1. Let bodyWithType be the result of safely extracting body.
582
0
            auto body_with_type = TRY(Fetch::safely_extract_body(realm, body->downcast<Fetch::BodyInitOrReadableBytes>()));
583
584
            // 2. Set this’s request body to bodyWithType’s body.
585
0
            m_request_body = move(body_with_type.body);
586
587
            // 3. Set extractedContentType to bodyWithType’s type.
588
0
            extracted_content_type = move(body_with_type.type);
589
0
        }
590
591
        // 4. Let originalAuthorContentType be the result of getting `Content-Type` from this’s author request headers.
592
0
        auto original_author_content_type = m_author_request_headers->get("Content-Type"sv.bytes());
593
594
        // 5. If originalAuthorContentType is non-null, then:
595
0
        if (original_author_content_type.has_value()) {
596
            // 1. If body is a Document or a USVString, then:
597
0
            if (body->has<JS::Handle<DOM::Document>>() || body->has<String>()) {
598
                // 1. Let contentTypeRecord be the result of parsing originalAuthorContentType.
599
0
                auto content_type_record = MimeSniff::MimeType::parse(original_author_content_type.value());
600
601
                // 2. If contentTypeRecord is not failure, contentTypeRecord’s parameters["charset"] exists, and parameters["charset"] is not an ASCII case-insensitive match for "UTF-8", then:
602
0
                if (content_type_record.has_value()) {
603
0
                    auto charset_parameter_iterator = content_type_record->parameters().find("charset"sv);
604
0
                    if (charset_parameter_iterator != content_type_record->parameters().end() && !Infra::is_ascii_case_insensitive_match(charset_parameter_iterator->value, "UTF-8"sv)) {
605
                        // 1. Set contentTypeRecord’s parameters["charset"] to "UTF-8".
606
0
                        content_type_record->set_parameter("charset"_string, "UTF-8"_string);
607
608
                        // 2. Let newContentTypeSerialized be the result of serializing contentTypeRecord.
609
0
                        auto new_content_type_serialized = content_type_record->serialized();
610
611
                        // 3. Set (`Content-Type`, newContentTypeSerialized) in this’s author request headers.
612
0
                        auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, new_content_type_serialized);
613
0
                        m_author_request_headers->set(move(header));
614
0
                    }
615
0
                }
616
0
            }
617
0
        }
618
        // 6. Otherwise:
619
0
        else {
620
0
            if (body->has<JS::Handle<DOM::Document>>()) {
621
0
                auto document = body->get<JS::Handle<DOM::Document>>();
622
623
                // NOTE: A document can only be an HTML document or XML document.
624
                // 1. If body is an HTML document, then set (`Content-Type`, `text/html;charset=UTF-8`) in this’s author request headers.
625
0
                if (document->is_html_document()) {
626
0
                    auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=UTF-8"sv);
627
0
                    m_author_request_headers->set(move(header));
628
0
                }
629
                // 2. Otherwise, if body is an XML document, set (`Content-Type`, `application/xml;charset=UTF-8`) in this’s author request headers.
630
0
                else if (document->is_xml_document()) {
631
0
                    auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "application/xml;charset=UTF-8"sv);
632
0
                    m_author_request_headers->set(move(header));
633
0
                } else {
634
0
                    VERIFY_NOT_REACHED();
635
0
                }
636
0
            }
637
            // 3. Otherwise, if extractedContentType is not null, set (`Content-Type`, extractedContentType) in this’s author request headers.
638
0
            else if (extracted_content_type.has_value()) {
639
0
                auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, extracted_content_type.value());
640
0
                m_author_request_headers->set(move(header));
641
0
            }
642
0
        }
643
0
    }
644
645
    // 5. If one or more event listeners are registered on this’s upload object, then set this’s upload listener flag.
646
0
    m_upload_listener = m_upload_object->has_event_listeners();
647
648
    // 6. Let req be a new request, initialized as follows:
649
0
    auto request = Fetch::Infrastructure::Request::create(vm);
650
651
    // method
652
    //    This’s request method.
653
0
    request->set_method(MUST(ByteBuffer::copy(m_request_method.bytes())));
654
655
    // URL
656
    //    This’s request URL.
657
0
    request->set_url(m_request_url);
658
659
    // header list
660
    //    This’s author request headers.
661
0
    request->set_header_list(m_author_request_headers);
662
663
    // unsafe-request flag
664
    //    Set.
665
0
    request->set_unsafe_request(true);
666
667
    // body
668
    //    This’s request body.
669
0
    if (m_request_body)
670
0
        request->set_body(JS::NonnullGCPtr { *m_request_body });
671
672
    // client
673
    //    This’s relevant settings object.
674
0
    request->set_client(&HTML::relevant_settings_object(*this));
675
676
    // mode
677
    //    "cors".
678
0
    request->set_mode(Fetch::Infrastructure::Request::Mode::CORS);
679
680
    // use-CORS-preflight flag
681
    //    Set if this’s upload listener flag is set.
682
0
    request->set_use_cors_preflight(m_upload_listener);
683
684
    // credentials mode
685
    //    If this’s cross-origin credentials is true, then "include"; otherwise "same-origin".
686
0
    request->set_credentials_mode(m_cross_origin_credentials ? Fetch::Infrastructure::Request::CredentialsMode::Include : Fetch::Infrastructure::Request::CredentialsMode::SameOrigin);
687
688
    // use-URL-credentials flag
689
    //    Set if this’s request URL includes credentials.
690
0
    request->set_use_url_credentials(m_request_url.includes_credentials());
691
692
    // initiator type
693
    //    "xmlhttprequest".
694
0
    request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::XMLHttpRequest);
695
696
    // 7. Unset this’s upload complete flag.
697
0
    m_upload_complete = false;
698
699
    // 8. Unset this’s timed out flag.
700
0
    m_timed_out = false;
701
702
    // 9. If req’s body is null, then set this’s upload complete flag.
703
    // NOTE: req's body is always m_request_body here, see step 6.
704
0
    if (!m_request_body)
705
0
        m_upload_complete = true;
706
707
    // 10. Set this’s send() flag.
708
0
    m_send = true;
709
710
0
    dbgln_if(SPAM_DEBUG, "{}XHR send from {} to {}", m_synchronous ? "\033[33;1mSynchronous\033[0m " : "", HTML::relevant_settings_object(*this).creation_url, m_request_url);
711
712
    // 11. If this’s synchronous flag is unset, then:
713
0
    if (!m_synchronous) {
714
        // 1. Fire a progress event named loadstart at this with 0 and 0.
715
0
        fire_progress_event(*this, EventNames::loadstart, 0, 0);
716
717
        // 2. Let requestBodyTransmitted be 0.
718
        // NOTE: This is kept on the XHR object itself instead of the stack, as we cannot capture references to stack variables in an async context.
719
0
        m_request_body_transmitted = 0;
720
721
        // 3. Let requestBodyLength be req’s body’s length, if req’s body is non-null; otherwise 0.
722
        // NOTE: req's body is always m_request_body here, see step 6.
723
        // 4. Assert: requestBodyLength is an integer.
724
        // NOTE: This is done to provide a better assertion failure message, whereas below the message would be "m_has_value"
725
0
        if (m_request_body)
726
0
            VERIFY(m_request_body->length().has_value());
727
728
        // NOTE: This is const to allow the callback functions to take a copy of it and know it won't change.
729
0
        auto const request_body_length = m_request_body ? m_request_body->length().value() : 0;
730
731
        // 5. If this’s upload complete flag is unset and this’s upload listener flag is set, then fire a progress event named loadstart at this’s upload object with requestBodyTransmitted and requestBodyLength.
732
0
        if (!m_upload_complete && m_upload_listener)
733
0
            fire_progress_event(m_upload_object, EventNames::loadstart, m_request_body_transmitted, request_body_length);
734
735
        // 6. If this’s state is not opened or this’s send() flag is unset, then return.
736
0
        if (m_state != State::Opened || !m_send)
737
0
            return {};
738
739
        // 7. Let processRequestBodyChunkLength, given a bytesLength, be these steps:
740
        // NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.
741
        // NOTE: `this` is kept alive by FetchAlgorithms using JS::SafeFunction.
742
0
        auto process_request_body_chunk_length = [this, request_body_length](u64 bytes_length) {
743
            // 1. Increase requestBodyTransmitted by bytesLength.
744
0
            m_request_body_transmitted += bytes_length;
745
746
            // FIXME: 2. If not roughly 50ms have passed since these steps were last invoked, then return.
747
748
            // 3. If this’s upload listener flag is set, then fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.
749
0
            if (m_upload_listener)
750
0
                fire_progress_event(m_upload_object, EventNames::progress, m_request_body_transmitted, request_body_length);
751
0
        };
752
753
        // 8. Let processRequestEndOfBody be these steps:
754
        // NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.
755
        // NOTE: `this` is kept alive by FetchAlgorithms using JS::SafeFunction.
756
0
        auto process_request_end_of_body = [this, request_body_length]() {
757
            // 1. Set this’s upload complete flag.
758
0
            m_upload_complete = true;
759
760
            // 2. If this’s upload listener flag is unset, then return.
761
0
            if (!m_upload_listener)
762
0
                return;
763
764
            // 3. Fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.
765
0
            fire_progress_event(m_upload_object, EventNames::progress, m_request_body_transmitted, request_body_length);
766
767
            // 4. Fire a progress event named load at this’s upload object with requestBodyTransmitted and requestBodyLength.
768
0
            fire_progress_event(m_upload_object, EventNames::load, m_request_body_transmitted, request_body_length);
769
770
            // 5. Fire a progress event named loadend at this’s upload object with requestBodyTransmitted and requestBodyLength.
771
0
            fire_progress_event(m_upload_object, EventNames::loadend, m_request_body_transmitted, request_body_length);
772
0
        };
773
774
        // 9. Let processResponse, given a response, be these steps:
775
        // NOTE: `this` is kept alive by FetchAlgorithms using JS::SafeFunction.
776
0
        auto process_response = [this](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response) {
777
            // 1. Set this’s response to response.
778
0
            m_response = response;
779
780
            // 2. Handle errors for this.
781
            // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.
782
            // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
783
0
            handle_errors().release_value_but_fixme_should_propagate_errors();
784
785
            // 3. If this’s response is a network error, then return.
786
0
            if (m_response->is_network_error())
787
0
                return;
788
789
            // 4. Set this’s state to headers received.
790
0
            m_state = State::HeadersReceived;
791
792
            // 5. Fire an event named readystatechange at this.
793
            // FIXME: We're in an async context, so we can't propagate the error anywhere.
794
0
            dispatch_event(*DOM::Event::create(this->realm(), EventNames::readystatechange));
795
796
            // 6. If this’s state is not headers received, then return.
797
0
            if (m_state != State::HeadersReceived)
798
0
                return;
799
800
            // 7. If this’s response’s body is null, then run handle response end-of-body for this and return.
801
0
            if (!m_response->body()) {
802
                // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.
803
                // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
804
0
                handle_response_end_of_body().release_value_but_fixme_should_propagate_errors();
805
0
                return;
806
0
            }
807
808
            // 8. Let length be the result of extracting a length from this’s response’s header list.
809
            // FIXME: We're in an async context, so we can't propagate the error anywhere.
810
0
            auto length = m_response->header_list()->extract_length();
811
812
            // 9. If length is not an integer, then set it to 0.
813
0
            if (!length.has<u64>())
814
0
                length = 0;
815
816
            // FIXME: We can't implement these steps yet, as we don't fully implement the Streams standard.
817
818
            // 10. Let processBodyChunk given bytes be these steps:
819
0
            auto process_body_chunks = JS::create_heap_function(heap(), [this, length](ByteBuffer byte_buffer) {
820
                // 1. Append bytes to this’s received bytes.
821
0
                m_received_bytes.append(byte_buffer);
822
823
                // FIXME: 2. If not roughly 50ms have passed since these steps were last invoked, then return.
824
825
                // 3. If this’s state is headers received, then set this’s state to loading.
826
0
                if (m_state == State::HeadersReceived)
827
0
                    m_state = State::Loading;
828
829
                // 4. Fire an event named readystatechange at this.
830
                // Spec Note: Web compatibility is the reason readystatechange fires more often than this’s state changes.
831
0
                dispatch_event(*DOM::Event::create(this->realm(), EventNames::readystatechange));
832
833
                // 5. Fire a progress event named progress at this with this’s received bytes’s length and length.
834
0
                fire_progress_event(*this, EventNames::progress, m_received_bytes.size(), length.get<u64>());
835
0
            });
836
837
            // 11. Let processEndOfBody be this step: run handle response end-of-body for this.
838
0
            auto process_end_of_body = JS::create_heap_function(heap(), [this]() {
839
                // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.
840
                // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
841
0
                handle_response_end_of_body().release_value_but_fixme_should_propagate_errors();
842
0
            });
843
844
            // 12. Let processBodyError be these steps:
845
0
            auto process_body_error = JS::create_heap_function(heap(), [this](JS::Value) {
846
0
                auto& vm = this->vm();
847
                // 1. Set this’s response to a network error.
848
0
                m_response = Fetch::Infrastructure::Response::network_error(vm, "A network error occurred processing body."sv);
849
                // 2. Run handle errors for this.
850
                // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.
851
                // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
852
0
                handle_errors().release_value_but_fixme_should_propagate_errors();
853
0
            });
854
855
            // 13. Incrementally read this’s response’s body, given processBodyChunk, processEndOfBody, processBodyError, and this’s relevant global object.
856
0
            auto global_object = JS::NonnullGCPtr<JS::Object> { HTML::relevant_global_object(*this) };
857
0
            response->body()->incrementally_read(process_body_chunks, process_end_of_body, process_body_error, global_object);
858
0
        };
859
860
        // 10. Set this’s fetch controller to the result of fetching req with processRequestBodyChunkLength set to processRequestBodyChunkLength, processRequestEndOfBody set to processRequestEndOfBody, and processResponse set to processResponse.
861
0
        m_fetch_controller = TRY(Fetch::Fetching::fetch(
862
0
            realm,
863
0
            request,
864
0
            Fetch::Infrastructure::FetchAlgorithms::create(vm,
865
0
                {
866
0
                    .process_request_body_chunk_length = move(process_request_body_chunk_length),
867
0
                    .process_request_end_of_body = move(process_request_end_of_body),
868
0
                    .process_early_hints_response = {},
869
0
                    .process_response = move(process_response),
870
0
                    .process_response_end_of_body = {},
871
0
                    .process_response_consume_body = {},
872
0
                })));
873
874
        // 11. Let now be the present time.
875
        // 12. Run these steps in parallel:
876
        //     1. Wait until either req’s done flag is set or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.
877
        //     2. If req’s done flag is unset, then set this’s timed out flag and terminate this’s fetch controller.
878
0
        if (m_timeout != 0) {
879
0
            auto timer = Platform::Timer::create_single_shot(m_timeout, nullptr);
880
881
            // NOTE: `timer` is kept alive by copying the NNRP into the lambda, incrementing its ref-count.
882
            // NOTE: `this` and `request` is kept alive by Platform::Timer using JS::SafeFunction.
883
0
            timer->on_timeout = [this, request, timer]() {
884
0
                if (!request->done()) {
885
0
                    m_timed_out = true;
886
0
                    m_fetch_controller->terminate();
887
0
                }
888
0
            };
889
890
0
            timer->start();
891
0
        }
892
0
    } else {
893
        // 1. Let processedResponse be false.
894
0
        bool processed_response = false;
895
896
        // 2. Let processResponseConsumeBody, given a response and nullOrFailureOrBytes, be these steps:
897
0
        auto process_response_consume_body = [this, &processed_response](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response, Variant<Empty, Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag, ByteBuffer> null_or_failure_or_bytes) {
898
            // 1. If nullOrFailureOrBytes is not failure, then set this’s response to response.
899
0
            if (!null_or_failure_or_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>())
900
0
                m_response = response;
901
902
            // 2. If nullOrFailureOrBytes is a byte sequence, then append nullOrFailureOrBytes to this’s received bytes.
903
0
            if (null_or_failure_or_bytes.has<ByteBuffer>()) {
904
                // NOTE: We are not in a context where we can throw if this fails due to OOM.
905
0
                m_received_bytes.append(null_or_failure_or_bytes.get<ByteBuffer>());
906
0
            }
907
908
            // 3. Set processedResponse to true.
909
0
            processed_response = true;
910
0
        };
911
912
        // 3. Set this’s fetch controller to the result of fetching req with processResponseConsumeBody set to processResponseConsumeBody and useParallelQueue set to true.
913
0
        m_fetch_controller = TRY(Fetch::Fetching::fetch(
914
0
            realm,
915
0
            request,
916
0
            Fetch::Infrastructure::FetchAlgorithms::create(vm,
917
0
                {
918
0
                    .process_request_body_chunk_length = {},
919
0
                    .process_request_end_of_body = {},
920
0
                    .process_early_hints_response = {},
921
0
                    .process_response = {},
922
0
                    .process_response_end_of_body = {},
923
0
                    .process_response_consume_body = move(process_response_consume_body),
924
0
                }),
925
0
            Fetch::Fetching::UseParallelQueue::Yes));
926
927
        // 4. Let now be the present time.
928
        // 5. Pause until either processedResponse is true or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.
929
0
        bool did_time_out = false;
930
931
0
        if (m_timeout != 0) {
932
0
            auto timer = Platform::Timer::create_single_shot(m_timeout, nullptr);
933
934
            // NOTE: `timer` is kept alive by copying the NNRP into the lambda, incrementing its ref-count.
935
0
            timer->on_timeout = [timer, &did_time_out]() {
936
0
                did_time_out = true;
937
0
            };
938
939
0
            timer->start();
940
0
        }
941
942
        // FIXME: This is not exactly correct, as it allows the HTML event loop to continue executing tasks.
943
0
        Platform::EventLoopPlugin::the().spin_until([&]() {
944
0
            return processed_response || did_time_out;
945
0
        });
946
947
        // 6. If processedResponse is false, then set this’s timed out flag and terminate this’s fetch controller.
948
0
        if (!processed_response) {
949
0
            m_timed_out = true;
950
0
            m_fetch_controller->terminate();
951
0
        }
952
953
        // FIXME: 7. Report timing for this’s fetch controller given the current global object.
954
        //        We cannot do this for responses that have a body yet, as we do not setup the stream that then calls processResponseEndOfBody in `fetch_response_handover`.
955
956
        // 8. Run handle response end-of-body for this.
957
0
        TRY(handle_response_end_of_body());
958
0
    }
959
0
    return {};
960
0
}
961
962
WebIDL::CallbackType* XMLHttpRequest::onreadystatechange()
963
0
{
964
0
    return event_handler_attribute(Web::XHR::EventNames::readystatechange);
965
0
}
966
967
void XMLHttpRequest::set_onreadystatechange(WebIDL::CallbackType* value)
968
0
{
969
0
    set_event_handler_attribute(Web::XHR::EventNames::readystatechange, value);
970
0
}
971
972
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getresponseheader
973
WebIDL::ExceptionOr<Optional<String>> XMLHttpRequest::get_response_header(String const& name) const
974
0
{
975
0
    auto& vm = this->vm();
976
977
    // The getResponseHeader(name) method steps are to return the result of getting name from this’s response’s header list.
978
0
    auto header_bytes = m_response->header_list()->get(name.bytes());
979
0
    return header_bytes.has_value() ? TRY_OR_THROW_OOM(vm, String::from_utf8(*header_bytes)) : Optional<String> {};
980
0
}
981
982
// https://xhr.spec.whatwg.org/#legacy-uppercased-byte-less-than
983
static ErrorOr<bool> is_legacy_uppercased_byte_less_than(ReadonlyBytes a, ReadonlyBytes b)
984
0
{
985
    // 1. Let A be a, byte-uppercased.
986
0
    auto uppercased_a = TRY(ByteBuffer::copy(a));
987
0
    Infra::byte_uppercase(uppercased_a);
988
989
    // 2. Let B be b, byte-uppercased.
990
0
    auto uppercased_b = TRY(ByteBuffer::copy(b));
991
0
    Infra::byte_uppercase(uppercased_b);
992
993
    // 3. Return A is byte less than B.
994
0
    return Infra::is_byte_less_than(uppercased_a, uppercased_b);
995
0
}
996
997
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getallresponseheaders
998
WebIDL::ExceptionOr<String> XMLHttpRequest::get_all_response_headers() const
999
0
{
1000
0
    auto& vm = this->vm();
1001
1002
    // 1. Let output be an empty byte sequence.
1003
0
    ByteBuffer output;
1004
1005
    // 2. Let initialHeaders be the result of running sort and combine with this’s response’s header list.
1006
0
    auto initial_headers = m_response->header_list()->sort_and_combine();
1007
1008
    // 3. Let headers be the result of sorting initialHeaders in ascending order, with a being less than b if a’s name is legacy-uppercased-byte less than b’s name.
1009
    // Spec Note: Unfortunately, this is needed for compatibility with deployed content.
1010
    // NOTE: quick_sort mutates the collection instead of returning a sorted copy.
1011
0
    quick_sort(initial_headers, [](Fetch::Infrastructure::Header const& a, Fetch::Infrastructure::Header const& b) {
1012
        // FIXME: We are not in a context where we can throw from OOM.
1013
0
        return is_legacy_uppercased_byte_less_than(a.name, b.name).release_value_but_fixme_should_propagate_errors();
1014
0
    });
1015
1016
    // 4. For each header in headers, append header’s name, followed by a 0x3A 0x20 byte pair, followed by header’s value, followed by a 0x0D 0x0A byte pair, to output.
1017
0
    for (auto const& header : initial_headers) {
1018
0
        output.append(header.name);
1019
0
        output.append(0x3A); // ':'
1020
0
        output.append(0x20); // ' '
1021
0
        output.append(header.value);
1022
0
        output.append(0x0D); // '\r'
1023
0
        output.append(0x0A); // '\n'
1024
0
    }
1025
1026
    // 5. Return output.
1027
0
    return TRY_OR_THROW_OOM(vm, String::from_utf8(output));
1028
0
}
1029
1030
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
1031
WebIDL::ExceptionOr<void> XMLHttpRequest::override_mime_type(String const& mime)
1032
0
{
1033
    // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
1034
0
    if (m_state == State::Loading || m_state == State::Done)
1035
0
        return WebIDL::InvalidStateError::create(realm(), "Cannot override MIME type when state is Loading or Done."_string);
1036
1037
    // 2. Set this’s override MIME type to the result of parsing mime.
1038
0
    m_override_mime_type = MimeSniff::MimeType::parse(mime);
1039
1040
    // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
1041
0
    if (!m_override_mime_type.has_value())
1042
0
        m_override_mime_type = MimeSniff::MimeType::create("application"_string, "octet-stream"_string);
1043
1044
0
    return {};
1045
0
}
1046
1047
// https://xhr.spec.whatwg.org/#ref-for-dom-xmlhttprequest-timeout%E2%91%A2
1048
WebIDL::ExceptionOr<void> XMLHttpRequest::set_timeout(u32 timeout)
1049
0
{
1050
    // 1. If the current global object is a Window object and this’s synchronous flag is set,
1051
    //    then throw an "InvalidAccessError" DOMException.
1052
0
    if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
1053
0
        return WebIDL::InvalidAccessError::create(realm(), "Use of XMLHttpRequest's timeout attribute is not supported in the synchronous mode in window context."_string);
1054
1055
    // 2. Set this’s timeout to the given value.
1056
0
    m_timeout = timeout;
1057
1058
0
    return {};
1059
0
}
1060
1061
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-timeout
1062
0
u32 XMLHttpRequest::timeout() const { return m_timeout; }
1063
1064
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
1065
bool XMLHttpRequest::with_credentials() const
1066
0
{
1067
    // The withCredentials getter steps are to return this’s cross-origin credentials.
1068
0
    return m_cross_origin_credentials;
1069
0
}
1070
1071
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
1072
WebIDL::ExceptionOr<void> XMLHttpRequest::set_with_credentials(bool with_credentials)
1073
0
{
1074
0
    auto& realm = this->realm();
1075
1076
    // 1. If this’s state is not unsent or opened, then throw an "InvalidStateError" DOMException.
1077
0
    if (m_state != State::Unsent && m_state != State::Opened)
1078
0
        return WebIDL::InvalidStateError::create(realm, "XHR readyState is not UNSENT or OPENED"_string);
1079
1080
    // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
1081
0
    if (m_send)
1082
0
        return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set"_string);
1083
1084
    // 3. Set this’s cross-origin credentials to the given value.
1085
0
    m_cross_origin_credentials = with_credentials;
1086
1087
0
    return {};
1088
0
}
1089
1090
// https://xhr.spec.whatwg.org/#garbage-collection
1091
bool XMLHttpRequest::must_survive_garbage_collection() const
1092
0
{
1093
    // An XMLHttpRequest object must not be garbage collected
1094
    // if its state is either opened with the send() flag set, headers received, or loading,
1095
    // and it has one or more event listeners registered whose type is one of
1096
    // readystatechange, progress, abort, error, load, timeout, and loadend.
1097
0
    if ((m_state == State::Opened && m_send)
1098
0
        || m_state == State::HeadersReceived
1099
0
        || m_state == State::Loading) {
1100
0
        if (has_event_listener(EventNames::readystatechange))
1101
0
            return true;
1102
0
        if (has_event_listener(EventNames::progress))
1103
0
            return true;
1104
0
        if (has_event_listener(EventNames::abort))
1105
0
            return true;
1106
0
        if (has_event_listener(EventNames::error))
1107
0
            return true;
1108
0
        if (has_event_listener(EventNames::load))
1109
0
            return true;
1110
0
        if (has_event_listener(EventNames::timeout))
1111
0
            return true;
1112
0
        if (has_event_listener(EventNames::loadend))
1113
0
            return true;
1114
0
    }
1115
1116
    // FIXME: If an XMLHttpRequest object is garbage collected while its connection is still open,
1117
    //        the user agent must terminate the XMLHttpRequest object’s fetch controller.
1118
    // NOTE: This would go in XMLHttpRequest::finalize().
1119
1120
0
    return false;
1121
0
}
1122
1123
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-abort
1124
void XMLHttpRequest::abort()
1125
0
{
1126
    // 1. Abort this’s fetch controller.
1127
0
    m_fetch_controller->abort(realm(), {});
1128
1129
    // 2. If this’s state is opened with this’s send() flag set, headers received, or loading, then run the request error steps for this and abort.
1130
0
    if ((m_state == State::Opened || m_state == State::HeadersReceived || m_state == State::Loading) && m_send) {
1131
        // NOTE: This cannot throw as we don't pass in an exception. XHR::abort cannot be reached in a synchronous context where the state matches above.
1132
        //       This is because it pauses inside XHR::send until the request is done or times out and then immediately calls `handle_response_end_of_body`
1133
        //       which will always set `m_state` to `Done`.
1134
0
        MUST(request_error_steps(EventNames::abort));
1135
0
    }
1136
1137
    // 3. If this’s state is done, then set this’s state to unsent and this’s response to a network error.
1138
    // Spec Note: No readystatechange event is dispatched.
1139
0
    if (m_state == State::Done) {
1140
0
        m_state = State::Unsent;
1141
0
        m_response = Fetch::Infrastructure::Response::network_error(vm(), "Not yet sent"sv);
1142
0
    }
1143
0
}
1144
1145
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-upload
1146
JS::NonnullGCPtr<XMLHttpRequestUpload> XMLHttpRequest::upload() const
1147
0
{
1148
    // The upload getter steps are to return this’s upload object.
1149
0
    return m_upload_object;
1150
0
}
1151
1152
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-status
1153
Fetch::Infrastructure::Status XMLHttpRequest::status() const
1154
0
{
1155
    // The status getter steps are to return this’s response’s status.
1156
0
    return m_response->status();
1157
0
}
1158
1159
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-statustext
1160
WebIDL::ExceptionOr<String> XMLHttpRequest::status_text() const
1161
0
{
1162
0
    auto& vm = this->vm();
1163
1164
    // The statusText getter steps are to return this’s response’s status message.
1165
0
    return TRY_OR_THROW_OOM(vm, String::from_utf8(m_response->status_message()));
1166
0
}
1167
1168
// https://xhr.spec.whatwg.org/#handle-response-end-of-body
1169
WebIDL::ExceptionOr<void> XMLHttpRequest::handle_response_end_of_body()
1170
0
{
1171
0
    auto& realm = this->realm();
1172
1173
    // 1. Handle errors for xhr.
1174
0
    TRY(handle_errors());
1175
1176
    // 2. If xhr’s response is a network error, then return.
1177
0
    if (m_response->is_network_error())
1178
0
        return {};
1179
1180
    // 3. Let transmitted be xhr’s received bytes’s length.
1181
0
    auto transmitted = m_received_bytes.size();
1182
1183
    // 4. Let length be the result of extracting a length from this’s response’s header list.
1184
0
    auto maybe_length = m_response->header_list()->extract_length();
1185
1186
    // 5. If length is not an integer, then set it to 0.
1187
0
    if (!maybe_length.has<u64>())
1188
0
        maybe_length = 0;
1189
1190
0
    auto length = maybe_length.get<u64>();
1191
1192
    // 6. If xhr’s synchronous flag is unset, then fire a progress event named progress at xhr with transmitted and length.
1193
0
    if (!m_synchronous)
1194
0
        fire_progress_event(*this, EventNames::progress, transmitted, length);
1195
1196
    // 7. Set xhr’s state to done.
1197
0
    m_state = State::Done;
1198
1199
    // 8. Unset xhr’s send() flag.
1200
0
    m_send = false;
1201
1202
    // 9. Fire an event named readystatechange at xhr.
1203
    // FIXME: If we're in an async context, this will propagate to a callback context which can't propagate it anywhere else and does not expect this to fail.
1204
0
    dispatch_event(*DOM::Event::create(realm, EventNames::readystatechange));
1205
1206
    // 10. Fire a progress event named load at xhr with transmitted and length.
1207
0
    fire_progress_event(*this, EventNames::load, transmitted, length);
1208
1209
    // 11. Fire a progress event named loadend at xhr with transmitted and length.
1210
0
    fire_progress_event(*this, EventNames::loadend, transmitted, length);
1211
1212
0
    return {};
1213
0
}
1214
1215
// https://xhr.spec.whatwg.org/#handle-errors
1216
WebIDL::ExceptionOr<void> XMLHttpRequest::handle_errors()
1217
0
{
1218
    // 1. If xhr’s send() flag is unset, then return.
1219
0
    if (!m_send)
1220
0
        return {};
1221
1222
    // 2. If xhr’s timed out flag is set, then run the request error steps for xhr, timeout, and "TimeoutError" DOMException.
1223
0
    if (m_timed_out)
1224
0
        return TRY(request_error_steps(EventNames::timeout, WebIDL::TimeoutError::create(realm(), "Timed out"_string)));
1225
1226
    // 3. Otherwise, if xhr’s response’s aborted flag is set, run the request error steps for xhr, abort, and "AbortError" DOMException.
1227
0
    if (m_response->aborted())
1228
0
        return TRY(request_error_steps(EventNames::abort, WebIDL::AbortError::create(realm(), "Aborted"_string)));
1229
1230
    // 4. Otherwise, if xhr’s response is a network error, then run the request error steps for xhr, error, and "NetworkError" DOMException.
1231
0
    if (m_response->is_network_error())
1232
0
        return TRY(request_error_steps(EventNames::error, WebIDL::NetworkError::create(realm(), "Network error"_string)));
1233
1234
0
    return {};
1235
0
}
1236
1237
JS::ThrowCompletionOr<void> XMLHttpRequest::request_error_steps(FlyString const& event_name, JS::GCPtr<WebIDL::DOMException> exception)
1238
0
{
1239
    // 1. Set xhr’s state to done.
1240
0
    m_state = State::Done;
1241
1242
    // 2. Unset xhr’s send() flag.
1243
0
    m_send = false;
1244
1245
    // 3. Set xhr’s response to a network error.
1246
0
    m_response = Fetch::Infrastructure::Response::network_error(realm().vm(), "Failed to load"sv);
1247
1248
    // 4. If xhr’s synchronous flag is set, then throw exception.
1249
0
    if (m_synchronous) {
1250
0
        VERIFY(exception);
1251
0
        return JS::throw_completion(exception.ptr());
1252
0
    }
1253
1254
    // 5. Fire an event named readystatechange at xhr.
1255
    // FIXME: Since we're in an async context, this will propagate to a callback context which can't propagate it anywhere else and does not expect this to fail.
1256
0
    dispatch_event(*DOM::Event::create(realm(), EventNames::readystatechange));
1257
1258
    // 6. If xhr’s upload complete flag is unset, then:
1259
0
    if (!m_upload_complete) {
1260
        // 1. Set xhr’s upload complete flag.
1261
0
        m_upload_complete = true;
1262
1263
        // 2. If xhr’s upload listener flag is set, then:
1264
0
        if (m_upload_listener) {
1265
            // 1. Fire a progress event named event at xhr’s upload object with 0 and 0.
1266
0
            fire_progress_event(m_upload_object, event_name, 0, 0);
1267
1268
            // 2. Fire a progress event named loadend at xhr’s upload object with 0 and 0.
1269
0
            fire_progress_event(m_upload_object, EventNames::loadend, 0, 0);
1270
0
        }
1271
0
    }
1272
1273
    // 7. Fire a progress event named event at xhr with 0 and 0.
1274
0
    fire_progress_event(*this, event_name, 0, 0);
1275
1276
    // 8. Fire a progress event named loadend at xhr with 0 and 0.
1277
0
    fire_progress_event(*this, EventNames::loadend, 0, 0);
1278
1279
0
    return {};
1280
0
}
1281
1282
// https://xhr.spec.whatwg.org/#the-responseurl-attribute
1283
String XMLHttpRequest::response_url()
1284
0
{
1285
    // The responseURL getter steps are to return the empty string if this’s response’s URL is null;
1286
    // otherwise its serialization with the exclude fragment flag set.
1287
0
    if (!m_response->url().has_value())
1288
0
        return String {};
1289
1290
0
    auto serialized = m_response->url().value().serialize(URL::ExcludeFragment::Yes);
1291
0
    return String::from_utf8_without_validation(serialized.bytes());
1292
0
}
1293
1294
}