Skip to content

Truly independent web browser

LibWebSocket: Remove the client opening handshake

Shannon Boothb9d202ef9ae6
diff --git a/Libraries/LibWebSocket/ConnectionInfo.cpp b/Libraries/LibWebSocket/ConnectionInfo.cpp
index ea71b3248ec..3afe35d7afa 100644
--- a/Libraries/LibWebSocket/ConnectionInfo.cpp
+++ b/Libraries/LibWebSocket/ConnectionInfo.cpp
@@ -33,31 +33,4 @@ void ConnectionInfo::set_dns_result(NonnullRefPtr<DNS::LookupResult const> dns_r
m_dns_result = move(dns_result);
}
-bool ConnectionInfo::is_secure() const
-{
- // RFC 6455 Section 3 :
- // The URI is called "secure" if the scheme component matches "wss" case-insensitively.
- return m_url.scheme().equals_ignoring_ascii_case("wss"sv);
-}
-
-ByteString ConnectionInfo::resource_name() const
-{
- // RFC 6455 Section 3 :
- // The "resource-name" can be constructed by concatenating the following:
- StringBuilder builder;
- // "/" if the path component is empty
- auto path = URL::percent_decode(m_url.serialize_path());
- if (path.is_empty())
- builder.append('/');
- // The path component
- builder.append(path);
- // "?" if the query component is non-empty
- if (m_url.query().has_value() && !m_url.query()->is_empty()) {
- builder.append('?');
- // the query component
- builder.append(*m_url.query());
- }
- return builder.to_byte_string();
-}
-
}
diff --git a/Libraries/LibWebSocket/ConnectionInfo.h b/Libraries/LibWebSocket/ConnectionInfo.h
index 2f37ff11efc..f2c067d4fd4 100644
--- a/Libraries/LibWebSocket/ConnectionInfo.h
+++ b/Libraries/LibWebSocket/ConnectionInfo.h
@@ -47,12 +47,6 @@ public:
Optional<DNS::LookupResult const&> dns_result() const;
void set_dns_result(NonnullRefPtr<DNS::LookupResult const>);
- // secure flag - defined in RFC 6455 Section 3
- bool is_secure() const;
-
- // "resource-name" or "/resource name/" - defined in RFC 6455 Section 3
- ByteString resource_name() const;
-
private:
URL::URL m_url;
ByteString m_origin;
diff --git a/Libraries/LibWebSocket/Impl/AcceptedSocket.h b/Libraries/LibWebSocket/Impl/AcceptedSocket.h
index 046586ea799..10b3dcbba03 100644
--- a/Libraries/LibWebSocket/Impl/AcceptedSocket.h
+++ b/Libraries/LibWebSocket/Impl/AcceptedSocket.h
@@ -18,8 +18,6 @@ public:
virtual ~AcceptedSocket() override;
virtual void connect(ConnectionInfo const&) override;
- virtual bool can_read_line() override { return false; }
- virtual ErrorOr<ByteString> read_line(size_t) override { return Error::from_errno(ENOTSUP); }
virtual ErrorOr<ByteBuffer> read(int max_size) override;
virtual bool send(ReadonlyBytes) override;
virtual bool eof() override;
diff --git a/Libraries/LibWebSocket/Impl/WebSocketImpl.h b/Libraries/LibWebSocket/Impl/WebSocketImpl.h
index f5c28e822dc..ff6c339d9f5 100644
--- a/Libraries/LibWebSocket/Impl/WebSocketImpl.h
+++ b/Libraries/LibWebSocket/Impl/WebSocketImpl.h
@@ -20,15 +20,11 @@ public:
virtual ~WebSocketImpl();
virtual void connect(ConnectionInfo const&) = 0;
- virtual bool can_read_line() = 0;
- virtual ErrorOr<ByteString> read_line(size_t) = 0;
virtual ErrorOr<ByteBuffer> read(int max_size) = 0;
virtual bool send(ReadonlyBytes) = 0;
virtual bool eof() = 0;
virtual void discard_connection() = 0;
- virtual bool handshake_complete_when_connected() const { return false; }
-
Function<void()> on_connected;
Function<void()> on_connection_error;
Function<void()> on_ready_to_read;
diff --git a/Libraries/LibWebSocket/WebSocket.cpp b/Libraries/LibWebSocket/WebSocket.cpp
index ac3f4ed9366..65a52bb0311 100644
--- a/Libraries/LibWebSocket/WebSocket.cpp
+++ b/Libraries/LibWebSocket/WebSocket.cpp
@@ -96,13 +96,9 @@ void WebSocket::start()
fail_connection(to_underlying(CloseStatusCode::AbnormalClosure), Error::ConnectionUpgradeFailed, "Timed out waiting for the client's handshake");
});
m_opening_handshake_timer->start();
- } else if (m_impl->handshake_complete_when_connected()) {
+ } else {
set_state(WebSocket::InternalState::Open);
notify_open();
- } else {
- set_state(WebSocket::InternalState::SendingClientHandshake);
- send_client_handshake();
- drain_read();
}
};
m_impl->on_ready_to_read = [this] {
@@ -118,8 +114,6 @@ ReadyState WebSocket::ready_state()
switch (m_state) {
case WebSocket::InternalState::NotStarted:
case WebSocket::InternalState::EstablishingProtocolConnection:
- case WebSocket::InternalState::SendingClientHandshake:
- case WebSocket::InternalState::WaitingForServerHandshake:
case WebSocket::InternalState::WaitingForClientHandshake:
return ReadyState::Connecting;
case WebSocket::InternalState::Open:
@@ -168,8 +162,6 @@ void WebSocket::close(u16 code, ByteString const& message)
break;
case InternalState::NotStarted:
case InternalState::EstablishingProtocolConnection:
- case InternalState::SendingClientHandshake:
- case InternalState::WaitingForServerHandshake:
case InternalState::WaitingForClientHandshake:
// "If the WebSocket connection is not yet established [WSP]
// Fail the WebSocket connection and set this’s ready state to CLOSING (2)."
@@ -226,17 +218,13 @@ void WebSocket::drain_read()
switch (m_state) {
case InternalState::NotStarted:
- case InternalState::EstablishingProtocolConnection:
- case InternalState::SendingClientHandshake: {
+ case InternalState::EstablishingProtocolConnection: {
auto initializing_bytes = m_impl->read(1024);
if (!initializing_bytes.is_error())
dbgln("drain_read() was called on a websocket that isn't opened yet. Read {} bytes from the socket.", initializing_bytes.value().size());
} break;
case InternalState::WaitingForClientHandshake:
VERIFY_NOT_REACHED();
- case InternalState::WaitingForServerHandshake: {
- read_server_handshake();
- } break;
case InternalState::Open:
case InternalState::Closing: {
// NB: The socket tells us just once that it has data to read, however much it has — so keep reading until
@@ -285,70 +273,6 @@ void WebSocket::drain_read()
}
}
-// The client handshake message is defined in the second list of section 4.1
-void WebSocket::send_client_handshake()
-{
- VERIFY(m_impl);
- VERIFY(m_state == WebSocket::InternalState::SendingClientHandshake);
- StringBuilder builder;
-
- // 2. and 3. GET /resource name/ HTTP 1.1
- builder.appendff("GET {} HTTP/1.1\r\n", m_connection.resource_name());
-
- // 4. Host
- auto url = m_connection.url();
- builder.appendff("Host: {}", url.serialized_host());
- if (!m_connection.is_secure() && url.port_or_default() != 80)
- builder.appendff(":{}", url.port_or_default());
- else if (m_connection.is_secure() && url.port_or_default() != 443)
- builder.appendff(":{}", url.port_or_default());
- builder.append("\r\n"sv);
-
- // 5. and 6. Connection Upgrade
- builder.append("Upgrade: websocket\r\n"sv);
- builder.append("Connection: Upgrade\r\n"sv);
-
- // 7. 16-byte nonce encoded as Base64
- u8 nonce_data[16];
- fill_with_random(nonce_data);
- // FIXME: change to TRY() and make method fallible
- m_websocket_key = MUST(encode_base64({ nonce_data, 16 })).to_byte_string();
- builder.appendff("Sec-WebSocket-Key: {}\r\n", m_websocket_key);
-
- // 8. Origin (optional field)
- if (!m_connection.origin().is_empty()) {
- builder.appendff("Origin: {}\r\n", m_connection.origin());
- }
-
- // 9. Websocket version
- builder.append("Sec-WebSocket-Version: 13\r\n"sv);
-
- // 10. Websocket protocol (optional field)
- if (!m_connection.protocols().is_empty()) {
- builder.append("Sec-WebSocket-Protocol: "sv);
- builder.join(',', m_connection.protocols());
- builder.append("\r\n"sv);
- }
-
- // 11. Websocket extensions (optional field)
- if (!m_connection.extensions().is_empty()) {
- builder.append("Sec-WebSocket-Extensions: "sv);
- builder.join(',', m_connection.extensions());
- builder.append("\r\n"sv);
- }
-
- // 12. Additional headers
- for (auto const& header : m_connection.headers()) {
- builder.appendff("{}: {}\r\n", header.name, header.value);
- }
-
- builder.append("\r\n"sv);
-
- set_state(WebSocket::InternalState::WaitingForServerHandshake);
- auto success = m_impl->send(builder.string_view().bytes());
- VERIFY(success);
-}
-
void WebSocket::fail_connection(u16 close_status_code, WebSocket::Error error_code, ByteString const& reason)
{
auto protector = NonnullRefPtr { *this };
@@ -368,158 +292,6 @@ void WebSocket::fail_connection(u16 close_status_code, WebSocket::Error error_co
discard_connection();
}
-// The server handshake message is defined in the third list of section 4.1
-void WebSocket::read_server_handshake()
-{
- VERIFY(m_impl);
- VERIFY(m_state == WebSocket::InternalState::WaitingForServerHandshake);
-
- auto fail_opening_handshake = [&](ByteString const& reason, CloseStatusCode close_status_code = CloseStatusCode::AbnormalClosure) {
- fail_connection(to_underlying(close_status_code), WebSocket::Error::ConnectionUpgradeFailed, reason);
- };
-
- // Read the server handshake
- if (!m_impl->can_read_line())
- return;
-
- if (!m_has_read_server_handshake_first_line) {
- auto header = m_impl->read_line(PAGE_SIZE).release_value_but_fixme_should_propagate_errors();
- auto parts = header.split(' ');
- if (parts.size() < 2) {
- fail_opening_handshake("Server HTTP Handshake contained HTTP header was malformed");
- return;
- }
- if (parts[0] != "HTTP/1.1") {
- fail_opening_handshake(ByteString::formatted("Server HTTP Handshake contained HTTP header {} which isn't supported", parts[0]));
- return;
- }
- if (parts[1] != "101") {
- // 1. If the status code is not 101, handle as per HTTP procedures.
- // FIXME: This could be a redirect or a 401 authentication request, which we do not handle.
- fail_opening_handshake(ByteString::formatted("Server HTTP Handshake return status {} which isn't supported", parts[1]));
- return;
- }
- m_has_read_server_handshake_first_line = true;
- }
-
- // Read the rest of the reply until we find an empty line
- while (m_impl->can_read_line()) {
- auto line = m_impl->read_line(PAGE_SIZE).release_value_but_fixme_should_propagate_errors();
- if (line.is_whitespace()) {
- // We're done with the HTTP headers.
- // Fail the connection if we're missing any of the following:
- if (!m_has_read_server_handshake_upgrade) {
- // 2. |Upgrade| should be present
- fail_opening_handshake("Server HTTP Handshake didn't contain an |Upgrade| header");
- return;
- }
- if (!m_has_read_server_handshake_connection) {
- // 2. |Connection| should be present
- fail_opening_handshake("Server HTTP Handshake didn't contain a |Connection| header");
- return;
- }
- if (!m_has_read_server_handshake_accept) {
- // 2. |Sec-WebSocket-Accept| should be present
- fail_opening_handshake("Server HTTP Handshake didn't contain a |Sec-WebSocket-Accept| header");
- return;
- }
-
- set_state(WebSocket::InternalState::Open);
- notify_open();
- return;
- }
-
- auto parts = line.split(':');
- if (parts.size() < 2) {
- // The header field is not valid
- fail_opening_handshake(ByteString::formatted("Got invalid header line {} in the Server HTTP handshake", line));
- return;
- }
-
- auto header_name = parts[0];
-
- if (header_name.equals_ignoring_ascii_case("Upgrade"sv)) {
- // 2. |Upgrade| should be case-insensitive "websocket"
- if (!parts[1].trim_whitespace().equals_ignoring_ascii_case("websocket"sv)) {
- fail_opening_handshake(ByteString::formatted("Server HTTP Handshake Header |Upgrade| should be 'websocket', got '{}'. Failing connection.", parts[1]));
- return;
- }
-
- m_has_read_server_handshake_upgrade = true;
- continue;
- }
-
- if (header_name.equals_ignoring_ascii_case("Connection"sv)) {
- // 3. |Connection| should be case-insensitive "Upgrade"
- if (!parts[1].trim_whitespace().equals_ignoring_ascii_case("Upgrade"sv)) {
- fail_opening_handshake(ByteString::formatted("Server HTTP Handshake Header |Connection| should be 'Upgrade', got '{}'. Failing connection.", parts[1]));
- return;
- }
-
- m_has_read_server_handshake_connection = true;
- continue;
- }
-
- if (header_name.equals_ignoring_ascii_case("Sec-WebSocket-Accept"sv)) {
- // 4. |Sec-WebSocket-Accept| should be base64(SHA1(|Sec-WebSocket-Key| + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
- auto expected_content = ByteString::formatted("{}258EAFA5-E914-47DA-95CA-C5AB0DC85B11", m_websocket_key);
-
- Crypto::Hash::Manager hash;
- hash.initialize(Crypto::Hash::HashKind::SHA1);
- hash.update(expected_content);
- auto expected_sha1 = hash.digest();
- // FIXME: change to TRY() and make method fallible
- auto expected_sha1_string = MUST(encode_base64({ expected_sha1.immutable_data(), expected_sha1.data_length() }));
- if (!parts[1].trim_whitespace().equals_ignoring_ascii_case(expected_sha1_string)) {
- fail_opening_handshake(ByteString::formatted("Server HTTP Handshake Header |Sec-Websocket-Accept| should be '{}', got '{}'. Failing connection.", expected_sha1_string, parts[1]));
- return;
- }
-
- m_has_read_server_handshake_accept = true;
- continue;
- }
-
- if (header_name.equals_ignoring_ascii_case("Sec-WebSocket-Extensions"sv)) {
- // 5. |Sec-WebSocket-Extensions| should not contain an extension that doesn't appear in m_connection->extensions()
- auto server_extensions = parts[1].split(',');
- for (auto const& extension : server_extensions) {
- auto trimmed_extension = extension.trim_whitespace();
- bool found_extension = false;
- for (auto const& supported_extension : m_connection.extensions()) {
- if (trimmed_extension.equals_ignoring_ascii_case(supported_extension)) {
- found_extension = true;
- }
- }
- if (!found_extension) {
- fail_opening_handshake(ByteString::formatted("Server HTTP Handshake Header |Sec-WebSocket-Extensions| contains '{}', which is not supported by the client. Failing connection.", trimmed_extension));
- return;
- }
- }
- continue;
- }
-
- if (header_name.equals_ignoring_ascii_case("Sec-WebSocket-Protocol"sv)) {
- // 6. If the response includes a |Sec-WebSocket-Protocol| header field and this header field indicates the use of a subprotocol that was not present in the client's handshake (the server has indicated a subprotocol not requested by the client), the client MUST _Fail the WebSocket Connection_.
- // Additionally, Section 4.2.2 says this is "Either a single value representing the subprotocol the server is ready to use or null."
- auto server_protocol = parts[1].trim_whitespace();
- bool found_protocol = false;
- for (auto const& supported_protocol : m_connection.protocols()) {
- if (server_protocol.equals_ignoring_ascii_case(supported_protocol)) {
- found_protocol = true;
- }
- }
- if (!found_protocol) {
- fail_opening_handshake(ByteString::formatted("Server HTTP Handshake Header |Sec-WebSocket-Protocol| contains '{}', which is not supported by the client. Failing connection.", server_protocol));
- return;
- }
- m_subprotocol_in_use = server_protocol;
- continue;
- }
- }
-
- // If needed, we will keep reading the header on the next drain_read call
-}
-
static bool contains_header_token(ByteString const& value, StringView token)
{
for (auto part : value.view().split_view(',')) {
diff --git a/Libraries/LibWebSocket/WebSocket.h b/Libraries/LibWebSocket/WebSocket.h
index facb386218f..af60df9b7fb 100644
--- a/Libraries/LibWebSocket/WebSocket.h
+++ b/Libraries/LibWebSocket/WebSocket.h
@@ -49,8 +49,7 @@ public:
AK::Duration handshake_timeout { AK::Duration::from_seconds(10) };
};
- // The transport is already connected. start() reads the client's HTTP upgrade request; it never uses a
- // transport's client-side handshake shortcut.
+ // The transport is already connected. start() reads the client's HTTP upgrade request.
static NonnullRefPtr<WebSocket> create_server(NonnullRefPtr<WebSocketImpl>, ServerOptions);
static ErrorOr<NonnullRefPtr<WebSocket>> accept(NonnullOwnPtr<Core::TCPSocket>, ServerOptions);
virtual ~WebSocket() override;
@@ -109,8 +108,6 @@ private:
void drain_read();
- void send_client_handshake();
- void read_server_handshake();
void read_client_handshake();
void reject_client_handshake(StringView status);
@@ -127,8 +124,6 @@ private:
enum class InternalState {
NotStarted,
EstablishingProtocolConnection,
- SendingClientHandshake,
- WaitingForServerHandshake,
WaitingForClientHandshake,
Open,
Closing,
@@ -144,12 +139,6 @@ private:
ByteString m_subprotocol_in_use { ByteString::empty() };
- ByteString m_websocket_key;
- bool m_has_read_server_handshake_first_line { false };
- bool m_has_read_server_handshake_upgrade { false };
- bool m_has_read_server_handshake_connection { false };
- bool m_has_read_server_handshake_accept { false };
-
bool m_discard_connection_requested { false };
u16 m_last_close_code { to_underlying(CloseStatusCode::NoStatusReceived) };
diff --git a/Services/RequestServer/WebSocketImplCurl.cpp b/Services/RequestServer/WebSocketImplCurl.cpp
index 11005f8a4bc..4414a08dfb6 100644
--- a/Services/RequestServer/WebSocketImplCurl.cpp
+++ b/Services/RequestServer/WebSocketImplCurl.cpp
@@ -123,11 +123,6 @@ void WebSocketImplCurl::connect(WebSocket::ConnectionInfo const& info)
VERIFY(err == CURLM_OK);
}
-bool WebSocketImplCurl::can_read_line()
-{
- VERIFY_NOT_REACHED();
-}
-
ErrorOr<ByteBuffer> WebSocketImplCurl::read(int max_size)
{
auto buffer = TRY(ByteBuffer::create_uninitialized(max_size));
@@ -135,11 +130,6 @@ ErrorOr<ByteBuffer> WebSocketImplCurl::read(int max_size)
return buffer.slice(0, read_bytes.size());
}
-ErrorOr<ByteString> WebSocketImplCurl::read_line(size_t)
-{
- VERIFY_NOT_REACHED();
-}
-
bool WebSocketImplCurl::send(ReadonlyBytes bytes)
{
if (auto const error = m_pending_write_buffer.try_append(bytes); error.is_error()) {
diff --git a/Services/RequestServer/WebSocketImplCurl.h b/Services/RequestServer/WebSocketImplCurl.h
index d8269b3979c..9abf240bc1b 100644
--- a/Services/RequestServer/WebSocketImplCurl.h
+++ b/Services/RequestServer/WebSocketImplCurl.h
@@ -26,15 +26,11 @@ public:
void set_proxy(Optional<HTTP::Proxy> proxy) { m_proxy = move(proxy); }
virtual void connect(WebSocket::ConnectionInfo const&) override;
- virtual bool can_read_line() override;
- virtual ErrorOr<ByteString> read_line(size_t) override;
virtual ErrorOr<ByteBuffer> read(int max_size) override;
virtual bool send(ReadonlyBytes) override;
virtual bool eof() override;
virtual void discard_connection() override;
- virtual bool handshake_complete_when_connected() const override { return true; }
-
bool did_connect();
private:
diff --git a/Tests/LibWebSocket/TestWebSocket.cpp b/Tests/LibWebSocket/TestWebSocket.cpp
index 9e609260a7a..4a50ec69fd6 100644
--- a/Tests/LibWebSocket/TestWebSocket.cpp
+++ b/Tests/LibWebSocket/TestWebSocket.cpp
@@ -16,8 +16,6 @@ namespace {
class TestWebSocketImpl final : public WebSocket::WebSocketImpl {
public:
virtual void connect(WebSocket::ConnectionInfo const&) override { on_connected(); }
- virtual bool can_read_line() override { return false; }
- virtual ErrorOr<ByteString> read_line(size_t) override { return Error::from_errno(ENOTSUP); }
virtual ErrorOr<ByteBuffer> read(int max_size) override
{
auto size = min(m_pending_data.size(), static_cast<size_t>(max_size));
@@ -34,7 +32,6 @@ public:
}
virtual bool eof() override { return m_eof; }
virtual void discard_connection() override { }
- virtual bool handshake_complete_when_connected() const override { return true; }
void receive(ByteBuffer data)
{