WebSocket.cpp 23 KB

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