wsl_server.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /**************************************************************************/
  2. /* wsl_server.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. #ifndef JAVASCRIPT_ENABLED
  31. #include "wsl_server.h"
  32. #include "core/os/os.h"
  33. #include "core/project_settings.h"
  34. WSLServer::PendingPeer::PendingPeer() {
  35. use_ssl = false;
  36. time = 0;
  37. has_request = false;
  38. response_sent = 0;
  39. req_pos = 0;
  40. memset(req_buf, 0, sizeof(req_buf));
  41. }
  42. bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) {
  43. Vector<String> psa = String((char *)req_buf).split("\r\n");
  44. int len = psa.size();
  45. ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
  46. Vector<String> req = psa[0].split(" ", false);
  47. ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");
  48. // Wrong protocol
  49. ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");
  50. Map<String, String> headers;
  51. for (int i = 1; i < len; i++) {
  52. Vector<String> header = psa[i].split(":", false, 1);
  53. ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
  54. String name = header[0].to_lower();
  55. String value = header[1].strip_edges();
  56. if (headers.has(name)) {
  57. headers[name] += "," + value;
  58. } else {
  59. headers[name] = value;
  60. }
  61. }
  62. #define _WSL_CHECK(NAME, VALUE) \
  63. ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
  64. "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
  65. #define _WSL_CHECK_EX(NAME) \
  66. ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
  67. _WSL_CHECK("upgrade", "websocket");
  68. _WSL_CHECK("sec-websocket-version", "13");
  69. _WSL_CHECK_EX("sec-websocket-key");
  70. _WSL_CHECK_EX("connection");
  71. #undef _WSL_CHECK_EX
  72. #undef _WSL_CHECK
  73. key = headers["sec-websocket-key"];
  74. if (headers.has("sec-websocket-protocol")) {
  75. Vector<String> protos = headers["sec-websocket-protocol"].split(",");
  76. for (int i = 0; i < protos.size(); i++) {
  77. String proto = protos[i].strip_edges();
  78. // Check if we have the given protocol
  79. for (int j = 0; j < p_protocols.size(); j++) {
  80. if (proto != p_protocols[j]) {
  81. continue;
  82. }
  83. protocol = proto;
  84. break;
  85. }
  86. // Found a protocol
  87. if (protocol != "") {
  88. break;
  89. }
  90. }
  91. if (protocol == "") { // Invalid protocol(s) requested
  92. return false;
  93. }
  94. } else if (p_protocols.size() > 0) { // No protocol requested, but we need one
  95. return false;
  96. }
  97. return true;
  98. }
  99. Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, const Vector<String> &p_extra_headers) {
  100. if (OS::get_singleton()->get_ticks_msec() - time > p_timeout) {
  101. print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", p_timeout * 0.001));
  102. return ERR_TIMEOUT;
  103. }
  104. if (use_ssl) {
  105. Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL>>(connection);
  106. if (ssl.is_null()) {
  107. ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerSSL for WebSocket handshake.");
  108. }
  109. ssl->poll();
  110. if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
  111. return ERR_BUSY;
  112. } else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
  113. print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerSSL status code %d).", ssl->get_status()));
  114. return FAILED;
  115. }
  116. }
  117. if (!has_request) {
  118. int read = 0;
  119. while (true) {
  120. ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big.");
  121. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  122. if (err != OK) { // Got an error
  123. print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err));
  124. return FAILED;
  125. } else if (read != 1) { // Busy, wait next poll
  126. return ERR_BUSY;
  127. }
  128. char *r = (char *)req_buf;
  129. int l = req_pos;
  130. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  131. r[l - 3] = '\0';
  132. if (!_parse_request(p_protocols)) {
  133. return FAILED;
  134. }
  135. String s = "HTTP/1.1 101 Switching Protocols\r\n";
  136. s += "Upgrade: websocket\r\n";
  137. s += "Connection: Upgrade\r\n";
  138. s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
  139. if (protocol != "") {
  140. s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
  141. }
  142. for (int i = 0; i < p_extra_headers.size(); i++) {
  143. s += p_extra_headers[i] + "\r\n";
  144. }
  145. s += "\r\n";
  146. response = s.utf8();
  147. has_request = true;
  148. break;
  149. }
  150. req_pos += 1;
  151. }
  152. }
  153. if (has_request && response_sent < response.size() - 1) {
  154. int sent = 0;
  155. Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent);
  156. if (err != OK) {
  157. print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err));
  158. return err;
  159. }
  160. response_sent += sent;
  161. }
  162. if (response_sent < response.size() - 1) {
  163. return ERR_BUSY;
  164. }
  165. return OK;
  166. }
  167. void WSLServer::set_extra_headers(const Vector<String> &p_headers) {
  168. _extra_headers = p_headers;
  169. }
  170. Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) {
  171. ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE);
  172. _is_multiplayer = gd_mp_api;
  173. // Strip edges from protocols.
  174. _protocols.resize(p_protocols.size());
  175. String *pw = _protocols.ptrw();
  176. for (int i = 0; i < p_protocols.size(); i++) {
  177. pw[i] = p_protocols[i].strip_edges();
  178. }
  179. return _server->listen(p_port, bind_ip);
  180. }
  181. void WSLServer::poll() {
  182. List<int> remove_ids;
  183. for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
  184. Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
  185. peer->poll();
  186. if (!peer->is_connected_to_host()) {
  187. _on_disconnect(E->key(), peer->close_code != -1);
  188. remove_ids.push_back(E->key());
  189. }
  190. }
  191. for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) {
  192. _peer_map.erase(E->get());
  193. }
  194. remove_ids.clear();
  195. List<Ref<PendingPeer>> remove_peers;
  196. for (List<Ref<PendingPeer>>::Element *E = _pending.front(); E; E = E->next()) {
  197. Ref<PendingPeer> ppeer = E->get();
  198. Error err = ppeer->do_handshake(_protocols, handshake_timeout, _extra_headers);
  199. if (err == ERR_BUSY) {
  200. continue;
  201. } else if (err != OK) {
  202. remove_peers.push_back(ppeer);
  203. continue;
  204. }
  205. // Creating new peer
  206. int32_t id = _gen_unique_id();
  207. WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
  208. data->obj = this;
  209. data->conn = ppeer->connection;
  210. data->tcp = ppeer->tcp;
  211. data->is_server = true;
  212. data->id = id;
  213. Ref<WSLPeer> ws_peer = memnew(WSLPeer);
  214. ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
  215. ws_peer->set_no_delay(true);
  216. _peer_map[id] = ws_peer;
  217. remove_peers.push_back(ppeer);
  218. _on_connect(id, ppeer->protocol);
  219. }
  220. for (List<Ref<PendingPeer>>::Element *E = remove_peers.front(); E; E = E->next()) {
  221. _pending.erase(E->get());
  222. }
  223. remove_peers.clear();
  224. if (!_server->is_listening()) {
  225. return;
  226. }
  227. while (_server->is_connection_available()) {
  228. Ref<StreamPeerTCP> conn = _server->take_connection();
  229. if (is_refusing_new_connections()) {
  230. continue; // Conn will go out-of-scope and be closed.
  231. }
  232. Ref<PendingPeer> peer = memnew(PendingPeer);
  233. if (private_key.is_valid() && ssl_cert.is_valid()) {
  234. Ref<StreamPeerSSL> ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
  235. ssl->set_blocking_handshake_enabled(false);
  236. ssl->accept_stream(conn, private_key, ssl_cert, ca_chain);
  237. peer->connection = ssl;
  238. peer->use_ssl = true;
  239. } else {
  240. peer->connection = conn;
  241. }
  242. peer->tcp = conn;
  243. peer->time = OS::get_singleton()->get_ticks_msec();
  244. _pending.push_back(peer);
  245. }
  246. }
  247. bool WSLServer::is_listening() const {
  248. return _server->is_listening();
  249. }
  250. int WSLServer::get_max_packet_size() const {
  251. return (1 << _out_buf_size) - PROTO_SIZE;
  252. }
  253. void WSLServer::stop() {
  254. _server->stop();
  255. for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
  256. Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
  257. peer->close_now();
  258. }
  259. _pending.clear();
  260. _peer_map.clear();
  261. _protocols.clear();
  262. }
  263. bool WSLServer::has_peer(int p_id) const {
  264. return _peer_map.has(p_id);
  265. }
  266. Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const {
  267. ERR_FAIL_COND_V(!has_peer(p_id), nullptr);
  268. return _peer_map[p_id];
  269. }
  270. IP_Address WSLServer::get_peer_address(int p_peer_id) const {
  271. ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address());
  272. return _peer_map[p_peer_id]->get_connected_host();
  273. }
  274. int WSLServer::get_peer_port(int p_peer_id) const {
  275. ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);
  276. return _peer_map[p_peer_id]->get_connected_port();
  277. }
  278. void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
  279. ERR_FAIL_COND(!has_peer(p_peer_id));
  280. get_peer(p_peer_id)->close(p_code, p_reason);
  281. }
  282. Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
  283. ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting.");
  284. _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
  285. _in_pkt_size = nearest_shift(p_in_packets - 1);
  286. _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
  287. _out_pkt_size = nearest_shift(p_out_packets - 1);
  288. return OK;
  289. }
  290. WSLServer::WSLServer() {
  291. _in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10;
  292. _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1);
  293. _out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10;
  294. _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1);
  295. _server.instance();
  296. }
  297. WSLServer::~WSLServer() {
  298. stop();
  299. }
  300. #endif // JAVASCRIPT_ENABLED