WebSocket.cpp 23 KB

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