WebSocket.cpp 24 KB

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