Debian Codegraph @

modules/websocket/websocket_multiplayer_peer.cpp

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