wsl_peer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. /**************************************************************************/
  2. /* wsl_peer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "wsl_peer.h"
  31. #ifndef WEB_ENABLED
  32. #include "core/io/stream_peer_tls.h"
  33. CryptoCore::RandomGenerator *WSLPeer::_static_rng = nullptr;
  34. void WSLPeer::initialize() {
  35. WebSocketPeer::_create = WSLPeer::_create;
  36. _static_rng = memnew(CryptoCore::RandomGenerator);
  37. _static_rng->init();
  38. }
  39. void WSLPeer::deinitialize() {
  40. if (_static_rng) {
  41. memdelete(_static_rng);
  42. _static_rng = nullptr;
  43. }
  44. }
  45. ///
  46. /// Resolver
  47. ///
  48. void WSLPeer::Resolver::start(const String &p_host, int p_port) {
  49. stop();
  50. port = p_port;
  51. if (p_host.is_valid_ip_address()) {
  52. ip_candidates.push_back(IPAddress(p_host));
  53. } else {
  54. // Queue hostname for resolution.
  55. resolver_id = IP::get_singleton()->resolve_hostname_queue_item(p_host);
  56. ERR_FAIL_COND(resolver_id == IP::RESOLVER_INVALID_ID);
  57. // Check if it was found in cache.
  58. IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id);
  59. if (ip_status == IP::RESOLVER_STATUS_DONE) {
  60. ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id);
  61. IP::get_singleton()->erase_resolve_item(resolver_id);
  62. resolver_id = IP::RESOLVER_INVALID_ID;
  63. }
  64. }
  65. }
  66. void WSLPeer::Resolver::stop() {
  67. if (resolver_id != IP::RESOLVER_INVALID_ID) {
  68. IP::get_singleton()->erase_resolve_item(resolver_id);
  69. resolver_id = IP::RESOLVER_INVALID_ID;
  70. }
  71. port = 0;
  72. }
  73. void WSLPeer::Resolver::try_next_candidate(Ref<StreamPeerTCP> &p_tcp) {
  74. // Check if we still need resolving.
  75. if (resolver_id != IP::RESOLVER_INVALID_ID) {
  76. IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id);
  77. if (ip_status == IP::RESOLVER_STATUS_WAITING) {
  78. return;
  79. }
  80. if (ip_status == IP::RESOLVER_STATUS_DONE) {
  81. ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id);
  82. }
  83. IP::get_singleton()->erase_resolve_item(resolver_id);
  84. resolver_id = IP::RESOLVER_INVALID_ID;
  85. }
  86. // Try the current candidate if we have one.
  87. if (p_tcp->get_status() != StreamPeerTCP::STATUS_NONE) {
  88. p_tcp->poll();
  89. StreamPeerTCP::Status status = p_tcp->get_status();
  90. if (status == StreamPeerTCP::STATUS_CONNECTED) {
  91. p_tcp->set_no_delay(true);
  92. ip_candidates.clear();
  93. return;
  94. } else if (status == StreamPeerTCP::STATUS_CONNECTING) {
  95. return; // Keep connecting.
  96. } else {
  97. p_tcp->disconnect_from_host();
  98. }
  99. }
  100. // Keep trying next candidate.
  101. while (ip_candidates.size()) {
  102. Error err = p_tcp->connect_to_host(ip_candidates.pop_front(), port);
  103. if (err == OK) {
  104. return;
  105. } else {
  106. p_tcp->disconnect_from_host();
  107. }
  108. }
  109. }
  110. ///
  111. /// Server functions
  112. ///
  113. Error WSLPeer::accept_stream(Ref<StreamPeer> p_stream) {
  114. ERR_FAIL_COND_V(wsl_ctx || tcp.is_valid(), ERR_ALREADY_IN_USE);
  115. ERR_FAIL_COND_V(p_stream.is_null(), ERR_INVALID_PARAMETER);
  116. _clear();
  117. if (p_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static())) {
  118. tcp = p_stream;
  119. connection = p_stream;
  120. use_tls = false;
  121. } else if (p_stream->is_class_ptr(StreamPeerTLS::get_class_ptr_static())) {
  122. Ref<StreamPeer> base_stream = static_cast<Ref<StreamPeerTLS>>(p_stream)->get_stream();
  123. ERR_FAIL_COND_V(base_stream.is_null() || !base_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static()), ERR_INVALID_PARAMETER);
  124. tcp = static_cast<Ref<StreamPeerTCP>>(base_stream);
  125. connection = p_stream;
  126. use_tls = true;
  127. }
  128. ERR_FAIL_COND_V(connection.is_null() || tcp.is_null(), ERR_INVALID_PARAMETER);
  129. is_server = true;
  130. ready_state = STATE_CONNECTING;
  131. handshake_buffer->resize(WSL_MAX_HEADER_SIZE);
  132. handshake_buffer->seek(0);
  133. return OK;
  134. }
  135. bool WSLPeer::_parse_client_request() {
  136. Vector<String> psa = String((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4).split("\r\n");
  137. int len = psa.size();
  138. ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
  139. Vector<String> req = psa[0].split(" ", false);
  140. ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");
  141. // Wrong protocol
  142. ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");
  143. HashMap<String, String> headers;
  144. for (int i = 1; i < len; i++) {
  145. Vector<String> header = psa[i].split(":", false, 1);
  146. ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
  147. String name = header[0].to_lower();
  148. String value = header[1].strip_edges();
  149. if (headers.has(name)) {
  150. headers[name] += "," + value;
  151. } else {
  152. headers[name] = value;
  153. }
  154. }
  155. requested_host = headers.has("host") ? headers.get("host") : "";
  156. requested_url = (use_tls ? "wss://" : "ws://") + requested_host + req[1];
  157. #define WSL_CHECK(NAME, VALUE) \
  158. ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
  159. "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
  160. #define WSL_CHECK_EX(NAME) \
  161. ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
  162. WSL_CHECK("upgrade", "websocket");
  163. WSL_CHECK("sec-websocket-version", "13");
  164. WSL_CHECK_EX("sec-websocket-key");
  165. WSL_CHECK_EX("connection");
  166. #undef WSL_CHECK_EX
  167. #undef WSL_CHECK
  168. session_key = headers["sec-websocket-key"];
  169. if (headers.has("sec-websocket-protocol")) {
  170. Vector<String> protos = headers["sec-websocket-protocol"].split(",");
  171. for (int i = 0; i < protos.size(); i++) {
  172. String proto = protos[i].strip_edges();
  173. // Check if we have the given protocol
  174. for (int j = 0; j < supported_protocols.size(); j++) {
  175. if (proto != supported_protocols[j]) {
  176. continue;
  177. }
  178. selected_protocol = proto;
  179. break;
  180. }
  181. // Found a protocol
  182. if (!selected_protocol.is_empty()) {
  183. break;
  184. }
  185. }
  186. if (selected_protocol.is_empty()) { // Invalid protocol(s) requested
  187. return false;
  188. }
  189. } else if (supported_protocols.size() > 0) { // No protocol requested, but we need one
  190. return false;
  191. }
  192. return true;
  193. }
  194. Error WSLPeer::_do_server_handshake() {
  195. if (use_tls) {
  196. Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(connection);
  197. if (tls.is_null()) {
  198. ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerTLS for WebSocket handshake.");
  199. close(-1);
  200. return FAILED;
  201. }
  202. tls->poll();
  203. if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
  204. return OK; // Pending handshake
  205. } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) {
  206. print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", tls->get_status()));
  207. close(-1);
  208. return FAILED;
  209. }
  210. }
  211. if (pending_request) {
  212. int read = 0;
  213. while (true) {
  214. ERR_FAIL_COND_V_MSG(handshake_buffer->get_available_bytes() < 1, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big.");
  215. int pos = handshake_buffer->get_position();
  216. uint8_t byte;
  217. Error err = connection->get_partial_data(&byte, 1, read);
  218. if (err != OK) { // Got an error
  219. print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err));
  220. close(-1);
  221. return FAILED;
  222. } else if (read != 1) { // Busy, wait next poll
  223. return OK;
  224. }
  225. handshake_buffer->put_u8(byte);
  226. const char *r = (const char *)handshake_buffer->get_data_array().ptr();
  227. int l = pos;
  228. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  229. if (!_parse_client_request()) {
  230. close(-1);
  231. return FAILED;
  232. }
  233. String s = "HTTP/1.1 101 Switching Protocols\r\n";
  234. s += "Upgrade: websocket\r\n";
  235. s += "Connection: Upgrade\r\n";
  236. s += "Sec-WebSocket-Accept: " + _compute_key_response(session_key) + "\r\n";
  237. if (!selected_protocol.is_empty()) {
  238. s += "Sec-WebSocket-Protocol: " + selected_protocol + "\r\n";
  239. }
  240. for (int i = 0; i < handshake_headers.size(); i++) {
  241. s += handshake_headers[i] + "\r\n";
  242. }
  243. s += "\r\n";
  244. CharString cs = s.utf8();
  245. handshake_buffer->clear();
  246. handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length());
  247. handshake_buffer->seek(0);
  248. pending_request = false;
  249. break;
  250. }
  251. }
  252. }
  253. if (pending_request) { // Still pending.
  254. return OK;
  255. }
  256. int left = handshake_buffer->get_available_bytes();
  257. if (left) {
  258. Vector<uint8_t> data = handshake_buffer->get_data_array();
  259. int pos = handshake_buffer->get_position();
  260. int sent = 0;
  261. Error err = connection->put_partial_data(data.ptr() + pos, left, sent);
  262. if (err != OK) {
  263. print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err));
  264. close(-1);
  265. return err;
  266. }
  267. handshake_buffer->seek(pos + sent);
  268. left -= sent;
  269. if (left == 0) {
  270. resolver.stop();
  271. // Response sent, initialize wslay context.
  272. wslay_event_context_server_init(&wsl_ctx, &_wsl_callbacks, this);
  273. wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size);
  274. in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets);
  275. packet_buffer.resize(inbound_buffer_size);
  276. ready_state = STATE_OPEN;
  277. }
  278. }
  279. return OK;
  280. }
  281. ///
  282. /// Client functions
  283. ///
  284. void WSLPeer::_do_client_handshake() {
  285. ERR_FAIL_COND(tcp.is_null());
  286. // Try to connect to candidates.
  287. if (resolver.has_more_candidates()) {
  288. resolver.try_next_candidate(tcp);
  289. if (resolver.has_more_candidates()) {
  290. return; // Still pending.
  291. }
  292. }
  293. tcp->poll();
  294. if (tcp->get_status() == StreamPeerTCP::STATUS_CONNECTING) {
  295. return; // Keep connecting.
  296. } else if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  297. close(-1); // Failed to connect.
  298. return;
  299. }
  300. if (use_tls) {
  301. Ref<StreamPeerTLS> tls;
  302. if (connection == tcp) {
  303. // Start SSL handshake
  304. tls = Ref<StreamPeerTLS>(StreamPeerTLS::create());
  305. ERR_FAIL_COND(tls.is_null());
  306. if (tls->connect_to_stream(tcp, requested_host, tls_options) != OK) {
  307. close(-1);
  308. return; // Error.
  309. }
  310. connection = tls;
  311. } else {
  312. tls = static_cast<Ref<StreamPeerTLS>>(connection);
  313. ERR_FAIL_COND(tls.is_null());
  314. tls->poll();
  315. }
  316. if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
  317. return; // Need more polling.
  318. } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) {
  319. close(-1);
  320. return; // Error.
  321. }
  322. }
  323. // Do websocket handshake.
  324. if (pending_request) {
  325. int left = handshake_buffer->get_available_bytes();
  326. int pos = handshake_buffer->get_position();
  327. const Vector<uint8_t> data = handshake_buffer->get_data_array();
  328. int sent = 0;
  329. Error err = connection->put_partial_data(data.ptr() + pos, left, sent);
  330. // Sending handshake failed
  331. if (err != OK) {
  332. close(-1);
  333. return; // Error.
  334. }
  335. handshake_buffer->seek(pos + sent);
  336. if (handshake_buffer->get_available_bytes() == 0) {
  337. pending_request = false;
  338. handshake_buffer->clear();
  339. handshake_buffer->resize(WSL_MAX_HEADER_SIZE);
  340. handshake_buffer->seek(0);
  341. }
  342. } else {
  343. int read = 0;
  344. while (true) {
  345. int left = handshake_buffer->get_available_bytes();
  346. int pos = handshake_buffer->get_position();
  347. if (left == 0) {
  348. // Header is too big
  349. close(-1);
  350. ERR_FAIL_MSG("Response headers too big.");
  351. }
  352. uint8_t byte;
  353. Error err = connection->get_partial_data(&byte, 1, read);
  354. if (err != OK) {
  355. // Got some error.
  356. close(-1);
  357. return;
  358. } else if (read != 1) {
  359. // Busy, wait next poll.
  360. break;
  361. }
  362. handshake_buffer->put_u8(byte);
  363. // Check "\r\n\r\n" header terminator
  364. const char *r = (const char *)handshake_buffer->get_data_array().ptr();
  365. int l = pos;
  366. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  367. // Response is over, verify headers and initialize wslay context/
  368. if (!_verify_server_response()) {
  369. close(-1);
  370. ERR_FAIL_MSG("Invalid response headers.");
  371. }
  372. wslay_event_context_client_init(&wsl_ctx, &_wsl_callbacks, this);
  373. wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size);
  374. in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets);
  375. packet_buffer.resize(inbound_buffer_size);
  376. ready_state = STATE_OPEN;
  377. break;
  378. }
  379. }
  380. }
  381. }
  382. bool WSLPeer::_verify_server_response() {
  383. Vector<String> psa = String((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4).split("\r\n");
  384. int len = psa.size();
  385. ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers. Got: " + itos(len) + ", expected >= 4.");
  386. Vector<String> req = psa[0].split(" ", false);
  387. ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code. Got '" + psa[0] + "', expected 'HTTP/1.1 101'.");
  388. // Wrong protocol
  389. ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1", false, "Invalid protocol. Got: '" + req[0] + "', expected 'HTTP/1.1'.");
  390. ERR_FAIL_COND_V_MSG(req[1] != "101", false, "Invalid status code. Got: '" + req[1] + "', expected '101'.");
  391. HashMap<String, String> headers;
  392. for (int i = 1; i < len; i++) {
  393. Vector<String> header = psa[i].split(":", false, 1);
  394. ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + ".");
  395. String name = header[0].to_lower();
  396. String value = header[1].strip_edges();
  397. if (headers.has(name)) {
  398. headers[name] += "," + value;
  399. } else {
  400. headers[name] = value;
  401. }
  402. }
  403. #define WSL_CHECK(NAME, VALUE) \
  404. ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
  405. "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
  406. #define WSL_CHECK_NC(NAME, VALUE) \
  407. ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \
  408. "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
  409. WSL_CHECK("connection", "upgrade");
  410. WSL_CHECK("upgrade", "websocket");
  411. WSL_CHECK_NC("sec-websocket-accept", _compute_key_response(session_key));
  412. #undef WSL_CHECK_NC
  413. #undef WSL_CHECK
  414. if (supported_protocols.size() == 0) {
  415. // We didn't request a custom protocol
  416. ERR_FAIL_COND_V_MSG(headers.has("sec-websocket-protocol"), false, "Received unrequested sub-protocol -> " + headers["sec-websocket-protocol"]);
  417. } else {
  418. // We requested at least one custom protocol but didn't receive one
  419. ERR_FAIL_COND_V_MSG(!headers.has("sec-websocket-protocol"), false, "Requested sub-protocol(s) but received none.");
  420. // Check received sub-protocol was one of those requested.
  421. selected_protocol = headers["sec-websocket-protocol"];
  422. bool valid = false;
  423. for (int i = 0; i < supported_protocols.size(); i++) {
  424. if (supported_protocols[i] != selected_protocol) {
  425. continue;
  426. }
  427. valid = true;
  428. break;
  429. }
  430. if (!valid) {
  431. ERR_FAIL_V_MSG(false, "Received unrequested sub-protocol -> " + selected_protocol);
  432. }
  433. }
  434. return true;
  435. }
  436. Error WSLPeer::connect_to_url(const String &p_url, Ref<TLSOptions> p_options) {
  437. ERR_FAIL_COND_V(wsl_ctx || tcp.is_valid(), ERR_ALREADY_IN_USE);
  438. ERR_FAIL_COND_V(p_url.is_empty(), ERR_INVALID_PARAMETER);
  439. ERR_FAIL_COND_V(p_options.is_valid() && p_options->is_server(), ERR_INVALID_PARAMETER);
  440. _clear();
  441. String host;
  442. String path;
  443. String scheme;
  444. int port = 0;
  445. Error err = p_url.parse_url(scheme, host, port, path);
  446. ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url);
  447. if (scheme.is_empty()) {
  448. scheme = "ws://";
  449. }
  450. ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme));
  451. use_tls = false;
  452. if (scheme == "wss://") {
  453. use_tls = true;
  454. }
  455. if (port == 0) {
  456. port = use_tls ? 443 : 80;
  457. }
  458. if (path.is_empty()) {
  459. path = "/";
  460. }
  461. ERR_FAIL_COND_V_MSG(use_tls && !StreamPeerTLS::is_available(), ERR_UNAVAILABLE, "WSS is not available in this build.");
  462. requested_url = p_url;
  463. requested_host = host;
  464. if (p_options.is_valid()) {
  465. tls_options = p_options;
  466. } else {
  467. tls_options = TLSOptions::client();
  468. }
  469. tcp.instantiate();
  470. resolver.start(host, port);
  471. resolver.try_next_candidate(tcp);
  472. if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTING && tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED && !resolver.has_more_candidates()) {
  473. _clear();
  474. return FAILED;
  475. }
  476. connection = tcp;
  477. // Prepare handshake request.
  478. session_key = _generate_key();
  479. String request = "GET " + path + " HTTP/1.1\r\n";
  480. String port_string;
  481. if ((port != 80 && !use_tls) || (port != 443 && use_tls)) {
  482. port_string = ":" + itos(port);
  483. }
  484. request += "Host: " + host + port_string + "\r\n";
  485. request += "Upgrade: websocket\r\n";
  486. request += "Connection: Upgrade\r\n";
  487. request += "Sec-WebSocket-Key: " + session_key + "\r\n";
  488. request += "Sec-WebSocket-Version: 13\r\n";
  489. if (supported_protocols.size() > 0) {
  490. request += "Sec-WebSocket-Protocol: ";
  491. for (int i = 0; i < supported_protocols.size(); i++) {
  492. if (i != 0) {
  493. request += ",";
  494. }
  495. request += supported_protocols[i];
  496. }
  497. request += "\r\n";
  498. }
  499. for (int i = 0; i < handshake_headers.size(); i++) {
  500. request += handshake_headers[i] + "\r\n";
  501. }
  502. request += "\r\n";
  503. CharString cs = request.utf8();
  504. handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length());
  505. handshake_buffer->seek(0);
  506. ready_state = STATE_CONNECTING;
  507. is_server = false;
  508. return OK;
  509. }
  510. ///
  511. /// Callback functions.
  512. ///
  513. ssize_t WSLPeer::_wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) {
  514. WSLPeer *peer = (WSLPeer *)user_data;
  515. Ref<StreamPeer> conn = peer->connection;
  516. if (conn.is_null()) {
  517. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  518. return -1;
  519. }
  520. int read = 0;
  521. Error err = conn->get_partial_data(data, len, read);
  522. if (err != OK) {
  523. print_verbose("Websocket get data error: " + itos(err) + ", read (should be 0!): " + itos(read));
  524. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  525. return -1;
  526. }
  527. if (read == 0) {
  528. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  529. return -1;
  530. }
  531. return read;
  532. }
  533. ssize_t WSLPeer::_wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) {
  534. WSLPeer *peer = (WSLPeer *)user_data;
  535. Ref<StreamPeer> conn = peer->connection;
  536. if (conn.is_null()) {
  537. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  538. return -1;
  539. }
  540. int sent = 0;
  541. Error err = conn->put_partial_data(data, len, sent);
  542. if (err != OK) {
  543. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  544. return -1;
  545. }
  546. if (sent == 0) {
  547. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  548. return -1;
  549. }
  550. return sent;
  551. }
  552. int WSLPeer::_wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) {
  553. ERR_FAIL_NULL_V(_static_rng, WSLAY_ERR_CALLBACK_FAILURE);
  554. Error err = _static_rng->get_random_bytes(buf, len);
  555. ERR_FAIL_COND_V(err != OK, WSLAY_ERR_CALLBACK_FAILURE);
  556. return 0;
  557. }
  558. void WSLPeer::_wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) {
  559. WSLPeer *peer = (WSLPeer *)user_data;
  560. uint8_t op = arg->opcode;
  561. if (op == WSLAY_CONNECTION_CLOSE) {
  562. // Close request or confirmation.
  563. peer->close_code = arg->status_code;
  564. size_t len = arg->msg_length;
  565. peer->close_reason = "";
  566. if (len > 2 /* first 2 bytes = close code */) {
  567. peer->close_reason.parse_utf8((char *)arg->msg + 2, len - 2);
  568. }
  569. if (peer->ready_state == STATE_OPEN) {
  570. peer->ready_state = STATE_CLOSING;
  571. }
  572. return;
  573. }
  574. if (peer->ready_state == STATE_CLOSING) {
  575. return;
  576. }
  577. if (op == WSLAY_TEXT_FRAME || op == WSLAY_BINARY_FRAME) {
  578. // Message.
  579. uint8_t is_string = arg->opcode == WSLAY_TEXT_FRAME ? 1 : 0;
  580. peer->in_buffer.write_packet(arg->msg, arg->msg_length, &is_string);
  581. }
  582. // Ping or pong.
  583. }
  584. wslay_event_callbacks WSLPeer::_wsl_callbacks = {
  585. _wsl_recv_callback,
  586. _wsl_send_callback,
  587. _wsl_genmask_callback,
  588. nullptr, /* on_frame_recv_start_callback */
  589. nullptr, /* on_frame_recv_callback */
  590. nullptr, /* on_frame_recv_end_callback */
  591. _wsl_msg_recv_callback
  592. };
  593. String WSLPeer::_generate_key() {
  594. // Random key
  595. Vector<uint8_t> bkey;
  596. int len = 16; // 16 bytes, as per RFC
  597. bkey.resize(len);
  598. _wsl_genmask_callback(nullptr, bkey.ptrw(), len, nullptr);
  599. return CryptoCore::b64_encode_str(bkey.ptrw(), len);
  600. }
  601. String WSLPeer::_compute_key_response(String p_key) {
  602. String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC
  603. Vector<uint8_t> sha = key.sha1_buffer();
  604. return CryptoCore::b64_encode_str(sha.ptr(), sha.size());
  605. }
  606. void WSLPeer::poll() {
  607. // Nothing to do.
  608. if (ready_state == STATE_CLOSED) {
  609. return;
  610. }
  611. if (ready_state == STATE_CONNECTING) {
  612. if (is_server) {
  613. _do_server_handshake();
  614. } else {
  615. _do_client_handshake();
  616. }
  617. }
  618. if (ready_state == STATE_OPEN || ready_state == STATE_CLOSING) {
  619. ERR_FAIL_NULL(wsl_ctx);
  620. int err = 0;
  621. if ((err = wslay_event_recv(wsl_ctx)) != 0 || (err = wslay_event_send(wsl_ctx)) != 0) {
  622. // Error close.
  623. print_verbose("Websocket (wslay) poll error: " + itos(err));
  624. wslay_event_context_free(wsl_ctx);
  625. wsl_ctx = nullptr;
  626. close(-1);
  627. return;
  628. }
  629. if (wslay_event_get_close_sent(wsl_ctx) && wslay_event_get_close_received(wsl_ctx)) {
  630. // Clean close.
  631. wslay_event_context_free(wsl_ctx);
  632. wsl_ctx = nullptr;
  633. close(-1);
  634. return;
  635. }
  636. }
  637. }
  638. Error WSLPeer::_send(const uint8_t *p_buffer, int p_buffer_size, wslay_opcode p_opcode) {
  639. ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED);
  640. ERR_FAIL_COND_V(wslay_event_get_queued_msg_count(wsl_ctx) >= (uint32_t)max_queued_packets, ERR_OUT_OF_MEMORY);
  641. ERR_FAIL_COND_V(outbound_buffer_size > 0 && (wslay_event_get_queued_msg_length(wsl_ctx) + p_buffer_size > (uint32_t)outbound_buffer_size), ERR_OUT_OF_MEMORY);
  642. struct wslay_event_msg msg;
  643. msg.opcode = p_opcode;
  644. msg.msg = p_buffer;
  645. msg.msg_length = p_buffer_size;
  646. // Queue & send message.
  647. if (wslay_event_queue_msg(wsl_ctx, &msg) != 0 || wslay_event_send(wsl_ctx) != 0) {
  648. close(-1);
  649. return FAILED;
  650. }
  651. return OK;
  652. }
  653. Error WSLPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) {
  654. wslay_opcode opcode = p_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME;
  655. return _send(p_buffer, p_buffer_size, opcode);
  656. }
  657. Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  658. return _send(p_buffer, p_buffer_size, WSLAY_BINARY_FRAME);
  659. }
  660. Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  661. r_buffer_size = 0;
  662. ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED);
  663. if (in_buffer.packets_left() == 0) {
  664. return ERR_UNAVAILABLE;
  665. }
  666. int read = 0;
  667. uint8_t *rw = packet_buffer.ptrw();
  668. in_buffer.read_packet(rw, packet_buffer.size(), &was_string, read);
  669. *r_buffer = rw;
  670. r_buffer_size = read;
  671. return OK;
  672. }
  673. int WSLPeer::get_available_packet_count() const {
  674. if (ready_state != STATE_OPEN) {
  675. return 0;
  676. }
  677. return in_buffer.packets_left();
  678. }
  679. int WSLPeer::get_current_outbound_buffered_amount() const {
  680. if (ready_state != STATE_OPEN) {
  681. return 0;
  682. }
  683. return wslay_event_get_queued_msg_length(wsl_ctx);
  684. }
  685. void WSLPeer::close(int p_code, String p_reason) {
  686. if (p_code < 0) {
  687. // Force immediate close.
  688. ready_state = STATE_CLOSED;
  689. }
  690. if (ready_state == STATE_OPEN && !wslay_event_get_close_sent(wsl_ctx)) {
  691. CharString cs = p_reason.utf8();
  692. wslay_event_queue_close(wsl_ctx, p_code, (uint8_t *)cs.ptr(), cs.length());
  693. wslay_event_send(wsl_ctx);
  694. ready_state = STATE_CLOSING;
  695. } else if (ready_state == STATE_CONNECTING || ready_state == STATE_CLOSED) {
  696. ready_state = STATE_CLOSED;
  697. connection.unref();
  698. if (tcp.is_valid()) {
  699. tcp->disconnect_from_host();
  700. tcp.unref();
  701. }
  702. }
  703. in_buffer.clear();
  704. packet_buffer.resize(0);
  705. }
  706. IPAddress WSLPeer::get_connected_host() const {
  707. ERR_FAIL_COND_V(tcp.is_null(), IPAddress());
  708. return tcp->get_connected_host();
  709. }
  710. uint16_t WSLPeer::get_connected_port() const {
  711. ERR_FAIL_COND_V(tcp.is_null(), 0);
  712. return tcp->get_connected_port();
  713. }
  714. String WSLPeer::get_selected_protocol() const {
  715. return selected_protocol;
  716. }
  717. String WSLPeer::get_requested_url() const {
  718. return requested_url;
  719. }
  720. void WSLPeer::set_no_delay(bool p_enabled) {
  721. ERR_FAIL_COND(tcp.is_null());
  722. tcp->set_no_delay(p_enabled);
  723. }
  724. void WSLPeer::_clear() {
  725. // Connection info.
  726. ready_state = STATE_CLOSED;
  727. is_server = false;
  728. connection.unref();
  729. if (tcp.is_valid()) {
  730. tcp->disconnect_from_host();
  731. tcp.unref();
  732. }
  733. if (wsl_ctx) {
  734. wslay_event_context_free(wsl_ctx);
  735. wsl_ctx = nullptr;
  736. }
  737. resolver.stop();
  738. requested_url.clear();
  739. requested_host.clear();
  740. pending_request = true;
  741. handshake_buffer->clear();
  742. selected_protocol.clear();
  743. session_key.clear();
  744. // Pending packets info.
  745. was_string = 0;
  746. in_buffer.clear();
  747. packet_buffer.clear();
  748. // Close code info.
  749. close_code = -1;
  750. close_reason.clear();
  751. }
  752. WSLPeer::WSLPeer() {
  753. handshake_buffer.instantiate();
  754. }
  755. WSLPeer::~WSLPeer() {
  756. close(-1);
  757. }
  758. #endif // WEB_ENABLED