WebSocket.cpp 23 KB

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