websocket_multiplayer_peer.cpp 17 KB

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