LibWebSocket: Fix close frame status code written in wrong byte order

The close status code was written using (u8*)&code which produces
platform byte order (little-endian on x86/ARM). This caused echo
servers to receive invalid close codes and respond with 1011
(UnexpectedCondition).

Fixes for example WPT:

https://wpt.live/websockets/Close-1000-verify-code.any.html?wss
This commit is contained in:
Shannon Booth
2026-03-09 16:22:30 +01:00
committed by Shannon Booth
parent c4c0afe4d7
commit e7525bf3df
Notes: github-actions[bot] 2026-03-13 16:29:13 +00:00

View File

@@ -6,6 +6,7 @@
*/
#include <AK/Base64.h>
#include <AK/Endian.h>
#include <AK/Random.h>
#include <LibCrypto/Hash/HashManager.h>
#include <LibWebSocket/Impl/WebSocketImplSerenity.h>
@@ -130,7 +131,11 @@ void WebSocket::close(u16 code, ByteString const& message)
// Start the WebSocket closing handshake and set thiss ready state to CLOSING (2)."
auto message_bytes = message.bytes();
auto close_payload = ByteBuffer::create_uninitialized(message_bytes.size() + 2).release_value_but_fixme_should_propagate_errors(); // FIXME: Handle possible OOM situation.
close_payload.overwrite(0, (u8*)&code, 2);
// Section 5.5.1:
// > If there is a body, the first two bytes of the body MUST be a 2-byte unsigned integer (in network byte order)
// > representing a status code with value /code/ defined in Section 7.4.
NetworkOrdered<u16> network_ordered_code { code };
close_payload.overwrite(0, &network_ordered_code, sizeof(network_ordered_code));
close_payload.overwrite(2, message_bytes.data(), message_bytes.size());
send_frame(WebSocket::OpCode::ConnectionClose, close_payload, true);
set_state(InternalState::Closing);