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