wsl_server.cpp 11 KB

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