websocket_multiplayer_peer.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. Vector<uint8_t> buffer = _make_pkt(SYS_NONE, get_unique_id(), target_peer, p_buffer, p_buffer_size);
  116. if (is_server()) {
  117. return _server_relay(1, target_peer, &(buffer.ptr()[0]), buffer.size());
  118. } else {
  119. return get_peer(1)->put_packet(&(buffer.ptr()[0]), buffer.size());
  120. }
  121. }
  122. //
  123. // MultiplayerPeer
  124. //
  125. void WebSocketMultiplayerPeer::set_target_peer(int p_target_peer) {
  126. target_peer = p_target_peer;
  127. }
  128. int WebSocketMultiplayerPeer::get_packet_peer() const {
  129. ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
  130. return incoming_packets.front()->get().source;
  131. }
  132. int WebSocketMultiplayerPeer::get_unique_id() const {
  133. return unique_id;
  134. }
  135. int WebSocketMultiplayerPeer::get_max_packet_size() const {
  136. return get_outbound_buffer_size() - PROTO_SIZE;
  137. }
  138. Error WebSocketMultiplayerPeer::create_server(int p_port, IPAddress p_bind_ip, Ref<CryptoKey> p_tls_key, Ref<X509Certificate> p_tls_certificate) {
  139. ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE);
  140. _clear();
  141. tcp_server.instantiate();
  142. Error err = tcp_server->listen(p_port, p_bind_ip);
  143. if (err != OK) {
  144. tcp_server.unref();
  145. return err;
  146. }
  147. unique_id = 1;
  148. connection_status = CONNECTION_CONNECTED;
  149. // TLS config
  150. tls_key = p_tls_key;
  151. tls_certificate = p_tls_certificate;
  152. if (tls_key.is_valid() && tls_certificate.is_valid()) {
  153. use_tls = true;
  154. }
  155. return OK;
  156. }
  157. Error WebSocketMultiplayerPeer::create_client(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) {
  158. ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE);
  159. _clear();
  160. Ref<WebSocketPeer> peer = _create_peer();
  161. Error err = peer->connect_to_url(p_url, p_verify_tls, p_tls_certificate);
  162. if (err != OK) {
  163. return err;
  164. }
  165. PendingPeer pending;
  166. pending.time = OS::get_singleton()->get_ticks_msec();
  167. pending_peers[1] = pending;
  168. peers_map[1] = peer;
  169. connection_status = CONNECTION_CONNECTING;
  170. return OK;
  171. }
  172. bool WebSocketMultiplayerPeer::is_server() const {
  173. return tcp_server.is_valid();
  174. }
  175. void WebSocketMultiplayerPeer::_poll_client() {
  176. ERR_FAIL_COND(connection_status == CONNECTION_DISCONNECTED); // Bug.
  177. ERR_FAIL_COND(!peers_map.has(1) || peers_map[1].is_null()); // Bug.
  178. Ref<WebSocketPeer> peer = peers_map[1];
  179. peer->poll(); // Update state and fetch packets.
  180. WebSocketPeer::State ready_state = peer->get_ready_state();
  181. if (ready_state == WebSocketPeer::STATE_OPEN) {
  182. while (peer->get_available_packet_count()) {
  183. _process_multiplayer(peer, 1);
  184. }
  185. } else if (peer->get_ready_state() == WebSocketPeer::STATE_CLOSED) {
  186. if (connection_status == CONNECTION_CONNECTED) {
  187. emit_signal(SNAME("server_disconnected"));
  188. } else {
  189. emit_signal(SNAME("connection_failed"));
  190. }
  191. _clear();
  192. return;
  193. }
  194. if (connection_status == CONNECTION_CONNECTING) {
  195. // Still connecting
  196. ERR_FAIL_COND(!pending_peers.has(1)); // Bug.
  197. if (OS::get_singleton()->get_ticks_msec() - pending_peers[1].time > handshake_timeout) {
  198. print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001));
  199. emit_signal(SNAME("connection_failed"));
  200. _clear();
  201. return;
  202. }
  203. }
  204. }
  205. void WebSocketMultiplayerPeer::_poll_server() {
  206. ERR_FAIL_COND(connection_status != CONNECTION_CONNECTED); // Bug.
  207. ERR_FAIL_COND(tcp_server.is_null() || !tcp_server->is_listening()); // Bug.
  208. // Accept new connections.
  209. if (!is_refusing_new_connections() && tcp_server->is_connection_available()) {
  210. PendingPeer peer;
  211. peer.time = OS::get_singleton()->get_ticks_msec();
  212. peer.tcp = tcp_server->take_connection();
  213. peer.connection = peer.tcp;
  214. pending_peers[generate_unique_id()] = peer;
  215. }
  216. // Process pending peers.
  217. HashSet<int> to_remove;
  218. for (KeyValue<int, PendingPeer> &E : pending_peers) {
  219. PendingPeer &peer = E.value;
  220. int id = E.key;
  221. if (OS::get_singleton()->get_ticks_msec() - peer.time > handshake_timeout) {
  222. print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001));
  223. to_remove.insert(id);
  224. continue;
  225. }
  226. if (peer.ws.is_valid()) {
  227. peer.ws->poll();
  228. WebSocketPeer::State state = peer.ws->get_ready_state();
  229. if (state == WebSocketPeer::STATE_OPEN) {
  230. // Connected.
  231. to_remove.insert(id);
  232. if (is_refusing_new_connections()) {
  233. // The user does not want new connections, dropping it.
  234. continue;
  235. }
  236. peers_map[id] = peer.ws;
  237. _send_ack(peer.ws, id);
  238. emit_signal("peer_connected", id);
  239. continue;
  240. } else if (state == WebSocketPeer::STATE_CONNECTING) {
  241. continue; // Still connecting.
  242. }
  243. to_remove.insert(id); // Error.
  244. continue;
  245. }
  246. if (peer.tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  247. to_remove.insert(id); // Error.
  248. continue;
  249. }
  250. if (!use_tls) {
  251. peer.ws = _create_peer();
  252. peer.ws->accept_stream(peer.tcp);
  253. continue;
  254. } else {
  255. if (peer.connection == peer.tcp) {
  256. Ref<StreamPeerTLS> tls = Ref<StreamPeerTLS>(StreamPeerTLS::create());
  257. Error err = tls->accept_stream(peer.tcp, tls_key, tls_certificate);
  258. if (err != OK) {
  259. to_remove.insert(id);
  260. continue;
  261. }
  262. }
  263. Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(peer.connection);
  264. tls->poll();
  265. if (tls->get_status() == StreamPeerTLS::STATUS_CONNECTED) {
  266. peer.ws = _create_peer();
  267. peer.ws->accept_stream(peer.connection);
  268. continue;
  269. } else if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
  270. // Still connecting.
  271. continue;
  272. } else {
  273. // Error
  274. to_remove.insert(id);
  275. }
  276. }
  277. }
  278. // Remove disconnected pending peers.
  279. for (const int &pid : to_remove) {
  280. pending_peers.erase(pid);
  281. }
  282. to_remove.clear();
  283. // Process connected peers.
  284. for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
  285. Ref<WebSocketPeer> ws = E.value;
  286. int id = E.key;
  287. ws->poll();
  288. if (ws->get_ready_state() != WebSocketPeer::STATE_OPEN) {
  289. to_remove.insert(id); // Disconnected.
  290. continue;
  291. }
  292. // Fetch packets
  293. int pkts = ws->get_available_packet_count();
  294. while (pkts && ws->get_ready_state() == WebSocketPeer::STATE_OPEN) {
  295. _process_multiplayer(ws, id);
  296. pkts--;
  297. }
  298. }
  299. // Remove disconnected peers.
  300. for (const int &pid : to_remove) {
  301. emit_signal(SNAME("peer_disconnected"), pid);
  302. peers_map.erase(pid);
  303. }
  304. }
  305. void WebSocketMultiplayerPeer::poll() {
  306. if (connection_status == CONNECTION_DISCONNECTED) {
  307. return;
  308. }
  309. if (is_server()) {
  310. _poll_server();
  311. } else {
  312. _poll_client();
  313. }
  314. }
  315. MultiplayerPeer::ConnectionStatus WebSocketMultiplayerPeer::get_connection_status() const {
  316. return connection_status;
  317. }
  318. Ref<WebSocketPeer> WebSocketMultiplayerPeer::get_peer(int p_id) const {
  319. ERR_FAIL_COND_V(!peers_map.has(p_id), Ref<WebSocketPeer>());
  320. return peers_map[p_id];
  321. }
  322. void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id) {
  323. ERR_FAIL_COND(!p_peer.is_valid());
  324. ERR_FAIL_COND(p_peer->get_ready_state() != WebSocketPeer::STATE_OPEN);
  325. Vector<uint8_t> message = _make_pkt(p_type, 1, 0, (uint8_t *)&p_peer_id, 4);
  326. p_peer->put_packet(&(message.ptr()[0]), message.size());
  327. }
  328. Vector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) {
  329. Vector<uint8_t> out;
  330. out.resize(PROTO_SIZE + p_data_size);
  331. uint8_t *w = out.ptrw();
  332. memcpy(&w[0], &p_type, 1);
  333. memcpy(&w[1], &p_from, 4);
  334. memcpy(&w[5], &p_to, 4);
  335. memcpy(&w[PROTO_SIZE], p_data, p_data_size);
  336. return out;
  337. }
  338. void WebSocketMultiplayerPeer::_send_ack(Ref<WebSocketPeer> p_peer, int32_t p_peer_id) {
  339. ERR_FAIL_COND(p_peer.is_null());
  340. // First of all, confirm the ID!
  341. _send_sys(p_peer, SYS_ID, p_peer_id);
  342. // Then send the server peer (which will trigger connection_succeded in client)
  343. _send_sys(p_peer, SYS_ADD, 1);
  344. for (const KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
  345. ERR_CONTINUE(E.value.is_null());
  346. int32_t id = E.key;
  347. if (p_peer_id == id) {
  348. continue; // Skip the newly added peer (already confirmed)
  349. }
  350. // Send new peer to others
  351. _send_sys(E.value, SYS_ADD, p_peer_id);
  352. // Send others to new peer
  353. _send_sys(E.value, SYS_ADD, id);
  354. }
  355. }
  356. void WebSocketMultiplayerPeer::_send_del(int32_t p_peer_id) {
  357. for (const KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
  358. int32_t id = E.key;
  359. if (p_peer_id != id) {
  360. _send_sys(E.value, SYS_DEL, p_peer_id);
  361. }
  362. }
  363. }
  364. void WebSocketMultiplayerPeer::_store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size) {
  365. Packet packet;
  366. packet.data = (uint8_t *)memalloc(p_data_size);
  367. packet.size = p_data_size;
  368. packet.source = p_source;
  369. packet.destination = p_dest;
  370. memcpy(packet.data, &p_data[PROTO_SIZE], p_data_size);
  371. incoming_packets.push_back(packet);
  372. }
  373. Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size) {
  374. if (p_to == 1) {
  375. return OK; // Will not send to self
  376. } else if (p_to == 0) {
  377. for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
  378. if (E.key != p_from) {
  379. E.value->put_packet(p_buffer, p_buffer_size);
  380. }
  381. }
  382. return OK; // Sent to all but sender
  383. } else if (p_to < 0) {
  384. for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
  385. if (E.key != p_from && E.key != -p_to) {
  386. E.value->put_packet(p_buffer, p_buffer_size);
  387. }
  388. }
  389. return OK; // Sent to all but sender and excluded
  390. } else {
  391. ERR_FAIL_COND_V(p_to == p_from, FAILED);
  392. Ref<WebSocketPeer> peer_to = get_peer(p_to);
  393. ERR_FAIL_COND_V(peer_to.is_null(), FAILED);
  394. return peer_to->put_packet(p_buffer, p_buffer_size); // Sending to specific peer
  395. }
  396. }
  397. void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id) {
  398. ERR_FAIL_COND(!p_peer.is_valid());
  399. const uint8_t *in_buffer;
  400. int size = 0;
  401. int data_size = 0;
  402. Error err = p_peer->get_packet(&in_buffer, size);
  403. ERR_FAIL_COND(err != OK);
  404. ERR_FAIL_COND(size < PROTO_SIZE);
  405. data_size = size - PROTO_SIZE;
  406. uint8_t type = 0;
  407. uint32_t from = 0;
  408. int32_t to = 0;
  409. memcpy(&type, in_buffer, 1);
  410. memcpy(&from, &in_buffer[1], 4);
  411. memcpy(&to, &in_buffer[5], 4);
  412. if (is_server()) { // Server can resend
  413. ERR_FAIL_COND(type != SYS_NONE); // Only server sends sys messages
  414. ERR_FAIL_COND(from != p_peer_id); // Someone is cheating
  415. if (to == 1) {
  416. // This is for the server
  417. _store_pkt(from, to, in_buffer, data_size);
  418. } else if (to == 0) {
  419. // Broadcast, for us too
  420. _store_pkt(from, to, in_buffer, data_size);
  421. } else if (to < -1) {
  422. // All but one, for us if not excluded
  423. _store_pkt(from, to, in_buffer, data_size);
  424. }
  425. // Relay if needed (i.e. "to" includes a peer that is not the server)
  426. _server_relay(from, to, in_buffer, size);
  427. } else {
  428. if (type == SYS_NONE) {
  429. // Payload message
  430. _store_pkt(from, to, in_buffer, data_size);
  431. return;
  432. }
  433. // System message
  434. ERR_FAIL_COND(data_size < 4);
  435. int id = 0;
  436. memcpy(&id, &in_buffer[PROTO_SIZE], 4);
  437. switch (type) {
  438. case SYS_ADD: // Add peer
  439. if (id != 1) {
  440. peers_map[id] = Ref<WebSocketPeer>();
  441. } else {
  442. pending_peers.clear();
  443. connection_status = CONNECTION_CONNECTED;
  444. }
  445. emit_signal(SNAME("peer_connected"), id);
  446. if (id == 1) { // We just connected to the server
  447. emit_signal(SNAME("connection_succeeded"));
  448. }
  449. break;
  450. case SYS_DEL: // Remove peer
  451. emit_signal(SNAME("peer_disconnected"), id);
  452. peers_map.erase(id);
  453. break;
  454. case SYS_ID: // Hello, server assigned ID
  455. unique_id = id;
  456. break;
  457. default:
  458. ERR_FAIL_MSG("Invalid multiplayer message.");
  459. break;
  460. }
  461. }
  462. }
  463. void WebSocketMultiplayerPeer::set_supported_protocols(const Vector<String> &p_protocols) {
  464. peer_config->set_supported_protocols(p_protocols);
  465. }
  466. Vector<String> WebSocketMultiplayerPeer::get_supported_protocols() const {
  467. return peer_config->get_supported_protocols();
  468. }
  469. void WebSocketMultiplayerPeer::set_handshake_headers(const Vector<String> &p_headers) {
  470. peer_config->set_handshake_headers(p_headers);
  471. }
  472. Vector<String> WebSocketMultiplayerPeer::get_handshake_headers() const {
  473. return peer_config->get_handshake_headers();
  474. }
  475. void WebSocketMultiplayerPeer::set_outbound_buffer_size(int p_buffer_size) {
  476. peer_config->set_outbound_buffer_size(p_buffer_size);
  477. }
  478. int WebSocketMultiplayerPeer::get_outbound_buffer_size() const {
  479. return peer_config->get_outbound_buffer_size();
  480. }
  481. void WebSocketMultiplayerPeer::set_inbound_buffer_size(int p_buffer_size) {
  482. peer_config->set_inbound_buffer_size(p_buffer_size);
  483. }
  484. int WebSocketMultiplayerPeer::get_inbound_buffer_size() const {
  485. return peer_config->get_inbound_buffer_size();
  486. }
  487. void WebSocketMultiplayerPeer::set_max_queued_packets(int p_max_queued_packets) {
  488. peer_config->set_max_queued_packets(p_max_queued_packets);
  489. }
  490. int WebSocketMultiplayerPeer::get_max_queued_packets() const {
  491. return peer_config->get_max_queued_packets();
  492. }
  493. float WebSocketMultiplayerPeer::get_handshake_timeout() const {
  494. return handshake_timeout / 1000.0;
  495. }
  496. void WebSocketMultiplayerPeer::set_handshake_timeout(float p_timeout) {
  497. ERR_FAIL_COND(p_timeout <= 0.0);
  498. handshake_timeout = p_timeout * 1000;
  499. }
  500. IPAddress WebSocketMultiplayerPeer::get_peer_address(int p_peer_id) const {
  501. ERR_FAIL_COND_V(!peers_map.has(p_peer_id), IPAddress());
  502. return peers_map[p_peer_id]->get_connected_host();
  503. }
  504. int WebSocketMultiplayerPeer::get_peer_port(int p_peer_id) const {
  505. ERR_FAIL_COND_V(!peers_map.has(p_peer_id), 0);
  506. return peers_map[p_peer_id]->get_connected_port();
  507. }
  508. void WebSocketMultiplayerPeer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
  509. ERR_FAIL_COND(!peers_map.has(p_peer_id));
  510. peers_map[p_peer_id]->close(p_code, p_reason);
  511. }
  512. void WebSocketMultiplayerPeer::close() {
  513. _clear();
  514. }