wsl_client.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*************************************************************************/
  2. /* wsl_client.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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. #ifndef WEB_ENABLED
  31. #include "wsl_client.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/io/ip.h"
  34. void WSLClient::_do_handshake() {
  35. if (_requested < _request.size() - 1) {
  36. int sent = 0;
  37. Error err = _connection->put_partial_data(((const uint8_t *)_request.get_data() + _requested), _request.size() - _requested - 1, sent);
  38. // Sending handshake failed
  39. if (err != OK) {
  40. disconnect_from_host();
  41. _on_error();
  42. return;
  43. }
  44. _requested += sent;
  45. } else {
  46. int read = 0;
  47. while (true) {
  48. if (_resp_pos >= WSL_MAX_HEADER_SIZE) {
  49. // Header is too big
  50. disconnect_from_host();
  51. _on_error();
  52. ERR_FAIL_MSG("Response headers too big.");
  53. }
  54. Error err = _connection->get_partial_data(&_resp_buf[_resp_pos], 1, read);
  55. if (err == ERR_FILE_EOF) {
  56. // We got a disconnect.
  57. disconnect_from_host();
  58. _on_error();
  59. return;
  60. } else if (err != OK) {
  61. // Got some error.
  62. disconnect_from_host();
  63. _on_error();
  64. return;
  65. } else if (read != 1) {
  66. // Busy, wait next poll.
  67. break;
  68. }
  69. // Check "\r\n\r\n" header terminator
  70. char *r = (char *)_resp_buf;
  71. int l = _resp_pos;
  72. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  73. r[l - 3] = '\0';
  74. String protocol;
  75. // Response is over, verify headers and create peer.
  76. if (!_verify_headers(protocol)) {
  77. disconnect_from_host();
  78. _on_error();
  79. ERR_FAIL_MSG("Invalid response headers.");
  80. }
  81. // Create peer.
  82. WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
  83. data->obj = this;
  84. data->conn = _connection;
  85. data->tcp = _tcp;
  86. data->is_server = false;
  87. data->id = 1;
  88. _peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
  89. _peer->set_no_delay(true);
  90. _status = CONNECTION_CONNECTED;
  91. _on_connect(protocol);
  92. break;
  93. }
  94. _resp_pos += 1;
  95. }
  96. }
  97. }
  98. bool WSLClient::_verify_headers(String &r_protocol) {
  99. String s = (char *)_resp_buf;
  100. Vector<String> psa = s.split("\r\n");
  101. int len = psa.size();
  102. ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers. Got: " + itos(len) + ", expected >= 4.");
  103. Vector<String> req = psa[0].split(" ", false);
  104. ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code. Got '" + psa[0] + "', expected 'HTTP/1.1 101'.");
  105. // Wrong protocol
  106. ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1", false, "Invalid protocol. Got: '" + req[0] + "', expected 'HTTP/1.1'.");
  107. ERR_FAIL_COND_V_MSG(req[1] != "101", false, "Invalid status code. Got: '" + req[1] + "', expected '101'.");
  108. HashMap<String, String> headers;
  109. for (int i = 1; i < len; i++) {
  110. Vector<String> header = psa[i].split(":", false, 1);
  111. ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + ".");
  112. String name = header[0].to_lower();
  113. String value = header[1].strip_edges();
  114. if (headers.has(name)) {
  115. headers[name] += "," + value;
  116. } else {
  117. headers[name] = value;
  118. }
  119. }
  120. #define WSL_CHECK(NAME, VALUE) \
  121. ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
  122. "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
  123. #define WSL_CHECK_NC(NAME, VALUE) \
  124. ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \
  125. "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
  126. WSL_CHECK("connection", "upgrade");
  127. WSL_CHECK("upgrade", "websocket");
  128. WSL_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key));
  129. #undef WSL_CHECK_NC
  130. #undef WSL_CHECK
  131. if (_protocols.size() == 0) {
  132. // We didn't request a custom protocol
  133. ERR_FAIL_COND_V_MSG(headers.has("sec-websocket-protocol"), false, "Received unrequested sub-protocol -> " + headers["sec-websocket-protocol"]);
  134. } else {
  135. // We requested at least one custom protocol but didn't receive one
  136. ERR_FAIL_COND_V_MSG(!headers.has("sec-websocket-protocol"), false, "Requested sub-protocol(s) but received none.");
  137. // Check received sub-protocol was one of those requested.
  138. r_protocol = headers["sec-websocket-protocol"];
  139. bool valid = false;
  140. for (int i = 0; i < _protocols.size(); i++) {
  141. if (_protocols[i] != r_protocol) {
  142. continue;
  143. }
  144. valid = true;
  145. break;
  146. }
  147. if (!valid) {
  148. ERR_FAIL_V_MSG(false, "Received unrequested sub-protocol -> " + r_protocol);
  149. return false;
  150. }
  151. }
  152. return true;
  153. }
  154. Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocols, const Vector<String> p_custom_headers) {
  155. ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE);
  156. ERR_FAIL_COND_V(p_path.is_empty(), ERR_INVALID_PARAMETER);
  157. _peer = Ref<WSLPeer>(memnew(WSLPeer));
  158. if (p_host.is_valid_ip_address()) {
  159. _ip_candidates.push_back(IPAddress(p_host));
  160. } else {
  161. // Queue hostname for resolution.
  162. _resolver_id = IP::get_singleton()->resolve_hostname_queue_item(p_host);
  163. ERR_FAIL_COND_V(_resolver_id == IP::RESOLVER_INVALID_ID, ERR_INVALID_PARAMETER);
  164. // Check if it was found in cache.
  165. IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(_resolver_id);
  166. if (ip_status == IP::RESOLVER_STATUS_DONE) {
  167. _ip_candidates = IP::get_singleton()->get_resolve_item_addresses(_resolver_id);
  168. IP::get_singleton()->erase_resolve_item(_resolver_id);
  169. _resolver_id = IP::RESOLVER_INVALID_ID;
  170. }
  171. }
  172. // We assume OK while hostname resolution is pending.
  173. Error err = _resolver_id != IP::RESOLVER_INVALID_ID ? OK : FAILED;
  174. while (_ip_candidates.size()) {
  175. err = _tcp->connect_to_host(_ip_candidates.pop_front(), p_port);
  176. if (err == OK) {
  177. break;
  178. }
  179. }
  180. if (err != OK) {
  181. _tcp->disconnect_from_host();
  182. _on_error();
  183. return err;
  184. }
  185. _connection = _tcp;
  186. _use_ssl = p_ssl;
  187. _host = p_host;
  188. _port = p_port;
  189. // Strip edges from protocols.
  190. _protocols.resize(p_protocols.size());
  191. String *pw = _protocols.ptrw();
  192. for (int i = 0; i < p_protocols.size(); i++) {
  193. pw[i] = p_protocols[i].strip_edges();
  194. }
  195. _key = WSLPeer::generate_key();
  196. String request = "GET " + p_path + " HTTP/1.1\r\n";
  197. String port = "";
  198. if ((p_port != 80 && !p_ssl) || (p_port != 443 && p_ssl)) {
  199. port = ":" + itos(p_port);
  200. }
  201. request += "Host: " + p_host + port + "\r\n";
  202. request += "Upgrade: websocket\r\n";
  203. request += "Connection: Upgrade\r\n";
  204. request += "Sec-WebSocket-Key: " + _key + "\r\n";
  205. request += "Sec-WebSocket-Version: 13\r\n";
  206. if (p_protocols.size() > 0) {
  207. request += "Sec-WebSocket-Protocol: ";
  208. for (int i = 0; i < p_protocols.size(); i++) {
  209. if (i != 0) {
  210. request += ",";
  211. }
  212. request += p_protocols[i];
  213. }
  214. request += "\r\n";
  215. }
  216. for (int i = 0; i < p_custom_headers.size(); i++) {
  217. request += p_custom_headers[i] + "\r\n";
  218. }
  219. request += "\r\n";
  220. _request = request.utf8();
  221. _status = CONNECTION_CONNECTING;
  222. return OK;
  223. }
  224. int WSLClient::get_max_packet_size() const {
  225. return (1 << _out_buf_size) - PROTO_SIZE;
  226. }
  227. void WSLClient::poll() {
  228. if (_resolver_id != IP::RESOLVER_INVALID_ID) {
  229. IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(_resolver_id);
  230. if (ip_status == IP::RESOLVER_STATUS_WAITING) {
  231. return;
  232. }
  233. // Anything else is either a candidate or a failure.
  234. Error err = FAILED;
  235. if (ip_status == IP::RESOLVER_STATUS_DONE) {
  236. _ip_candidates = IP::get_singleton()->get_resolve_item_addresses(_resolver_id);
  237. while (_ip_candidates.size()) {
  238. err = _tcp->connect_to_host(_ip_candidates.pop_front(), _port);
  239. if (err == OK) {
  240. break;
  241. }
  242. }
  243. }
  244. IP::get_singleton()->erase_resolve_item(_resolver_id);
  245. _resolver_id = IP::RESOLVER_INVALID_ID;
  246. if (err != OK) {
  247. disconnect_from_host();
  248. _on_error();
  249. return;
  250. }
  251. }
  252. if (_peer->is_connected_to_host()) {
  253. _peer->poll();
  254. if (!_peer->is_connected_to_host()) {
  255. disconnect_from_host();
  256. _on_disconnect(_peer->close_code != -1);
  257. }
  258. return;
  259. }
  260. if (_connection.is_null()) {
  261. return; // Not connected.
  262. }
  263. _tcp->poll();
  264. switch (_tcp->get_status()) {
  265. case StreamPeerTCP::STATUS_NONE:
  266. // Clean close
  267. disconnect_from_host();
  268. _on_error();
  269. break;
  270. case StreamPeerTCP::STATUS_CONNECTED: {
  271. _ip_candidates.clear();
  272. Ref<StreamPeerTLS> ssl;
  273. if (_use_ssl) {
  274. if (_connection == _tcp) {
  275. // Start SSL handshake
  276. ssl = Ref<StreamPeerTLS>(StreamPeerTLS::create());
  277. ERR_FAIL_COND_MSG(ssl.is_null(), "SSL is not available in this build.");
  278. ssl->set_blocking_handshake_enabled(false);
  279. if (ssl->connect_to_stream(_tcp, verify_ssl, _host, ssl_cert) != OK) {
  280. disconnect_from_host();
  281. _on_error();
  282. return;
  283. }
  284. _connection = ssl;
  285. } else {
  286. ssl = static_cast<Ref<StreamPeerTLS>>(_connection);
  287. ERR_FAIL_COND(ssl.is_null()); // Bug?
  288. ssl->poll();
  289. }
  290. if (ssl->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
  291. return; // Need more polling.
  292. } else if (ssl->get_status() != StreamPeerTLS::STATUS_CONNECTED) {
  293. disconnect_from_host();
  294. _on_error();
  295. return; // Error.
  296. }
  297. }
  298. // Do websocket handshake.
  299. _do_handshake();
  300. } break;
  301. case StreamPeerTCP::STATUS_ERROR:
  302. while (_ip_candidates.size() > 0) {
  303. _tcp->disconnect_from_host();
  304. if (_tcp->connect_to_host(_ip_candidates.pop_front(), _port) == OK) {
  305. return;
  306. }
  307. }
  308. disconnect_from_host();
  309. _on_error();
  310. break;
  311. case StreamPeerTCP::STATUS_CONNECTING:
  312. break; // Wait for connection
  313. }
  314. }
  315. Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const {
  316. ERR_FAIL_COND_V(p_peer_id != 1, nullptr);
  317. return _peer;
  318. }
  319. MultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const {
  320. // This is surprising, but keeps the current behaviour to allow clean close requests.
  321. // TODO Refactor WebSocket and split Client/Server/Multiplayer like done in other peers.
  322. if (_peer->is_connected_to_host()) {
  323. return CONNECTION_CONNECTED;
  324. }
  325. return _status;
  326. }
  327. void WSLClient::disconnect_from_host(int p_code, String p_reason) {
  328. _peer->close(p_code, p_reason);
  329. _connection = Ref<StreamPeer>(nullptr);
  330. _tcp = Ref<StreamPeerTCP>(memnew(StreamPeerTCP));
  331. _status = CONNECTION_DISCONNECTED;
  332. _key = "";
  333. _host = "";
  334. _protocols.clear();
  335. _use_ssl = false;
  336. _request = "";
  337. _requested = 0;
  338. memset(_resp_buf, 0, sizeof(_resp_buf));
  339. _resp_pos = 0;
  340. if (_resolver_id != IP::RESOLVER_INVALID_ID) {
  341. IP::get_singleton()->erase_resolve_item(_resolver_id);
  342. _resolver_id = IP::RESOLVER_INVALID_ID;
  343. }
  344. _ip_candidates.clear();
  345. }
  346. IPAddress WSLClient::get_connected_host() const {
  347. ERR_FAIL_COND_V(!_peer->is_connected_to_host(), IPAddress());
  348. return _peer->get_connected_host();
  349. }
  350. uint16_t WSLClient::get_connected_port() const {
  351. ERR_FAIL_COND_V(!_peer->is_connected_to_host(), 0);
  352. return _peer->get_connected_port();
  353. }
  354. Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
  355. ERR_FAIL_COND_V_MSG(_connection.is_valid(), FAILED, "Buffers sizes can only be set before listening or connecting.");
  356. _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
  357. _in_pkt_size = nearest_shift(p_in_packets - 1);
  358. _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
  359. _out_pkt_size = nearest_shift(p_out_packets - 1);
  360. return OK;
  361. }
  362. WSLClient::WSLClient() {
  363. _peer.instantiate();
  364. _tcp.instantiate();
  365. disconnect_from_host();
  366. }
  367. WSLClient::~WSLClient() {
  368. _peer->close_now();
  369. _peer->invalidate();
  370. disconnect_from_host();
  371. }
  372. #endif // WEB_ENABLED