websocket_multiplayer_peer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*************************************************************************/
  2. /* websocket_multiplayer_peer.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. #include "websocket_multiplayer_peer.h"
  31. #include "core/os/os.h"
  32. WebSocketMultiplayerPeer::WebSocketMultiplayerPeer() {
  33. peer_config = Ref<WebSocketPeer>(WebSocketPeer::create());
  34. }
  35. WebSocketMultiplayerPeer::~WebSocketMultiplayerPeer() {
  36. _clear();
  37. }
  38. Ref<WebSocketPeer> WebSocketMultiplayerPeer::_create_peer() {
  39. Ref<WebSocketPeer> peer = Ref<WebSocketPeer>(WebSocketPeer::create());
  40. peer->set_supported_protocols(get_supported_protocols());
  41. peer->set_handshake_headers(get_handshake_headers());
  42. peer->set_inbound_buffer_size(get_inbound_buffer_size());
  43. peer->set_outbound_buffer_size(get_outbound_buffer_size());
  44. peer->set_max_queued_packets(get_max_queued_packets());
  45. return peer;
  46. }
  47. void WebSocketMultiplayerPeer::_clear() {
  48. connection_status = CONNECTION_DISCONNECTED;
  49. unique_id = 0;
  50. peers_map.clear();
  51. use_tls = false;
  52. tcp_server.unref();
  53. pending_peers.clear();
  54. tls_certificate.unref();
  55. tls_key.unref();
  56. if (current_packet.data != nullptr) {
  57. memfree(current_packet.data);
  58. current_packet.data = nullptr;
  59. }
  60. for (Packet &E : incoming_packets) {
  61. memfree(E.data);
  62. E.data = nullptr;
  63. }
  64. incoming_packets.clear();
  65. }
  66. void WebSocketMultiplayerPeer::_bind_methods() {
  67. ClassDB::bind_method(D_METHOD("create_client", "url", "verify_tls", "tls_certificate"), &WebSocketMultiplayerPeer::create_client, DEFVAL(true), DEFVAL(Ref<X509Certificate>()));
  68. ClassDB::bind_method(D_METHOD("create_server", "port", "bind_address", "tls_key", "tls_certificate"), &WebSocketMultiplayerPeer::create_server, DEFVAL("*"), DEFVAL(Ref<CryptoKey>()), DEFVAL(Ref<X509Certificate>()));
  69. ClassDB::bind_method(D_METHOD("close"), &WebSocketMultiplayerPeer::close);
  70. ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebSocketMultiplayerPeer::get_peer);
  71. ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &WebSocketMultiplayerPeer::get_peer_address);
  72. ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &WebSocketMultiplayerPeer::get_peer_port);
  73. ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "code", "reason"), &WebSocketMultiplayerPeer::disconnect_peer, DEFVAL(1000), DEFVAL(""));
  74. ClassDB::bind_method(D_METHOD("get_supported_protocols"), &WebSocketMultiplayerPeer::get_supported_protocols);
  75. ClassDB::bind_method(D_METHOD("set_supported_protocols", "protocols"), &WebSocketMultiplayerPeer::set_supported_protocols);
  76. ClassDB::bind_method(D_METHOD("get_handshake_headers"), &WebSocketMultiplayerPeer::get_handshake_headers);
  77. ClassDB::bind_method(D_METHOD("set_handshake_headers", "protocols"), &WebSocketMultiplayerPeer::set_handshake_headers);
  78. ClassDB::bind_method(D_METHOD("get_inbound_buffer_size"), &WebSocketMultiplayerPeer::get_inbound_buffer_size);
  79. ClassDB::bind_method(D_METHOD("set_inbound_buffer_size", "buffer_size"), &WebSocketMultiplayerPeer::set_inbound_buffer_size);
  80. ClassDB::bind_method(D_METHOD("get_outbound_buffer_size"), &WebSocketMultiplayerPeer::get_outbound_buffer_size);
  81. ClassDB::bind_method(D_METHOD("set_outbound_buffer_size", "buffer_size"), &WebSocketMultiplayerPeer::set_outbound_buffer_size);
  82. ClassDB::bind_method(D_METHOD("get_handshake_timeout"), &WebSocketMultiplayerPeer::get_handshake_timeout);
  83. ClassDB::bind_method(D_METHOD("set_handshake_timeout", "timeout"), &WebSocketMultiplayerPeer::set_handshake_timeout);
  84. ClassDB::bind_method(D_METHOD("set_max_queued_packets", "max_queued_packets"), &WebSocketMultiplayerPeer::set_max_queued_packets);
  85. ClassDB::bind_method(D_METHOD("get_max_queued_packets"), &WebSocketMultiplayerPeer::get_max_queued_packets);
  86. ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "supported_protocols"), "set_supported_protocols", "get_supported_protocols");
  87. ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "handshake_headers"), "set_handshake_headers", "get_handshake_headers");
  88. ADD_PROPERTY(PropertyInfo(Variant::INT, "inbound_buffer_size"), "set_inbound_buffer_size", "get_inbound_buffer_size");
  89. ADD_PROPERTY(PropertyInfo(Variant::INT, "outbound_buffer_size"), "set_outbound_buffer_size", "get_outbound_buffer_size");
  90. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "handshake_timeout"), "set_handshake_timeout", "get_handshake_timeout");
  91. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_queued_packets"), "set_max_queued_packets", "get_max_queued_packets");
  92. }
  93. //
  94. // PacketPeer
  95. //
  96. int WebSocketMultiplayerPeer::get_available_packet_count() const {
  97. return incoming_packets.size();
  98. }
  99. Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  100. ERR_FAIL_COND_V(get_connection_status() != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  101. r_buffer_size = 0;
  102. if (current_packet.data != nullptr) {
  103. memfree(current_packet.data);
  104. current_packet.data = nullptr;
  105. }
  106. ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE);
  107. current_packet = incoming_packets.front()->get();
  108. incoming_packets.pop_front();
  109. *r_buffer = current_packet.data;
  110. r_buffer_size = current_packet.size;
  111. return OK;
  112. }
  113. Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  114. ERR_FAIL_COND_V(get_connection_status() != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  115. if (is_server()) {
  116. if (target_peer > 0) {
  117. ERR_FAIL_COND_V_MSG(!peers_map.has(target_peer), ERR_INVALID_PARAMETER, "Peer not found: " + itos(target_peer));
  118. get_peer(target_peer)->put_packet(p_buffer, p_buffer_size);
  119. } else {
  120. for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
  121. if (target_peer && -target_peer == E.key) {
  122. continue; // Excluded.
  123. }
  124. E.value->put_packet(p_buffer, p_buffer_size);
  125. }
  126. }
  127. return OK;
  128. } else {
  129. return get_peer(1)->put_packet(p_buffer, p_buffer_size);
  130. }
  131. }
  132. //
  133. // MultiplayerPeer
  134. //
  135. void WebSocketMultiplayerPeer::set_target_peer(int p_target_peer) {
  136. target_peer = p_target_peer;
  137. }
  138. int WebSocketMultiplayerPeer::get_packet_peer() const {
  139. ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
  140. return incoming_packets.front()->get().source;
  141. }
  142. int WebSocketMultiplayerPeer::get_unique_id() const {
  143. return unique_id;
  144. }
  145. int WebSocketMultiplayerPeer::get_max_packet_size() const {
  146. return get_outbound_buffer_size() - PROTO_SIZE;
  147. }
  148. Error WebSocketMultiplayerPeer::create_server(int p_port, IPAddress p_bind_ip, Ref<CryptoKey> p_tls_key, Ref<X509Certificate> p_tls_certificate) {
  149. ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE);
  150. _clear();
  151. tcp_server.instantiate();
  152. Error err = tcp_server->listen(p_port, p_bind_ip);
  153. if (err != OK) {
  154. tcp_server.unref();
  155. return err;
  156. }
  157. unique_id = 1;
  158. connection_status = CONNECTION_CONNECTED;
  159. // TLS config
  160. tls_key = p_tls_key;
  161. tls_certificate = p_tls_certificate;
  162. if (tls_key.is_valid() && tls_certificate.is_valid()) {
  163. use_tls = true;
  164. }
  165. return OK;
  166. }
  167. Error WebSocketMultiplayerPeer::create_client(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) {
  168. ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE);
  169. _clear();
  170. Ref<WebSocketPeer> peer = _create_peer();
  171. Error err = peer->connect_to_url(p_url, p_verify_tls, p_tls_certificate);
  172. if (err != OK) {
  173. return err;
  174. }
  175. PendingPeer pending;
  176. pending.time = OS::get_singleton()->get_ticks_msec();
  177. pending_peers[1] = pending;
  178. peers_map[1] = peer;
  179. connection_status = CONNECTION_CONNECTING;
  180. return OK;
  181. }
  182. bool WebSocketMultiplayerPeer::is_server() const {
  183. return tcp_server.is_valid();
  184. }
  185. void WebSocketMultiplayerPeer::_poll_client() {
  186. ERR_FAIL_COND(connection_status == CONNECTION_DISCONNECTED); // Bug.
  187. ERR_FAIL_COND(!peers_map.has(1) || peers_map[1].is_null()); // Bug.
  188. Ref<WebSocketPeer> peer = peers_map[1];
  189. peer->poll(); // Update state and fetch packets.
  190. WebSocketPeer::State ready_state = peer->get_ready_state();
  191. if (ready_state == WebSocketPeer::STATE_OPEN) {
  192. if (connection_status == CONNECTION_CONNECTING) {
  193. if (peer->get_available_packet_count() > 0) {
  194. const uint8_t *in_buffer;
  195. int size = 0;
  196. Error err = peer->get_packet(&in_buffer, size);
  197. if (err != OK || size != 4) {
  198. peer->close(); // Will cause connection error on next poll.
  199. ERR_FAIL_MSG("Invalid ID received from server");
  200. }
  201. unique_id = *((int32_t *)in_buffer);
  202. if (unique_id < 2) {
  203. peer->close(); // Will cause connection error on next poll.
  204. ERR_FAIL_MSG("Invalid ID received from server");
  205. }
  206. connection_status = CONNECTION_CONNECTED;
  207. emit_signal("peer_connected", 1);
  208. emit_signal("connection_succeeded");
  209. } else {
  210. return; // Still waiting for an ID.
  211. }
  212. }
  213. int pkts = peer->get_available_packet_count();
  214. while (pkts > 0 && peer->get_ready_state() == WebSocketPeer::STATE_OPEN) {
  215. const uint8_t *in_buffer;
  216. int size = 0;
  217. Error err = peer->get_packet(&in_buffer, size);
  218. ERR_FAIL_COND(err != OK);
  219. ERR_FAIL_COND(size <= 0);
  220. Packet packet;
  221. packet.data = (uint8_t *)memalloc(size);
  222. memcpy(packet.data, in_buffer, size);
  223. packet.size = size;
  224. packet.source = 1;
  225. incoming_packets.push_back(packet);
  226. pkts--;
  227. }
  228. } else if (peer->get_ready_state() == WebSocketPeer::STATE_CLOSED) {
  229. if (connection_status == CONNECTION_CONNECTED) {
  230. emit_signal(SNAME("server_disconnected"));
  231. } else {
  232. emit_signal(SNAME("connection_failed"));
  233. }
  234. _clear();
  235. return;
  236. }
  237. if (connection_status == CONNECTION_CONNECTING) {
  238. // Still connecting
  239. ERR_FAIL_COND(!pending_peers.has(1)); // Bug.
  240. if (OS::get_singleton()->get_ticks_msec() - pending_peers[1].time > handshake_timeout) {
  241. print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001));
  242. emit_signal(SNAME("connection_failed"));
  243. _clear();
  244. return;
  245. }
  246. }
  247. }
  248. void WebSocketMultiplayerPeer::_poll_server() {
  249. ERR_FAIL_COND(connection_status != CONNECTION_CONNECTED); // Bug.
  250. ERR_FAIL_COND(tcp_server.is_null() || !tcp_server->is_listening()); // Bug.
  251. // Accept new connections.
  252. if (!is_refusing_new_connections() && tcp_server->is_connection_available()) {
  253. PendingPeer peer;
  254. peer.time = OS::get_singleton()->get_ticks_msec();
  255. peer.tcp = tcp_server->take_connection();
  256. peer.connection = peer.tcp;
  257. pending_peers[generate_unique_id()] = peer;
  258. }
  259. // Process pending peers.
  260. HashSet<int> to_remove;
  261. for (KeyValue<int, PendingPeer> &E : pending_peers) {
  262. PendingPeer &peer = E.value;
  263. int id = E.key;
  264. if (OS::get_singleton()->get_ticks_msec() - peer.time > handshake_timeout) {
  265. print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001));
  266. to_remove.insert(id);
  267. continue;
  268. }
  269. if (peer.ws.is_valid()) {
  270. peer.ws->poll();
  271. WebSocketPeer::State state = peer.ws->get_ready_state();
  272. if (state == WebSocketPeer::STATE_OPEN) {
  273. // Connected.
  274. to_remove.insert(id);
  275. if (is_refusing_new_connections()) {
  276. // The user does not want new connections, dropping it.
  277. continue;
  278. }
  279. int32_t peer_id = id;
  280. Error err = peer.ws->put_packet((const uint8_t *)&peer_id, sizeof(peer_id));
  281. if (err == OK) {
  282. peers_map[id] = peer.ws;
  283. emit_signal("peer_connected", id);
  284. } else {
  285. ERR_PRINT("Failed to send ID to newly connected peer.");
  286. }
  287. continue;
  288. } else if (state == WebSocketPeer::STATE_CONNECTING) {
  289. continue; // Still connecting.
  290. }
  291. to_remove.insert(id); // Error.
  292. continue;
  293. }
  294. if (peer.tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  295. to_remove.insert(id); // Error.
  296. continue;
  297. }
  298. if (!use_tls) {
  299. peer.ws = _create_peer();
  300. peer.ws->accept_stream(peer.tcp);
  301. continue;
  302. } else {
  303. if (peer.connection == peer.tcp) {
  304. Ref<StreamPeerTLS> tls = Ref<StreamPeerTLS>(StreamPeerTLS::create());
  305. Error err = tls->accept_stream(peer.tcp, tls_key, tls_certificate);
  306. if (err != OK) {
  307. to_remove.insert(id);
  308. continue;
  309. }
  310. }
  311. Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(peer.connection);
  312. tls->poll();
  313. if (tls->get_status() == StreamPeerTLS::STATUS_CONNECTED) {
  314. peer.ws = _create_peer();
  315. peer.ws->accept_stream(peer.connection);
  316. continue;
  317. } else if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
  318. // Still connecting.
  319. continue;
  320. } else {
  321. // Error
  322. to_remove.insert(id);
  323. }
  324. }
  325. }
  326. // Remove disconnected pending peers.
  327. for (const int &pid : to_remove) {
  328. pending_peers.erase(pid);
  329. }
  330. to_remove.clear();
  331. // Process connected peers.
  332. for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
  333. Ref<WebSocketPeer> ws = E.value;
  334. int id = E.key;
  335. ws->poll();
  336. if (ws->get_ready_state() != WebSocketPeer::STATE_OPEN) {
  337. to_remove.insert(id); // Disconnected.
  338. continue;
  339. }
  340. // Fetch packets
  341. int pkts = ws->get_available_packet_count();
  342. while (pkts > 0 && ws->get_ready_state() == WebSocketPeer::STATE_OPEN) {
  343. const uint8_t *in_buffer;
  344. int size = 0;
  345. Error err = ws->get_packet(&in_buffer, size);
  346. if (err != OK || size <= 0) {
  347. break;
  348. }
  349. Packet packet;
  350. packet.data = (uint8_t *)memalloc(size);
  351. memcpy(packet.data, in_buffer, size);
  352. packet.size = size;
  353. packet.source = E.key;
  354. incoming_packets.push_back(packet);
  355. pkts--;
  356. }
  357. }
  358. // Remove disconnected peers.
  359. for (const int &pid : to_remove) {
  360. emit_signal(SNAME("peer_disconnected"), pid);
  361. peers_map.erase(pid);
  362. }
  363. }
  364. void WebSocketMultiplayerPeer::poll() {
  365. if (connection_status == CONNECTION_DISCONNECTED) {
  366. return;
  367. }
  368. if (is_server()) {
  369. _poll_server();
  370. } else {
  371. _poll_client();
  372. }
  373. }
  374. MultiplayerPeer::ConnectionStatus WebSocketMultiplayerPeer::get_connection_status() const {
  375. return connection_status;
  376. }
  377. Ref<WebSocketPeer> WebSocketMultiplayerPeer::get_peer(int p_id) const {
  378. ERR_FAIL_COND_V(!peers_map.has(p_id), Ref<WebSocketPeer>());
  379. return peers_map[p_id];
  380. }
  381. void WebSocketMultiplayerPeer::set_supported_protocols(const Vector<String> &p_protocols) {
  382. peer_config->set_supported_protocols(p_protocols);
  383. }
  384. Vector<String> WebSocketMultiplayerPeer::get_supported_protocols() const {
  385. return peer_config->get_supported_protocols();
  386. }
  387. void WebSocketMultiplayerPeer::set_handshake_headers(const Vector<String> &p_headers) {
  388. peer_config->set_handshake_headers(p_headers);
  389. }
  390. Vector<String> WebSocketMultiplayerPeer::get_handshake_headers() const {
  391. return peer_config->get_handshake_headers();
  392. }
  393. void WebSocketMultiplayerPeer::set_outbound_buffer_size(int p_buffer_size) {
  394. peer_config->set_outbound_buffer_size(p_buffer_size);
  395. }
  396. int WebSocketMultiplayerPeer::get_outbound_buffer_size() const {
  397. return peer_config->get_outbound_buffer_size();
  398. }
  399. void WebSocketMultiplayerPeer::set_inbound_buffer_size(int p_buffer_size) {
  400. peer_config->set_inbound_buffer_size(p_buffer_size);
  401. }
  402. int WebSocketMultiplayerPeer::get_inbound_buffer_size() const {
  403. return peer_config->get_inbound_buffer_size();
  404. }
  405. void WebSocketMultiplayerPeer::set_max_queued_packets(int p_max_queued_packets) {
  406. peer_config->set_max_queued_packets(p_max_queued_packets);
  407. }
  408. int WebSocketMultiplayerPeer::get_max_queued_packets() const {
  409. return peer_config->get_max_queued_packets();
  410. }
  411. float WebSocketMultiplayerPeer::get_handshake_timeout() const {
  412. return handshake_timeout / 1000.0;
  413. }
  414. void WebSocketMultiplayerPeer::set_handshake_timeout(float p_timeout) {
  415. ERR_FAIL_COND(p_timeout <= 0.0);
  416. handshake_timeout = p_timeout * 1000;
  417. }
  418. IPAddress WebSocketMultiplayerPeer::get_peer_address(int p_peer_id) const {
  419. ERR_FAIL_COND_V(!peers_map.has(p_peer_id), IPAddress());
  420. return peers_map[p_peer_id]->get_connected_host();
  421. }
  422. int WebSocketMultiplayerPeer::get_peer_port(int p_peer_id) const {
  423. ERR_FAIL_COND_V(!peers_map.has(p_peer_id), 0);
  424. return peers_map[p_peer_id]->get_connected_port();
  425. }
  426. void WebSocketMultiplayerPeer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
  427. ERR_FAIL_COND(!peers_map.has(p_peer_id));
  428. peers_map[p_peer_id]->close(p_code, p_reason);
  429. }
  430. void WebSocketMultiplayerPeer::close() {
  431. _clear();
  432. }