Coverage Report

Created: 2025-09-05 06:52

/src/serenity/Userland/Libraries/LibWeb/WebSockets/WebSocket.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2021-2022, Dex♪ <dexes.ttp@gmail.com>
3
 * Copyright (c) 2023, Kenneth Myhra <kennethmyhra@serenityos.org>
4
 *
5
 * SPDX-License-Identifier: BSD-2-Clause
6
 */
7
8
#include <AK/QuickSort.h>
9
#include <LibJS/Runtime/ArrayBuffer.h>
10
#include <LibJS/Runtime/FunctionObject.h>
11
#include <LibURL/Origin.h>
12
#include <LibWeb/Bindings/WebSocketPrototype.h>
13
#include <LibWeb/DOM/Document.h>
14
#include <LibWeb/DOM/Event.h>
15
#include <LibWeb/DOM/EventDispatcher.h>
16
#include <LibWeb/DOM/IDLEventListener.h>
17
#include <LibWeb/DOMURL/DOMURL.h>
18
#include <LibWeb/FileAPI/Blob.h>
19
#include <LibWeb/HTML/CloseEvent.h>
20
#include <LibWeb/HTML/EventHandler.h>
21
#include <LibWeb/HTML/EventNames.h>
22
#include <LibWeb/HTML/MessageEvent.h>
23
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
24
#include <LibWeb/Loader/ResourceLoader.h>
25
#include <LibWeb/WebIDL/AbstractOperations.h>
26
#include <LibWeb/WebIDL/Buffers.h>
27
#include <LibWeb/WebIDL/DOMException.h>
28
#include <LibWeb/WebIDL/ExceptionOr.h>
29
#include <LibWeb/WebSockets/WebSocket.h>
30
31
namespace Web::WebSockets {
32
33
JS_DEFINE_ALLOCATOR(WebSocket);
34
35
0
WebSocketClientSocket::~WebSocketClientSocket() = default;
36
37
// https://websockets.spec.whatwg.org/#dom-websocket-websocket
38
WebIDL::ExceptionOr<JS::NonnullGCPtr<WebSocket>> WebSocket::construct_impl(JS::Realm& realm, String const& url, Optional<Variant<String, Vector<String>>> const& protocols)
39
0
{
40
0
    auto& vm = realm.vm();
41
42
0
    auto web_socket = realm.heap().allocate<WebSocket>(realm, realm);
43
0
    auto& relevant_settings_object = HTML::relevant_settings_object(*web_socket);
44
45
    // 1. Let baseURL be this's relevant settings object's API base URL.
46
0
    auto base_url = relevant_settings_object.api_base_url();
47
48
    // 2. Let urlRecord be the result of applying the URL parser to url with baseURL.
49
0
    auto url_record = DOMURL::parse(url, base_url);
50
51
    // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
52
0
    if (!url_record.is_valid())
53
0
        return WebIDL::SyntaxError::create(realm, "Invalid URL"_string);
54
55
    // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
56
0
    if (url_record.scheme() == "http"sv)
57
0
        url_record.set_scheme("ws"_string);
58
    // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
59
0
    else if (url_record.scheme() == "https"sv)
60
0
        url_record.set_scheme("wss"_string);
61
62
    // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
63
0
    if (!url_record.scheme().is_one_of("ws"sv, "wss"sv))
64
0
        return WebIDL::SyntaxError::create(realm, "Invalid protocol"_string);
65
66
    // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" DOMException.
67
0
    if (url_record.fragment().has_value())
68
0
        return WebIDL::SyntaxError::create(realm, "Presence of URL fragment is invalid"_string);
69
70
0
    Vector<String> protocols_sequence;
71
    // 8. If protocols is a string, set protocols to a sequence consisting of just that string.
72
0
    if (protocols.has_value() && protocols->has<String>())
73
0
        protocols_sequence = { protocols.value().get<String>() };
74
0
    else if (protocols.has_value() && protocols->has<Vector<String>>())
75
0
        protocols_sequence = protocols.value().get<Vector<String>>();
76
0
    else
77
0
        protocols_sequence = {};
78
79
    // 9. If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise
80
    //    the value of `Sec-WebSocket-Protocol` fields as defined by The WebSocket protocol, then throw a "SyntaxError" DOMException. [WSP]
81
0
    auto sorted_protocols = protocols_sequence;
82
0
    quick_sort(sorted_protocols);
83
0
    for (size_t i = 0; i < sorted_protocols.size(); i++) {
84
        // https://datatracker.ietf.org/doc/html/rfc6455
85
        // The elements that comprise this value MUST be non-empty strings with characters in the range U+0021 to U+007E not including
86
        // separator characters as defined in [RFC2616] and MUST all be unique strings.
87
0
        auto protocol = sorted_protocols[i];
88
0
        if (i < sorted_protocols.size() - 1 && protocol == sorted_protocols[i + 1])
89
0
            return WebIDL::SyntaxError::create(realm, "Found a duplicate protocol name in the specified list"_string);
90
0
        for (auto code_point : protocol.code_points()) {
91
0
            if (code_point < '\x21' || code_point > '\x7E')
92
0
                return WebIDL::SyntaxError::create(realm, "Found invalid character in subprotocol name"_string);
93
0
        }
94
0
    }
95
96
    // 10. Set this's url to urlRecord.
97
0
    web_socket->set_url(url_record);
98
99
    // 11. Let client be this’s relevant settings object.
100
0
    auto& client = relevant_settings_object;
101
102
    // FIXME: 12. Run this step in parallel:
103
    //     1. Establish a WebSocket connection given urlRecord, protocols, and client. [FETCH]
104
0
    TRY_OR_THROW_OOM(vm, web_socket->establish_web_socket_connection(url_record, protocols_sequence, client));
105
106
0
    return web_socket;
107
0
}
108
109
WebSocket::WebSocket(JS::Realm& realm)
110
0
    : EventTarget(realm)
111
0
{
112
0
}
113
114
0
WebSocket::~WebSocket() = default;
115
116
void WebSocket::initialize(JS::Realm& realm)
117
0
{
118
0
    Base::initialize(realm);
119
0
    WEB_SET_PROTOTYPE_FOR_INTERFACE(WebSocket);
120
0
}
121
122
ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL& url_record, Vector<String>& protocols, HTML::EnvironmentSettingsObject& client)
123
0
{
124
    // FIXME: Integrate properly with FETCH as per https://fetch.spec.whatwg.org/#websocket-opening-handshake
125
126
0
    auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&client.global_object());
127
0
    VERIFY(window_or_worker);
128
0
    auto origin_string = MUST(window_or_worker->origin()).to_byte_string();
129
130
0
    Vector<ByteString> protcol_byte_strings;
131
0
    for (auto const& protocol : protocols)
132
0
        TRY(protcol_byte_strings.try_append(protocol.to_byte_string()));
133
134
0
    m_websocket = ResourceLoader::the().connector().websocket_connect(url_record, origin_string, protcol_byte_strings);
135
0
    m_websocket->on_open = [weak_this = make_weak_ptr<WebSocket>()] {
136
0
        if (!weak_this)
137
0
            return;
138
0
        auto& websocket = const_cast<WebSocket&>(*weak_this);
139
0
        websocket.on_open();
140
0
    };
141
0
    m_websocket->on_message = [weak_this = make_weak_ptr<WebSocket>()](auto message) {
142
0
        if (!weak_this)
143
0
            return;
144
0
        auto& websocket = const_cast<WebSocket&>(*weak_this);
145
0
        websocket.on_message(move(message.data), message.is_text);
146
0
    };
147
0
    m_websocket->on_close = [weak_this = make_weak_ptr<WebSocket>()](auto code, auto reason, bool was_clean) {
148
0
        if (!weak_this)
149
0
            return;
150
0
        auto& websocket = const_cast<WebSocket&>(*weak_this);
151
0
        websocket.on_close(code, String::from_byte_string(reason).release_value_but_fixme_should_propagate_errors(), was_clean);
152
0
    };
153
0
    m_websocket->on_error = [weak_this = make_weak_ptr<WebSocket>()](auto) {
154
0
        if (!weak_this)
155
0
            return;
156
0
        auto& websocket = const_cast<WebSocket&>(*weak_this);
157
0
        websocket.on_error();
158
0
    };
159
160
0
    return {};
161
0
}
162
163
// https://websockets.spec.whatwg.org/#dom-websocket-readystate
164
WebSocket::ReadyState WebSocket::ready_state() const
165
0
{
166
0
    if (!m_websocket)
167
0
        return WebSocket::ReadyState::Closed;
168
0
    return const_cast<WebSocketClientSocket&>(*m_websocket).ready_state();
169
0
}
170
171
// https://websockets.spec.whatwg.org/#dom-websocket-extensions
172
String WebSocket::extensions() const
173
0
{
174
0
    if (!m_websocket)
175
0
        return String {};
176
    // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
177
    // FIXME: Change the extensions attribute's value to the extensions in use, if it is not the null value.
178
0
    return String {};
179
0
}
180
181
// https://websockets.spec.whatwg.org/#dom-websocket-protocol
182
WebIDL::ExceptionOr<String> WebSocket::protocol() const
183
0
{
184
0
    if (!m_websocket)
185
0
        return String {};
186
0
    return TRY_OR_THROW_OOM(vm(), String::from_byte_string(m_websocket->subprotocol_in_use()));
187
0
}
188
189
// https://websockets.spec.whatwg.org/#dom-websocket-close
190
WebIDL::ExceptionOr<void> WebSocket::close(Optional<u16> code, Optional<String> reason)
191
0
{
192
    // 1. If code is present, but is neither an integer equal to 1000 nor an integer in the range 3000 to 4999, inclusive, throw an "InvalidAccessError" DOMException.
193
0
    if (code.has_value() && *code != 1000 && (*code < 3000 || *code > 4099))
194
0
        return WebIDL::InvalidAccessError::create(realm(), "The close error code is invalid"_string);
195
    // 2. If reason is present, then run these substeps:
196
0
    if (reason.has_value()) {
197
        // 1. Let reasonBytes be the result of encoding reason.
198
        // 2. If reasonBytes is longer than 123 bytes, then throw a "SyntaxError" DOMException.
199
0
        if (reason->bytes().size() > 123)
200
0
            return WebIDL::SyntaxError::create(realm(), "The close reason is longer than 123 bytes"_string);
201
0
    }
202
    // 3. Run the first matching steps from the following list:
203
0
    auto state = ready_state();
204
    // -> If this's ready state is CLOSING (2) or CLOSED (3)
205
0
    if (state == WebSocket::ReadyState::Closing || state == WebSocket::ReadyState::Closed)
206
0
        return {};
207
    // -> If the WebSocket connection is not yet established [WSP]
208
    // -> If the WebSocket closing handshake has not yet been started [WSP]
209
    // -> Otherwise
210
    // NOTE: All of these are handled by the WebSocket Protocol when calling close()
211
    // FIXME: LibProtocol does not yet support sending empty Close messages, so we use default values for now
212
0
    m_websocket->close(code.value_or(1000), reason.value_or(String {}).to_byte_string());
213
0
    return {};
214
0
}
215
216
// https://websockets.spec.whatwg.org/#dom-websocket-send
217
WebIDL::ExceptionOr<void> WebSocket::send(Variant<JS::Handle<WebIDL::BufferSource>, JS::Handle<FileAPI::Blob>, String> const& data)
218
0
{
219
0
    auto state = ready_state();
220
0
    if (state == WebSocket::ReadyState::Connecting)
221
0
        return WebIDL::InvalidStateError::create(realm(), "Websocket is still CONNECTING"_string);
222
0
    if (state == WebSocket::ReadyState::Open) {
223
0
        TRY_OR_THROW_OOM(vm(),
224
0
            data.visit(
225
0
                [this](String const& string) -> ErrorOr<void> {
226
0
                    m_websocket->send(string);
227
0
                    return {};
228
0
                },
229
0
                [this](JS::Handle<WebIDL::BufferSource> const& buffer_source) -> ErrorOr<void> {
230
                    // FIXME: While the spec doesn't say to do this, it's not observable except from potentially throwing OOM.
231
                    //        Can we avoid this copy?
232
0
                    auto data_buffer = TRY(WebIDL::get_buffer_source_copy(*buffer_source->raw_object()));
233
0
                    m_websocket->send(data_buffer, false);
234
0
                    return {};
235
0
                },
236
0
                [this](JS::Handle<FileAPI::Blob> const& blob) -> ErrorOr<void> {
237
0
                    auto byte_buffer = TRY(ByteBuffer::copy(blob->raw_bytes()));
238
0
                    m_websocket->send(byte_buffer, false);
239
0
                    return {};
240
0
                }));
241
        // TODO : If the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection.
242
        // TODO : Any invocation of this method with a string argument that does not throw an exception must increase the bufferedAmount attribute by the number of bytes needed to express the argument as UTF-8.
243
0
    }
244
0
    return {};
245
0
}
246
247
// https://websockets.spec.whatwg.org/#feedback-from-the-protocol
248
void WebSocket::on_open()
249
0
{
250
    // 1. Change the readyState attribute's value to OPEN (1).
251
    // 2. Change the extensions attribute's value to the extensions in use, if it is not the null value. [WSP]
252
    // 3. Change the protocol attribute's value to the subprotocol in use, if it is not the null value. [WSP]
253
0
    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::open));
254
0
}
255
256
// https://websockets.spec.whatwg.org/#feedback-from-the-protocol
257
void WebSocket::on_error()
258
0
{
259
0
    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
260
0
}
261
262
// https://websockets.spec.whatwg.org/#feedback-from-the-protocol
263
void WebSocket::on_close(u16 code, String reason, bool was_clean)
264
0
{
265
    // 1. Change the readyState attribute's value to CLOSED. This is handled by the Protocol's WebSocket
266
    // 2. If [needed], fire an event named error at the WebSocket object. This is handled by the Protocol's WebSocket
267
0
    HTML::CloseEventInit event_init {};
268
0
    event_init.was_clean = was_clean;
269
0
    event_init.code = code;
270
0
    event_init.reason = reason;
271
0
    dispatch_event(HTML::CloseEvent::create(realm(), HTML::EventNames::close, event_init));
272
0
}
273
274
// https://websockets.spec.whatwg.org/#feedback-from-the-protocol
275
void WebSocket::on_message(ByteBuffer message, bool is_text)
276
0
{
277
0
    if (m_websocket->ready_state() != WebSocket::ReadyState::Open)
278
0
        return;
279
0
    if (is_text) {
280
0
        auto text_message = ByteString(ReadonlyBytes(message));
281
0
        HTML::MessageEventInit event_init;
282
0
        event_init.data = JS::PrimitiveString::create(vm(), text_message);
283
0
        event_init.origin = url().release_value_but_fixme_should_propagate_errors();
284
0
        dispatch_event(HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init));
285
0
        return;
286
0
    }
287
288
0
    if (m_binary_type == "blob") {
289
        // type indicates that the data is Binary and binaryType is "blob"
290
0
        HTML::MessageEventInit event_init;
291
0
        event_init.data = FileAPI::Blob::create(realm(), message, "text/plain;charset=utf-8"_string);
292
0
        event_init.origin = url().release_value_but_fixme_should_propagate_errors();
293
0
        dispatch_event(HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init));
294
0
        return;
295
0
    } else if (m_binary_type == "arraybuffer") {
296
        // type indicates that the data is Binary and binaryType is "arraybuffer"
297
0
        HTML::MessageEventInit event_init;
298
0
        event_init.data = JS::ArrayBuffer::create(realm(), message);
299
0
        event_init.origin = url().release_value_but_fixme_should_propagate_errors();
300
0
        dispatch_event(HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init));
301
0
        return;
302
0
    }
303
304
0
    dbgln("Unsupported WebSocket message type {}", m_binary_type);
305
0
    TODO();
306
0
}
307
308
#undef __ENUMERATE
309
#define __ENUMERATE(attribute_name, event_name)                       \
310
    void WebSocket::set_##attribute_name(WebIDL::CallbackType* value) \
311
0
    {                                                                 \
312
0
        set_event_handler_attribute(event_name, value);               \
313
0
    }                                                                 \
Unexecuted instantiation: Web::WebSockets::WebSocket::set_onerror(Web::WebIDL::CallbackType*)
Unexecuted instantiation: Web::WebSockets::WebSocket::set_onclose(Web::WebIDL::CallbackType*)
Unexecuted instantiation: Web::WebSockets::WebSocket::set_onopen(Web::WebIDL::CallbackType*)
Unexecuted instantiation: Web::WebSockets::WebSocket::set_onmessage(Web::WebIDL::CallbackType*)
314
    WebIDL::CallbackType* WebSocket::attribute_name()                 \
315
0
    {                                                                 \
316
0
        return event_handler_attribute(event_name);                   \
317
0
    }
Unexecuted instantiation: Web::WebSockets::WebSocket::onerror()
Unexecuted instantiation: Web::WebSockets::WebSocket::onclose()
Unexecuted instantiation: Web::WebSockets::WebSocket::onopen()
Unexecuted instantiation: Web::WebSockets::WebSocket::onmessage()
318
ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
319
#undef __ENUMERATE
320
321
}