WebSocket.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /*
  2. * Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Base64.h>
  8. #include <AK/Random.h>
  9. #include <LibCrypto/Hash/HashManager.h>
  10. #include <LibWebSocket/Impl/WebSocketImplSerenity.h>
  11. #include <LibWebSocket/WebSocket.h>
  12. #include <unistd.h>
  13. namespace WebSocket {
  14. // Note : The websocket protocol is defined by RFC 6455, found at https://tools.ietf.org/html/rfc6455
  15. // In this file, section numbers will refer to the RFC 6455
  16. NonnullRefPtr<WebSocket> WebSocket::create(ConnectionInfo connection, RefPtr<WebSocketImpl> impl)
  17. {
  18. return adopt_ref(*new WebSocket(move(connection), move(impl)));
  19. }
  20. WebSocket::WebSocket(ConnectionInfo connection, RefPtr<WebSocketImpl> impl)
  21. : m_connection(move(connection))
  22. , m_impl(move(impl))
  23. {
  24. }
  25. void WebSocket::start()
  26. {
  27. VERIFY(m_state == WebSocket::InternalState::NotStarted);
  28. if (!m_impl)
  29. m_impl = adopt_ref(*new WebSocketImplSerenity);
  30. m_impl->on_connection_error = [this] {
  31. dbgln("WebSocket: Connection error (underlying socket)");
  32. fatal_error(WebSocket::Error::CouldNotEstablishConnection);
  33. };
  34. m_impl->on_connected = [this] {
  35. if (m_state != WebSocket::InternalState::EstablishingProtocolConnection)
  36. return;
  37. m_state = WebSocket::InternalState::SendingClientHandshake;
  38. send_client_handshake();
  39. drain_read();
  40. };
  41. m_impl->on_ready_to_read = [this] {
  42. drain_read();
  43. };
  44. m_state = WebSocket::InternalState::EstablishingProtocolConnection;
  45. m_impl->connect(m_connection);
  46. }
  47. ReadyState WebSocket::ready_state()
  48. {
  49. switch (m_state) {
  50. case WebSocket::InternalState::NotStarted:
  51. case WebSocket::InternalState::EstablishingProtocolConnection:
  52. case WebSocket::InternalState::SendingClientHandshake:
  53. case WebSocket::InternalState::WaitingForServerHandshake:
  54. return ReadyState::Connecting;
  55. case WebSocket::InternalState::Open:
  56. return ReadyState::Open;
  57. case WebSocket::InternalState::Closing:
  58. return ReadyState::Closing;
  59. case WebSocket::InternalState::Closed:
  60. case WebSocket::InternalState::Errored:
  61. return ReadyState::Closed;
  62. default:
  63. VERIFY_NOT_REACHED();
  64. return ReadyState::Closed;
  65. }
  66. }
  67. void WebSocket::send(Message const& message)
  68. {
  69. // Calling send on a socket that is not opened is not allowed
  70. VERIFY(m_state == WebSocket::InternalState::Open);
  71. VERIFY(m_impl);
  72. if (message.is_text())
  73. send_frame(WebSocket::OpCode::Text, message.data(), true);
  74. else
  75. send_frame(WebSocket::OpCode::Binary, message.data(), true);
  76. }
  77. void WebSocket::close(u16 code, String const& message)
  78. {
  79. // Calling close on a socket that is not opened is not allowed
  80. VERIFY(m_state == WebSocket::InternalState::Open);
  81. VERIFY(m_impl);
  82. auto message_bytes = message.bytes();
  83. auto close_payload = ByteBuffer::create_uninitialized(message_bytes.size() + 2).release_value_but_fixme_should_propagate_errors(); // FIXME: Handle possible OOM situation.
  84. close_payload.overwrite(0, (u8*)&code, 2);
  85. close_payload.overwrite(2, message_bytes.data(), message_bytes.size());
  86. send_frame(WebSocket::OpCode::ConnectionClose, close_payload, true);
  87. }
  88. void WebSocket::drain_read()
  89. {
  90. if (m_impl->eof()) {
  91. // The connection got closed by the server
  92. m_state = WebSocket::InternalState::Closed;
  93. notify_close(m_last_close_code, m_last_close_message, true);
  94. discard_connection();
  95. return;
  96. }
  97. switch (m_state) {
  98. case InternalState::NotStarted:
  99. case InternalState::EstablishingProtocolConnection:
  100. case InternalState::SendingClientHandshake: {
  101. auto initializing_bytes = m_impl->read(1024);
  102. if (!initializing_bytes.is_error())
  103. dbgln("drain_read() was called on a websocket that isn't opened yet. Read {} bytes from the socket.", initializing_bytes.value().size());
  104. } break;
  105. case InternalState::WaitingForServerHandshake: {
  106. read_server_handshake();
  107. } break;
  108. case InternalState::Open:
  109. case InternalState::Closing: {
  110. read_frame();
  111. } break;
  112. case InternalState::Closed:
  113. case InternalState::Errored: {
  114. auto closed_bytes = m_impl->read(1024);
  115. if (!closed_bytes.is_error())
  116. dbgln("drain_read() was called on a closed websocket. Read {} bytes from the socket.", closed_bytes.value().size());
  117. } break;
  118. default:
  119. VERIFY_NOT_REACHED();
  120. }
  121. }
  122. // The client handshake message is defined in the second list of section 4.1
  123. void WebSocket::send_client_handshake()
  124. {
  125. VERIFY(m_impl);
  126. VERIFY(m_state == WebSocket::InternalState::SendingClientHandshake);
  127. StringBuilder builder;
  128. // 2. and 3. GET /resource name/ HTTP 1.1
  129. builder.appendff("GET {} HTTP/1.1\r\n", m_connection.resource_name());
  130. // 4. Host
  131. auto url = m_connection.url();
  132. builder.appendff("Host: {}", url.host());
  133. if (!m_connection.is_secure() && url.port_or_default() != 80)
  134. builder.appendff(":{}", url.port_or_default());
  135. else if (m_connection.is_secure() && url.port_or_default() != 443)
  136. builder.appendff(":{}", url.port_or_default());
  137. builder.append("\r\n"sv);
  138. // 5. and 6. Connection Upgrade
  139. builder.append("Upgrade: websocket\r\n"sv);
  140. builder.append("Connection: Upgrade\r\n"sv);
  141. // 7. 16-byte nonce encoded as Base64
  142. u8 nonce_data[16];
  143. fill_with_random(nonce_data, 16);
  144. m_websocket_key = encode_base64(ReadonlyBytes(nonce_data, 16));
  145. builder.appendff("Sec-WebSocket-Key: {}\r\n", m_websocket_key);
  146. // 8. Origin (optional field)
  147. if (!m_connection.origin().is_empty()) {
  148. builder.appendff("Origin: {}\r\n", m_connection.origin());
  149. }
  150. // 9. Websocket version
  151. builder.append("Sec-WebSocket-Version: 13\r\n"sv);
  152. // 10. Websocket protocol (optional field)
  153. if (!m_connection.protocols().is_empty()) {
  154. builder.append("Sec-WebSocket-Protocol: "sv);
  155. builder.join(',', m_connection.protocols());
  156. builder.append("\r\n"sv);
  157. }
  158. // 11. Websocket extensions (optional field)
  159. if (!m_connection.extensions().is_empty()) {
  160. builder.append("Sec-WebSocket-Extensions: "sv);
  161. builder.join(',', m_connection.extensions());
  162. builder.append("\r\n"sv);
  163. }
  164. // 12. Additional headers
  165. for (auto& header : m_connection.headers()) {
  166. builder.appendff("{}: {}\r\n", header.name, header.value);
  167. }
  168. builder.append("\r\n"sv);
  169. m_state = WebSocket::InternalState::WaitingForServerHandshake;
  170. auto success = m_impl->send(builder.to_string().bytes());
  171. VERIFY(success);
  172. }
  173. // The server handshake message is defined in the third list of section 4.1
  174. void WebSocket::read_server_handshake()
  175. {
  176. VERIFY(m_impl);
  177. VERIFY(m_state == WebSocket::InternalState::WaitingForServerHandshake);
  178. // Read the server handshake
  179. if (!m_impl->can_read_line())
  180. return;
  181. if (!m_has_read_server_handshake_first_line) {
  182. auto header = m_impl->read_line(PAGE_SIZE).release_value_but_fixme_should_propagate_errors();
  183. auto parts = header.split(' ');
  184. if (parts.size() < 2) {
  185. dbgln("WebSocket: Server HTTP Handshake contained HTTP header was malformed");
  186. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  187. discard_connection();
  188. return;
  189. }
  190. if (parts[0] != "HTTP/1.1") {
  191. dbgln("WebSocket: Server HTTP Handshake contained HTTP header {} which isn't supported", parts[0]);
  192. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  193. discard_connection();
  194. return;
  195. }
  196. if (parts[1] != "101") {
  197. // 1. If the status code is not 101, handle as per HTTP procedures.
  198. // FIXME : This could be a redirect or a 401 authentication request, which we do not handle.
  199. dbgln("WebSocket: Server HTTP Handshake return status {} which isn't supported", parts[1]);
  200. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  201. return;
  202. }
  203. m_has_read_server_handshake_first_line = true;
  204. }
  205. // Read the rest of the reply until we find an empty line
  206. while (m_impl->can_read_line()) {
  207. auto line = m_impl->read_line(PAGE_SIZE).release_value_but_fixme_should_propagate_errors();
  208. if (line.is_whitespace()) {
  209. // We're done with the HTTP headers.
  210. // Fail the connection if we're missing any of the following:
  211. if (!m_has_read_server_handshake_upgrade) {
  212. // 2. |Upgrade| should be present
  213. dbgln("WebSocket: Server HTTP Handshake didn't contain an |Upgrade| header");
  214. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  215. return;
  216. }
  217. if (!m_has_read_server_handshake_connection) {
  218. // 2. |Connection| should be present
  219. dbgln("WebSocket: Server HTTP Handshake didn't contain a |Connection| header");
  220. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  221. return;
  222. }
  223. if (!m_has_read_server_handshake_accept) {
  224. // 2. |Sec-WebSocket-Accept| should be present
  225. dbgln("WebSocket: Server HTTP Handshake didn't contain a |Sec-WebSocket-Accept| header");
  226. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  227. return;
  228. }
  229. m_state = WebSocket::InternalState::Open;
  230. notify_open();
  231. return;
  232. }
  233. auto parts = line.split(':');
  234. if (parts.size() < 2) {
  235. // The header field is not valid
  236. dbgln("WebSocket: Got invalid header line {} in the Server HTTP handshake", line);
  237. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  238. return;
  239. }
  240. auto header_name = parts[0];
  241. if (header_name.equals_ignoring_case("Upgrade"sv)) {
  242. // 2. |Upgrade| should be case-insensitive "websocket"
  243. if (!parts[1].trim_whitespace().equals_ignoring_case("websocket"sv)) {
  244. dbgln("WebSocket: Server HTTP Handshake Header |Upgrade| should be 'websocket', got '{}'. Failing connection.", parts[1]);
  245. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  246. return;
  247. }
  248. m_has_read_server_handshake_upgrade = true;
  249. continue;
  250. }
  251. if (header_name.equals_ignoring_case("Connection"sv)) {
  252. // 3. |Connection| should be case-insensitive "Upgrade"
  253. if (!parts[1].trim_whitespace().equals_ignoring_case("Upgrade"sv)) {
  254. dbgln("WebSocket: Server HTTP Handshake Header |Connection| should be 'Upgrade', got '{}'. Failing connection.", parts[1]);
  255. return;
  256. }
  257. m_has_read_server_handshake_connection = true;
  258. continue;
  259. }
  260. if (header_name.equals_ignoring_case("Sec-WebSocket-Accept"sv)) {
  261. // 4. |Sec-WebSocket-Accept| should be base64(SHA1(|Sec-WebSocket-Key| + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
  262. auto expected_content = String::formatted("{}258EAFA5-E914-47DA-95CA-C5AB0DC85B11", m_websocket_key);
  263. Crypto::Hash::Manager hash;
  264. hash.initialize(Crypto::Hash::HashKind::SHA1);
  265. hash.update(expected_content);
  266. auto expected_sha1 = hash.digest();
  267. auto expected_sha1_string = encode_base64(ReadonlyBytes(expected_sha1.immutable_data(), expected_sha1.data_length()));
  268. if (!parts[1].trim_whitespace().equals_ignoring_case(expected_sha1_string)) {
  269. dbgln("WebSocket: Server HTTP Handshake Header |Sec-Websocket-Accept| should be '{}', got '{}'. Failing connection.", expected_sha1_string, parts[1]);
  270. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  271. return;
  272. }
  273. m_has_read_server_handshake_accept = true;
  274. continue;
  275. }
  276. if (header_name.equals_ignoring_case("Sec-WebSocket-Extensions"sv)) {
  277. // 5. |Sec-WebSocket-Extensions| should not contain an extension that doesn't appear in m_connection->extensions()
  278. auto server_extensions = parts[1].split(',');
  279. for (auto const& extension : server_extensions) {
  280. auto trimmed_extension = extension.trim_whitespace();
  281. bool found_extension = false;
  282. for (auto const& supported_extension : m_connection.extensions()) {
  283. if (trimmed_extension.equals_ignoring_case(supported_extension)) {
  284. found_extension = true;
  285. }
  286. }
  287. if (!found_extension) {
  288. dbgln("WebSocket: Server HTTP Handshake Header |Sec-WebSocket-Extensions| contains '{}', which is not supported by the client. Failing connection.", trimmed_extension);
  289. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  290. return;
  291. }
  292. }
  293. continue;
  294. }
  295. if (header_name.equals_ignoring_case("Sec-WebSocket-Protocol"sv)) {
  296. // 6. |Sec-WebSocket-Protocol| should not contain an extension that doesn't appear in m_connection->protocols()
  297. auto server_protocols = parts[1].split(',');
  298. for (auto const& protocol : server_protocols) {
  299. auto trimmed_protocol = protocol.trim_whitespace();
  300. bool found_protocol = false;
  301. for (auto const& supported_protocol : m_connection.protocols()) {
  302. if (trimmed_protocol.equals_ignoring_case(supported_protocol)) {
  303. found_protocol = true;
  304. }
  305. }
  306. if (!found_protocol) {
  307. dbgln("WebSocket: Server HTTP Handshake Header |Sec-WebSocket-Protocol| contains '{}', which is not supported by the client. Failing connection.", trimmed_protocol);
  308. fatal_error(WebSocket::Error::ConnectionUpgradeFailed);
  309. return;
  310. }
  311. }
  312. continue;
  313. }
  314. }
  315. // If needed, we will keep reading the header on the next drain_read call
  316. }
  317. void WebSocket::read_frame()
  318. {
  319. VERIFY(m_impl);
  320. VERIFY(m_state == WebSocket::InternalState::Open || m_state == WebSocket::InternalState::Closing);
  321. auto head_bytes_result = m_impl->read(2);
  322. if (head_bytes_result.is_error() || head_bytes_result.value().is_empty()) {
  323. // The connection got closed.
  324. m_state = WebSocket::InternalState::Closed;
  325. notify_close(m_last_close_code, m_last_close_message, true);
  326. discard_connection();
  327. return;
  328. }
  329. auto head_bytes = head_bytes_result.release_value();
  330. VERIFY(head_bytes.size() == 2);
  331. bool is_final_frame = head_bytes[0] & 0x80;
  332. if (!is_final_frame) {
  333. // FIXME: Support fragmented frames
  334. TODO();
  335. }
  336. auto op_code = (WebSocket::OpCode)(head_bytes[0] & 0x0f);
  337. bool is_masked = head_bytes[1] & 0x80;
  338. // Parse the payload length.
  339. size_t payload_length;
  340. auto payload_length_bits = head_bytes[1] & 0x7f;
  341. if (payload_length_bits == 127) {
  342. // A code of 127 means that the next 8 bytes contains the payload length
  343. auto actual_bytes = MUST(m_impl->read(8));
  344. VERIFY(actual_bytes.size() == 8);
  345. u64 full_payload_length = (u64)((u64)(actual_bytes[0] & 0xff) << 56)
  346. | (u64)((u64)(actual_bytes[1] & 0xff) << 48)
  347. | (u64)((u64)(actual_bytes[2] & 0xff) << 40)
  348. | (u64)((u64)(actual_bytes[3] & 0xff) << 32)
  349. | (u64)((u64)(actual_bytes[4] & 0xff) << 24)
  350. | (u64)((u64)(actual_bytes[5] & 0xff) << 16)
  351. | (u64)((u64)(actual_bytes[6] & 0xff) << 8)
  352. | (u64)((u64)(actual_bytes[7] & 0xff) << 0);
  353. VERIFY(full_payload_length <= NumericLimits<size_t>::max());
  354. payload_length = (size_t)full_payload_length;
  355. } else if (payload_length_bits == 126) {
  356. // A code of 126 means that the next 2 bytes contains the payload length
  357. auto actual_bytes = MUST(m_impl->read(2));
  358. VERIFY(actual_bytes.size() == 2);
  359. payload_length = (size_t)((size_t)(actual_bytes[0] & 0xff) << 8)
  360. | (size_t)((size_t)(actual_bytes[1] & 0xff) << 0);
  361. } else {
  362. payload_length = (size_t)payload_length_bits;
  363. }
  364. // Parse the mask, if it exists.
  365. // Note : this is technically non-conformant with Section 5.1 :
  366. // > A server MUST NOT mask any frames that it sends to the client.
  367. // > A client MUST close a connection if it detects a masked frame.
  368. // > (These rules might be relaxed in a future specification.)
  369. // But because it doesn't cost much, we can support receiving masked frames anyways.
  370. u8 masking_key[4];
  371. if (is_masked) {
  372. auto masking_key_data = MUST(m_impl->read(4));
  373. VERIFY(masking_key_data.size() == 4);
  374. masking_key[0] = masking_key_data[0];
  375. masking_key[1] = masking_key_data[1];
  376. masking_key[2] = masking_key_data[2];
  377. masking_key[3] = masking_key_data[3];
  378. }
  379. auto payload = ByteBuffer::create_uninitialized(payload_length).release_value_but_fixme_should_propagate_errors(); // FIXME: Handle possible OOM situation.
  380. u64 read_length = 0;
  381. while (read_length < payload_length) {
  382. auto payload_part_result = m_impl->read(payload_length - read_length);
  383. if (payload_part_result.is_error() || payload_part_result.value().is_empty()) {
  384. // We got disconnected, somehow.
  385. dbgln("Websocket: Server disconnected while sending payload ({} bytes read out of {})", read_length, payload_length);
  386. fatal_error(WebSocket::Error::ServerClosedSocket);
  387. return;
  388. }
  389. auto payload_part = payload_part_result.release_value();
  390. // We read at most "actual_length - read" bytes, so this is safe to do.
  391. payload.overwrite(read_length, payload_part.data(), payload_part.size());
  392. read_length += payload_part.size();
  393. }
  394. if (is_masked) {
  395. // Unmask the payload
  396. for (size_t i = 0; i < payload.size(); ++i) {
  397. payload[i] = payload[i] ^ (masking_key[i % 4]);
  398. }
  399. }
  400. if (op_code == WebSocket::OpCode::ConnectionClose) {
  401. if (payload.size() > 1) {
  402. m_last_close_code = (((u16)(payload[0] & 0xff) << 8) | ((u16)(payload[1] & 0xff)));
  403. m_last_close_message = String(ReadonlyBytes(payload.offset_pointer(2), payload.size() - 2));
  404. }
  405. m_state = WebSocket::InternalState::Closing;
  406. return;
  407. }
  408. if (op_code == WebSocket::OpCode::Ping) {
  409. // Immediately send a pong frame as a reply, with the given payload.
  410. send_frame(WebSocket::OpCode::Pong, payload, true);
  411. return;
  412. }
  413. if (op_code == WebSocket::OpCode::Pong) {
  414. // We can safely ignore the pong
  415. return;
  416. }
  417. if (op_code == WebSocket::OpCode::Continuation) {
  418. // FIXME: Support fragmented frames
  419. TODO();
  420. }
  421. if (op_code == WebSocket::OpCode::Text) {
  422. notify_message(Message(payload, true));
  423. return;
  424. }
  425. if (op_code == WebSocket::OpCode::Binary) {
  426. notify_message(Message(payload, false));
  427. return;
  428. }
  429. dbgln("Websocket: Found unknown opcode {}", (u8)op_code);
  430. }
  431. void WebSocket::send_frame(WebSocket::OpCode op_code, ReadonlyBytes payload, bool is_final)
  432. {
  433. VERIFY(m_impl);
  434. VERIFY(m_state == WebSocket::InternalState::Open);
  435. u8 frame_head[1] = { (u8)((is_final ? 0x80 : 0x00) | ((u8)(op_code)&0xf)) };
  436. m_impl->send(ReadonlyBytes(frame_head, 1));
  437. // Section 5.1 : a client MUST mask all frames that it sends to the server
  438. bool has_mask = true;
  439. // FIXME: If the payload has a size > size_t max on a 32-bit platform, we could
  440. // technically stream it via non-final packets. However, the size was already
  441. // truncated earlier in the call stack when stuffing into a ReadonlyBytes
  442. if (payload.size() > NumericLimits<u16>::max()) {
  443. // Send (the 'mask' flag + 127) + the 8-byte payload length
  444. if constexpr (sizeof(size_t) >= 8) {
  445. u8 payload_length[9] = {
  446. (u8)((has_mask ? 0x80 : 0x00) | 127),
  447. (u8)((payload.size() >> 56) & 0xff),
  448. (u8)((payload.size() >> 48) & 0xff),
  449. (u8)((payload.size() >> 40) & 0xff),
  450. (u8)((payload.size() >> 32) & 0xff),
  451. (u8)((payload.size() >> 24) & 0xff),
  452. (u8)((payload.size() >> 16) & 0xff),
  453. (u8)((payload.size() >> 8) & 0xff),
  454. (u8)((payload.size() >> 0) & 0xff),
  455. };
  456. m_impl->send(ReadonlyBytes(payload_length, 9));
  457. } else {
  458. u8 payload_length[9] = {
  459. (u8)((has_mask ? 0x80 : 0x00) | 127),
  460. 0,
  461. 0,
  462. 0,
  463. 0,
  464. (u8)((payload.size() >> 24) & 0xff),
  465. (u8)((payload.size() >> 16) & 0xff),
  466. (u8)((payload.size() >> 8) & 0xff),
  467. (u8)((payload.size() >> 0) & 0xff),
  468. };
  469. m_impl->send(ReadonlyBytes(payload_length, 9));
  470. }
  471. } else if (payload.size() >= 126) {
  472. // Send (the 'mask' flag + 126) + the 2-byte payload length
  473. u8 payload_length[3] = {
  474. (u8)((has_mask ? 0x80 : 0x00) | 126),
  475. (u8)((payload.size() >> 8) & 0xff),
  476. (u8)((payload.size() >> 0) & 0xff),
  477. };
  478. m_impl->send(ReadonlyBytes(payload_length, 3));
  479. } else {
  480. // Send the mask flag + the payload in a single byte
  481. u8 payload_length[1] = {
  482. (u8)((has_mask ? 0x80 : 0x00) | (u8)(payload.size() & 0x7f)),
  483. };
  484. m_impl->send(ReadonlyBytes(payload_length, 1));
  485. }
  486. if (has_mask) {
  487. // Section 10.3 :
  488. // > Clients MUST choose a new masking key for each frame, using an algorithm
  489. // > that cannot be predicted by end applications that provide data
  490. u8 masking_key[4];
  491. fill_with_random(masking_key, 4);
  492. m_impl->send(ReadonlyBytes(masking_key, 4));
  493. // don't try to send empty payload
  494. if (payload.size() == 0)
  495. return;
  496. // Mask the payload
  497. auto buffer_result = ByteBuffer::create_uninitialized(payload.size());
  498. if (!buffer_result.is_error()) {
  499. auto& masked_payload = buffer_result.value();
  500. for (size_t i = 0; i < payload.size(); ++i) {
  501. masked_payload[i] = payload[i] ^ (masking_key[i % 4]);
  502. }
  503. m_impl->send(masked_payload);
  504. }
  505. } else if (payload.size() > 0) {
  506. m_impl->send(payload);
  507. }
  508. }
  509. void WebSocket::fatal_error(WebSocket::Error error)
  510. {
  511. m_state = WebSocket::InternalState::Errored;
  512. notify_error(error);
  513. discard_connection();
  514. }
  515. void WebSocket::discard_connection()
  516. {
  517. deferred_invoke([this] {
  518. VERIFY(m_impl);
  519. m_impl->discard_connection();
  520. m_impl->on_connection_error = nullptr;
  521. m_impl->on_connected = nullptr;
  522. m_impl->on_ready_to_read = nullptr;
  523. m_impl = nullptr;
  524. });
  525. }
  526. void WebSocket::notify_open()
  527. {
  528. if (!on_open)
  529. return;
  530. on_open();
  531. }
  532. void WebSocket::notify_close(u16 code, String reason, bool was_clean)
  533. {
  534. if (!on_close)
  535. return;
  536. on_close(code, move(reason), was_clean);
  537. }
  538. void WebSocket::notify_error(WebSocket::Error error)
  539. {
  540. if (!on_error)
  541. return;
  542. on_error(error);
  543. }
  544. void WebSocket::notify_message(Message message)
  545. {
  546. if (!on_message)
  547. return;
  548. on_message(move(message));
  549. }
  550. }