wsl_client.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*************************************************************************/
  2. /* wsl_client.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 JAVASCRIPT_ENABLED
  31. #include "wsl_client.h"
  32. #include "core/io/ip.h"
  33. #include "core/project_settings.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. uint8_t byte = 0;
  47. int read = 0;
  48. while (true) {
  49. Error err = _connection->get_partial_data(&byte, 1, read);
  50. if (err == ERR_FILE_EOF) {
  51. // We got a disconnect.
  52. disconnect_from_host();
  53. _on_error();
  54. return;
  55. } else if (err != OK) {
  56. // Got some error.
  57. disconnect_from_host();
  58. _on_error();
  59. return;
  60. } else if (read != 1) {
  61. // Busy, wait next poll.
  62. break;
  63. }
  64. // TODO lots of allocs. Use a buffer.
  65. _response += byte;
  66. if (_response.size() > WSL_MAX_HEADER_SIZE) {
  67. // Header is too big
  68. disconnect_from_host();
  69. _on_error();
  70. ERR_EXPLAIN("Response headers too big");
  71. ERR_FAIL();
  72. }
  73. if (_response.ends_with("\r\n\r\n")) {
  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_EXPLAIN("Invalid response headers");
  80. ERR_FAIL();
  81. }
  82. // Create peer.
  83. WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
  84. data->obj = this;
  85. data->conn = _connection;
  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. _on_connect(protocol);
  90. }
  91. }
  92. }
  93. }
  94. bool WSLClient::_verify_headers(String &r_protocol) {
  95. Vector<String> psa = _response.trim_suffix("\r\n\r\n").split("\r\n");
  96. int len = psa.size();
  97. if (len < 4) {
  98. ERR_EXPLAIN("Not enough response headers.");
  99. ERR_FAIL_V(false);
  100. }
  101. Vector<String> req = psa[0].split(" ", false);
  102. if (req.size() < 2) {
  103. ERR_EXPLAIN("Invalid protocol or status code.");
  104. ERR_FAIL_V(false);
  105. }
  106. // Wrong protocol
  107. if (req[0] != "HTTP/1.1" || req[1] != "101") {
  108. ERR_EXPLAIN("Invalid protocol or status code.");
  109. ERR_FAIL_V(false);
  110. }
  111. Map<String, String> headers;
  112. for (int i = 1; i < len; i++) {
  113. Vector<String> header = psa[i].split(":", false, 1);
  114. if (header.size() != 2) {
  115. ERR_EXPLAIN("Invalid header -> " + psa[i]);
  116. ERR_FAIL_V(false);
  117. }
  118. String name = header[0].to_lower();
  119. String value = header[1].strip_edges();
  120. if (headers.has(name))
  121. headers[name] += "," + value;
  122. else
  123. headers[name] = value;
  124. }
  125. #define _WLS_EXPLAIN(NAME, VALUE) \
  126. ERR_EXPLAIN("Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'");
  127. #define _WLS_CHECK(NAME, VALUE) \
  128. _WLS_EXPLAIN(NAME, VALUE); \
  129. ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false);
  130. #define _WLS_CHECK_NC(NAME, VALUE) \
  131. _WLS_EXPLAIN(NAME, VALUE); \
  132. ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME] != VALUE, false);
  133. _WLS_CHECK("connection", "upgrade");
  134. _WLS_CHECK("upgrade", "websocket");
  135. _WLS_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key));
  136. if (_protocols.size() == 0) {
  137. // We didn't request a custom protocol
  138. ERR_FAIL_COND_V(headers.has("sec-websocket-protocol"), false);
  139. } else {
  140. ERR_FAIL_COND_V(!headers.has("sec-websocket-protocol"), false);
  141. r_protocol = headers["sec-websocket-protocol"];
  142. bool valid = false;
  143. for (int i = 0; i < _protocols.size(); i++) {
  144. if (_protocols[i] != r_protocol)
  145. continue;
  146. valid = true;
  147. break;
  148. }
  149. if (!valid)
  150. return false;
  151. }
  152. #undef _WLS_CHECK_NC
  153. #undef _WLS_CHECK
  154. #undef _WLS_EXPLAIN
  155. return true;
  156. }
  157. Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) {
  158. ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE);
  159. _peer = Ref<WSLPeer>(memnew(WSLPeer));
  160. IP_Address addr;
  161. if (!p_host.is_valid_ip_address()) {
  162. addr = IP::get_singleton()->resolve_hostname(p_host);
  163. } else {
  164. addr = p_host;
  165. }
  166. ERR_FAIL_COND_V(!addr.is_valid(), ERR_INVALID_PARAMETER);
  167. String port = "";
  168. if ((p_port != 80 && !p_ssl) || (p_port != 443 && p_ssl)) {
  169. port = ":" + itos(p_port);
  170. }
  171. Error err = _tcp->connect_to_host(addr, p_port);
  172. if (err != OK) {
  173. _on_error();
  174. _tcp->disconnect_from_host();
  175. return err;
  176. }
  177. _connection = _tcp;
  178. _use_ssl = p_ssl;
  179. _host = p_host;
  180. _protocols = p_protocols;
  181. _key = WSLPeer::generate_key();
  182. // TODO custom extra headers (allow overriding this too?)
  183. String request = "GET " + p_path + " HTTP/1.1\r\n";
  184. request += "Host: " + p_host + port + "\r\n";
  185. request += "Upgrade: websocket\r\n";
  186. request += "Connection: Upgrade\r\n";
  187. request += "Sec-WebSocket-Key: " + _key + "\r\n";
  188. request += "Sec-WebSocket-Version: 13\r\n";
  189. if (p_protocols.size() > 0) {
  190. request += "Sec-WebSocket-Protocol: ";
  191. for (int i = 0; i < p_protocols.size(); i++) {
  192. if (i != 0)
  193. request += ",";
  194. request += p_protocols[i];
  195. }
  196. request += "\r\n";
  197. }
  198. request += "\r\n";
  199. _request = request.utf8();
  200. return OK;
  201. }
  202. int WSLClient::get_max_packet_size() const {
  203. return (1 << _out_buf_size) - PROTO_SIZE;
  204. }
  205. void WSLClient::poll() {
  206. if (_peer->is_connected_to_host()) {
  207. _peer->poll();
  208. if (!_peer->is_connected_to_host()) {
  209. _on_disconnect(_peer->close_code != -1);
  210. disconnect_from_host();
  211. }
  212. return;
  213. }
  214. if (_connection.is_null())
  215. return; // Not connected.
  216. switch (_tcp->get_status()) {
  217. case StreamPeerTCP::STATUS_NONE:
  218. // Clean close
  219. _on_error();
  220. disconnect_from_host();
  221. break;
  222. case StreamPeerTCP::STATUS_CONNECTED: {
  223. Ref<StreamPeerSSL> ssl;
  224. if (_use_ssl) {
  225. if (_connection == _tcp) {
  226. // Start SSL handshake
  227. ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
  228. ERR_EXPLAIN("SSL is not available in this build");
  229. ERR_FAIL_COND(ssl.is_null());
  230. ssl->set_blocking_handshake_enabled(false);
  231. if (ssl->connect_to_stream(_tcp, verify_ssl, _host) != OK) {
  232. _on_error();
  233. disconnect_from_host();
  234. return;
  235. }
  236. _connection = ssl;
  237. } else {
  238. ssl = static_cast<Ref<StreamPeerSSL> >(_connection);
  239. ERR_FAIL_COND(ssl.is_null()); // Bug?
  240. ssl->poll();
  241. }
  242. if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING)
  243. return; // Need more polling.
  244. else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
  245. _on_error();
  246. disconnect_from_host();
  247. return; // Error.
  248. }
  249. }
  250. // Do websocket handshake.
  251. _do_handshake();
  252. } break;
  253. case StreamPeerTCP::STATUS_ERROR:
  254. _on_error();
  255. disconnect_from_host();
  256. break;
  257. case StreamPeerTCP::STATUS_CONNECTING:
  258. break; // Wait for connection
  259. }
  260. }
  261. Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const {
  262. ERR_FAIL_COND_V(p_peer_id != 1, NULL);
  263. return _peer;
  264. }
  265. NetworkedMultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const {
  266. if (_peer->is_connected_to_host())
  267. return CONNECTION_CONNECTED;
  268. if (_tcp->is_connected_to_host())
  269. return CONNECTION_CONNECTING;
  270. return CONNECTION_DISCONNECTED;
  271. }
  272. void WSLClient::disconnect_from_host(int p_code, String p_reason) {
  273. _peer->close(p_code, p_reason);
  274. _connection = Ref<StreamPeer>(NULL);
  275. _tcp = Ref<StreamPeerTCP>(memnew(StreamPeerTCP));
  276. _request = "";
  277. _response = "";
  278. _key = "";
  279. _host = "";
  280. _use_ssl = false;
  281. _requested = 0;
  282. }
  283. IP_Address WSLClient::get_connected_host() const {
  284. return IP_Address();
  285. }
  286. uint16_t WSLClient::get_connected_port() const {
  287. return 1025;
  288. }
  289. Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
  290. ERR_EXPLAIN("Buffers sizes can only be set before listening or connecting");
  291. ERR_FAIL_COND_V(_ctx != NULL, FAILED);
  292. _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
  293. _in_pkt_size = nearest_shift(p_in_packets - 1);
  294. _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
  295. _out_pkt_size = nearest_shift(p_out_packets - 1);
  296. return OK;
  297. }
  298. WSLClient::WSLClient() {
  299. _in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10;
  300. _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1);
  301. _out_buf_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_BUF) - 1) + 10;
  302. _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_PKT) - 1);
  303. _ctx = NULL;
  304. _peer.instance();
  305. _tcp.instance();
  306. _requested = 0;
  307. }
  308. WSLClient::~WSLClient() {
  309. _peer->close_now();
  310. _peer->invalidate();
  311. disconnect_from_host();
  312. }
  313. #endif // JAVASCRIPT_ENABLED