1/**************************************************************************/
2/* net_socket_posix.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 "net_socket_posix.h"
32
33// Some proprietary Unix-derived platforms don't expose Unix sockets
34// so this allows skipping this file to reimplement this API differently.
35#ifndef UNIX_SOCKET_UNAVAILABLE
36
37#if defined(UNIX_ENABLED)
38
39#include <errno.h>
40#include <fcntl.h>
41#include <netdb.h>
42#include <netinet/in.h>
43#include <netinet/tcp.h>
44#include <poll.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <sys/ioctl.h>
49#include <sys/socket.h>
50#include <sys/types.h>
51#include <unistd.h>
52
53#ifdef WEB_ENABLED
54#include <arpa/inet.h>
55#endif
56
57// BSD calls this flag IPV6_JOIN_GROUP
58#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
59#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
60#endif
61#if !defined(IPV6_DROP_MEMBERSHIP) && defined(IPV6_LEAVE_GROUP)
62#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
63#endif
64
65// Some custom defines to minimize ifdefs
66#define SOCK_EMPTY -1
67#define SOCK_BUF(x) x
68#define SOCK_CBUF(x) x
69#define SOCK_IOCTL ioctl
70#define SOCK_CLOSE ::close
71#define SOCK_CONNECT(p_sock, p_addr, p_addr_len) ::connect(p_sock, p_addr, p_addr_len)
72
73/* Windows */
74#elif defined(WINDOWS_ENABLED)
75#include <winsock2.h>
76#include <ws2tcpip.h>
77
78#include <mswsock.h>
79// Some custom defines to minimize ifdefs
80#define SOCK_EMPTY INVALID_SOCKET
81#define SOCK_BUF(x) (char *)(x)
82#define SOCK_CBUF(x) (const char *)(x)
83#define SOCK_IOCTL ioctlsocket
84#define SOCK_CLOSE closesocket
85// connect is broken on windows under certain conditions, reasons unknown:
86// See https://github.com/godotengine/webrtc-native/issues/6
87#define SOCK_CONNECT(p_sock, p_addr, p_addr_len) ::WSAConnect(p_sock, p_addr, p_addr_len, nullptr, nullptr, nullptr, nullptr)
88
89// Workaround missing flag in MinGW
90#if defined(__MINGW32__) && !defined(SIO_UDP_NETRESET)
91#define SIO_UDP_NETRESET _WSAIOW(IOC_VENDOR, 15)
92#endif
93
94#endif // UNIX_ENABLED
95
96size_t NetSocketPosix::_set_addr_storage(struct sockaddr_storage *p_addr, const IPAddress &p_ip, uint16_t p_port, IP::Type p_ip_type) {
97 memset(p_addr, 0, sizeof(struct sockaddr_storage));
98 if (p_ip_type == IP::TYPE_IPV6 || p_ip_type == IP::TYPE_ANY) { // IPv6 socket
99
100 // IPv6 only socket with IPv4 address
101 ERR_FAIL_COND_V(!p_ip.is_wildcard() && p_ip_type == IP::TYPE_IPV6 && p_ip.is_ipv4(), 0);
102
103 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
104 addr6->sin6_family = AF_INET6;
105 addr6->sin6_port = htons(p_port);
106 if (p_ip.is_valid()) {
107 memcpy(&addr6->sin6_addr.s6_addr, p_ip.get_ipv6(), 16);
108 } else {
109 addr6->sin6_addr = in6addr_any;
110 }
111 return sizeof(sockaddr_in6);
112 } else { // IPv4 socket
113
114 // IPv4 socket with IPv6 address
115 ERR_FAIL_COND_V(!p_ip.is_wildcard() && !p_ip.is_ipv4(), 0);
116
117 struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
118 addr4->sin_family = AF_INET;
119 addr4->sin_port = htons(p_port); // short, network byte order
120
121 if (p_ip.is_valid()) {
122 memcpy(&addr4->sin_addr.s_addr, p_ip.get_ipv4(), 4);
123 } else {
124 addr4->sin_addr.s_addr = INADDR_ANY;
125 }
126
127 return sizeof(sockaddr_in);
128 }
129}
130
131void NetSocketPosix::_set_ip_port(struct sockaddr_storage *p_addr, IPAddress *r_ip, uint16_t *r_port) {
132 if (p_addr->ss_family == AF_INET) {
133 struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
134 if (r_ip) {
135 r_ip->set_ipv4((uint8_t *)&(addr4->sin_addr.s_addr));
136 }
137 if (r_port) {
138 *r_port = ntohs(addr4->sin_port);
139 }
140 } else if (p_addr->ss_family == AF_INET6) {
141 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
142 if (r_ip) {
143 r_ip->set_ipv6(addr6->sin6_addr.s6_addr);
144 }
145 if (r_port) {
146 *r_port = ntohs(addr6->sin6_port);
147 }
148 }
149}
150
151NetSocket *NetSocketPosix::_create_func() {
152 return memnew(NetSocketPosix);
153}
154
155void NetSocketPosix::make_default() {
156#if defined(WINDOWS_ENABLED)
157 if (_create == nullptr) {
158 WSADATA data;
159 WSAStartup(MAKEWORD(2, 2), &data);
160 }
161#endif
162 _create = _create_func;
163}
164
165void NetSocketPosix::cleanup() {
166#if defined(WINDOWS_ENABLED)
167 if (_create != nullptr) {
168 WSACleanup();
169 }
170 _create = nullptr;
171#endif
172}
173
174NetSocketPosix::NetSocketPosix() :
175 _sock(SOCK_EMPTY) {
176}
177
178NetSocketPosix::~NetSocketPosix() {
179 close();
180}
181
182// Silence a warning reported in GH-27594.
183// EAGAIN and EWOULDBLOCK have the same value on most platforms, but it's not guaranteed.
184#if defined(__GNUC__) && !defined(__clang__)
185#pragma GCC diagnostic push
186#pragma GCC diagnostic ignored "-Wlogical-op"
187#endif
188
189NetSocketPosix::NetError NetSocketPosix::_get_socket_error() const {
190#if defined(WINDOWS_ENABLED)
191 int err = WSAGetLastError();
192 if (err == WSAEISCONN) {
193 return ERR_NET_IS_CONNECTED;
194 }
195 if (err == WSAEINPROGRESS || err == WSAEALREADY) {
196 return ERR_NET_IN_PROGRESS;
197 }
198 if (err == WSAEWOULDBLOCK) {
199 return ERR_NET_WOULD_BLOCK;
200 }
201 if (err == WSAEADDRINUSE || err == WSAEADDRNOTAVAIL) {
202 return ERR_NET_ADDRESS_INVALID_OR_UNAVAILABLE;
203 }
204 if (err == WSAEACCES) {
205 return ERR_NET_UNAUTHORIZED;
206 }
207 if (err == WSAEMSGSIZE || err == WSAENOBUFS) {
208 return ERR_NET_BUFFER_TOO_SMALL;
209 }
210 print_verbose("Socket error: " + itos(err));
211 return ERR_NET_OTHER;
212#else
213 if (errno == EISCONN) {
214 return ERR_NET_IS_CONNECTED;
215 }
216 if (errno == EINPROGRESS || errno == EALREADY) {
217 return ERR_NET_IN_PROGRESS;
218 }
219 if (errno == EAGAIN || errno == EWOULDBLOCK) {
220 return ERR_NET_WOULD_BLOCK;
221 }
222 if (errno == EADDRINUSE || errno == EINVAL || errno == EADDRNOTAVAIL) {
223 return ERR_NET_ADDRESS_INVALID_OR_UNAVAILABLE;
224 }
225 if (errno == EACCES) {
226 return ERR_NET_UNAUTHORIZED;
227 }
228 if (errno == ENOBUFS) {
229 return ERR_NET_BUFFER_TOO_SMALL;
230 }
231 print_verbose("Socket error: " + itos(errno));
232 return ERR_NET_OTHER;
233#endif
234}
235
236#if defined(__GNUC__) && !defined(__clang__)
237#pragma GCC diagnostic pop
238#endif
239
240bool NetSocketPosix::_can_use_ip(const IPAddress &p_ip, const bool p_for_bind) const {
241 if (p_for_bind && !(p_ip.is_valid() || p_ip.is_wildcard())) {
242 return false;
243 } else if (!p_for_bind && !p_ip.is_valid()) {
244 return false;
245 }
246 // Check if socket support this IP type.
247 IP::Type type = p_ip.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
248 return !(_ip_type != IP::TYPE_ANY && !p_ip.is_wildcard() && _ip_type != type);
249}
250
251_FORCE_INLINE_ Error NetSocketPosix::_change_multicast_group(IPAddress p_ip, String p_if_name, bool p_add) {
252 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
253 ERR_FAIL_COND_V(!_can_use_ip(p_ip, false), ERR_INVALID_PARAMETER);
254
255 // Need to force level and af_family to IP(v4) when using dual stacking and provided multicast group is IPv4
256 IP::Type type = _ip_type == IP::TYPE_ANY && p_ip.is_ipv4() ? IP::TYPE_IPV4 : _ip_type;
257 // This needs to be the proper level for the multicast group, no matter if the socket is dual stacking.
258 int level = type == IP::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
259 int ret = -1;
260
261 IPAddress if_ip;
262 uint32_t if_v6id = 0;
263 HashMap<String, IP::Interface_Info> if_info;
264 IP::get_singleton()->get_local_interfaces(&if_info);
265 for (KeyValue<String, IP::Interface_Info> &E : if_info) {
266 IP::Interface_Info &c = E.value;
267 if (c.name != p_if_name) {
268 continue;
269 }
270
271 if_v6id = (uint32_t)c.index.to_int();
272 if (type == IP::TYPE_IPV6) {
273 break; // IPv6 uses index.
274 }
275
276 for (const IPAddress &F : c.ip_addresses) {
277 if (!F.is_ipv4()) {
278 continue; // Wrong IP type
279 }
280 if_ip = F;
281 break;
282 }
283 break;
284 }
285
286 if (level == IPPROTO_IP) {
287 ERR_FAIL_COND_V(!if_ip.is_valid(), ERR_INVALID_PARAMETER);
288 struct ip_mreq greq;
289 int sock_opt = p_add ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
290 memcpy(&greq.imr_multiaddr, p_ip.get_ipv4(), 4);
291 memcpy(&greq.imr_interface, if_ip.get_ipv4(), 4);
292 ret = setsockopt(_sock, level, sock_opt, (const char *)&greq, sizeof(greq));
293 } else {
294 struct ipv6_mreq greq;
295 int sock_opt = p_add ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
296 memcpy(&greq.ipv6mr_multiaddr, p_ip.get_ipv6(), 16);
297 greq.ipv6mr_interface = if_v6id;
298 ret = setsockopt(_sock, level, sock_opt, (const char *)&greq, sizeof(greq));
299 }
300 ERR_FAIL_COND_V(ret != 0, FAILED);
301
302 return OK;
303}
304
305void NetSocketPosix::_set_socket(SOCKET_TYPE p_sock, IP::Type p_ip_type, bool p_is_stream) {
306 _sock = p_sock;
307 _ip_type = p_ip_type;
308 _is_stream = p_is_stream;
309 // Disable descriptor sharing with subprocesses.
310 _set_close_exec_enabled(true);
311}
312
313void NetSocketPosix::_set_close_exec_enabled(bool p_enabled) {
314#ifndef WINDOWS_ENABLED
315 // Enable close on exec to avoid sharing with subprocesses. Off by default on Windows.
316 int opts = fcntl(_sock, F_GETFD);
317 fcntl(_sock, F_SETFD, opts | FD_CLOEXEC);
318#endif
319}
320
321Error NetSocketPosix::open(Type p_sock_type, IP::Type &ip_type) {
322 ERR_FAIL_COND_V(is_open(), ERR_ALREADY_IN_USE);
323 ERR_FAIL_COND_V(ip_type > IP::TYPE_ANY || ip_type < IP::TYPE_NONE, ERR_INVALID_PARAMETER);
324
325#if defined(__OpenBSD__)
326 // OpenBSD does not support dual stacking, fallback to IPv4 only.
327 if (ip_type == IP::TYPE_ANY) {
328 ip_type = IP::TYPE_IPV4;
329 }
330#endif
331
332 int family = ip_type == IP::TYPE_IPV4 ? AF_INET : AF_INET6;
333 int protocol = p_sock_type == TYPE_TCP ? IPPROTO_TCP : IPPROTO_UDP;
334 int type = p_sock_type == TYPE_TCP ? SOCK_STREAM : SOCK_DGRAM;
335 _sock = socket(family, type, protocol);
336
337 if (_sock == SOCK_EMPTY && ip_type == IP::TYPE_ANY) {
338 // Careful here, changing the referenced parameter so the caller knows that we are using an IPv4 socket
339 // in place of a dual stack one, and further calls to _set_sock_addr will work as expected.
340 ip_type = IP::TYPE_IPV4;
341 family = AF_INET;
342 _sock = socket(family, type, protocol);
343 }
344
345 ERR_FAIL_COND_V(_sock == SOCK_EMPTY, FAILED);
346 _ip_type = ip_type;
347
348 if (family == AF_INET6) {
349 // Select IPv4 over IPv6 mapping
350 set_ipv6_only_enabled(ip_type != IP::TYPE_ANY);
351 }
352
353 if (protocol == IPPROTO_UDP) {
354 // Make sure to disable broadcasting for UDP sockets.
355 // Depending on the OS, this option might or might not be enabled by default. Let's normalize it.
356 set_broadcasting_enabled(false);
357 }
358
359 _is_stream = p_sock_type == TYPE_TCP;
360
361 // Disable descriptor sharing with subprocesses.
362 _set_close_exec_enabled(true);
363
364#if defined(WINDOWS_ENABLED)
365 if (!_is_stream) {
366 // Disable windows feature/bug reporting WSAECONNRESET/WSAENETRESET when
367 // recv/recvfrom and an ICMP reply was received from a previous send/sendto.
368 unsigned long disable = 0;
369 if (ioctlsocket(_sock, SIO_UDP_CONNRESET, &disable) == SOCKET_ERROR) {
370 print_verbose("Unable to turn off UDP WSAECONNRESET behavior on Windows");
371 }
372 if (ioctlsocket(_sock, SIO_UDP_NETRESET, &disable) == SOCKET_ERROR) {
373 // This feature seems not to be supported on wine.
374 print_verbose("Unable to turn off UDP WSAENETRESET behavior on Windows");
375 }
376 }
377#endif
378#if defined(SO_NOSIGPIPE)
379 // Disable SIGPIPE (should only be relevant to stream sockets, but seems to affect UDP too on iOS)
380 int par = 1;
381 if (setsockopt(_sock, SOL_SOCKET, SO_NOSIGPIPE, SOCK_CBUF(&par), sizeof(int)) != 0) {
382 print_verbose("Unable to turn off SIGPIPE on socket");
383 }
384#endif
385 return OK;
386}
387
388void NetSocketPosix::close() {
389 if (_sock != SOCK_EMPTY) {
390 SOCK_CLOSE(_sock);
391 }
392
393 _sock = SOCK_EMPTY;
394 _ip_type = IP::TYPE_NONE;
395 _is_stream = false;
396}
397
398Error NetSocketPosix::bind(IPAddress p_addr, uint16_t p_port) {
399 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
400 ERR_FAIL_COND_V(!_can_use_ip(p_addr, true), ERR_INVALID_PARAMETER);
401
402 sockaddr_storage addr;
403 size_t addr_size = _set_addr_storage(&addr, p_addr, p_port, _ip_type);
404
405 if (::bind(_sock, (struct sockaddr *)&addr, addr_size) != 0) {
406 NetError err = _get_socket_error();
407 print_verbose("Failed to bind socket. Error: " + itos(err));
408 close();
409 return ERR_UNAVAILABLE;
410 }
411
412 return OK;
413}
414
415Error NetSocketPosix::listen(int p_max_pending) {
416 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
417
418 if (::listen(_sock, p_max_pending) != 0) {
419 _get_socket_error();
420 print_verbose("Failed to listen from socket.");
421 close();
422 return FAILED;
423 }
424
425 return OK;
426}
427
428Error NetSocketPosix::connect_to_host(IPAddress p_host, uint16_t p_port) {
429 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
430 ERR_FAIL_COND_V(!_can_use_ip(p_host, false), ERR_INVALID_PARAMETER);
431
432 struct sockaddr_storage addr;
433 size_t addr_size = _set_addr_storage(&addr, p_host, p_port, _ip_type);
434
435 if (SOCK_CONNECT(_sock, (struct sockaddr *)&addr, addr_size) != 0) {
436 NetError err = _get_socket_error();
437
438 switch (err) {
439 // We are already connected
440 case ERR_NET_IS_CONNECTED:
441 return OK;
442 // Still waiting to connect, try again in a while
443 case ERR_NET_WOULD_BLOCK:
444 case ERR_NET_IN_PROGRESS:
445 return ERR_BUSY;
446 default:
447 print_verbose("Connection to remote host failed!");
448 close();
449 return FAILED;
450 }
451 }
452
453 return OK;
454}
455
456Error NetSocketPosix::poll(PollType p_type, int p_timeout) const {
457 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
458
459#if defined(WINDOWS_ENABLED)
460 bool ready = false;
461 fd_set rd, wr, ex;
462 fd_set *rdp = nullptr;
463 fd_set *wrp = nullptr;
464 FD_ZERO(&rd);
465 FD_ZERO(&wr);
466 FD_ZERO(&ex);
467 FD_SET(_sock, &ex);
468 struct timeval timeout = { p_timeout / 1000, (p_timeout % 1000) * 1000 };
469 // For blocking operation, pass nullptr timeout pointer to select.
470 struct timeval *tp = nullptr;
471 if (p_timeout >= 0) {
472 // If timeout is non-negative, we want to specify the timeout instead.
473 tp = &timeout;
474 }
475
476 switch (p_type) {
477 case POLL_TYPE_IN:
478 FD_SET(_sock, &rd);
479 rdp = &rd;
480 break;
481 case POLL_TYPE_OUT:
482 FD_SET(_sock, &wr);
483 wrp = &wr;
484 break;
485 case POLL_TYPE_IN_OUT:
486 FD_SET(_sock, &rd);
487 FD_SET(_sock, &wr);
488 rdp = &rd;
489 wrp = &wr;
490 }
491 int ret = select(1, rdp, wrp, &ex, tp);
492
493 if (ret == SOCKET_ERROR) {
494 return FAILED;
495 }
496
497 if (ret == 0) {
498 return ERR_BUSY;
499 }
500
501 if (FD_ISSET(_sock, &ex)) {
502 _get_socket_error();
503 print_verbose("Exception when polling socket.");
504 return FAILED;
505 }
506
507 if (rdp && FD_ISSET(_sock, rdp)) {
508 ready = true;
509 }
510 if (wrp && FD_ISSET(_sock, wrp)) {
511 ready = true;
512 }
513
514 return ready ? OK : ERR_BUSY;
515#else
516 struct pollfd pfd;
517 pfd.fd = _sock;
518 pfd.events = POLLIN;
519 pfd.revents = 0;
520
521 switch (p_type) {
522 case POLL_TYPE_IN:
523 pfd.events = POLLIN;
524 break;
525 case POLL_TYPE_OUT:
526 pfd.events = POLLOUT;
527 break;
528 case POLL_TYPE_IN_OUT:
529 pfd.events = POLLOUT | POLLIN;
530 }
531
532 int ret = ::poll(&pfd, 1, p_timeout);
533
534 if (ret < 0 || pfd.revents & POLLERR) {
535 _get_socket_error();
536 print_verbose("Error when polling socket.");
537 return FAILED;
538 }
539
540 if (ret == 0) {
541 return ERR_BUSY;
542 }
543
544 return OK;
545#endif
546}
547
548Error NetSocketPosix::recv(uint8_t *p_buffer, int p_len, int &r_read) {
549 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
550
551 r_read = ::recv(_sock, SOCK_BUF(p_buffer), p_len, 0);
552
553 if (r_read < 0) {
554 NetError err = _get_socket_error();
555 if (err == ERR_NET_WOULD_BLOCK) {
556 return ERR_BUSY;
557 }
558
559 if (err == ERR_NET_BUFFER_TOO_SMALL) {
560 return ERR_OUT_OF_MEMORY;
561 }
562
563 return FAILED;
564 }
565
566 return OK;
567}
568
569Error NetSocketPosix::recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IPAddress &r_ip, uint16_t &r_port, bool p_peek) {
570 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
571
572 struct sockaddr_storage from;
573 socklen_t len = sizeof(struct sockaddr_storage);
574 memset(&from, 0, len);
575
576 r_read = ::recvfrom(_sock, SOCK_BUF(p_buffer), p_len, p_peek ? MSG_PEEK : 0, (struct sockaddr *)&from, &len);
577
578 if (r_read < 0) {
579 NetError err = _get_socket_error();
580 if (err == ERR_NET_WOULD_BLOCK) {
581 return ERR_BUSY;
582 }
583
584 if (err == ERR_NET_BUFFER_TOO_SMALL) {
585 return ERR_OUT_OF_MEMORY;
586 }
587
588 return FAILED;
589 }
590
591 if (from.ss_family == AF_INET) {
592 struct sockaddr_in *sin_from = (struct sockaddr_in *)&from;
593 r_ip.set_ipv4((uint8_t *)&sin_from->sin_addr);
594 r_port = ntohs(sin_from->sin_port);
595 } else if (from.ss_family == AF_INET6) {
596 struct sockaddr_in6 *s6_from = (struct sockaddr_in6 *)&from;
597 r_ip.set_ipv6((uint8_t *)&s6_from->sin6_addr);
598 r_port = ntohs(s6_from->sin6_port);
599 } else {
600 // Unsupported socket family, should never happen.
601 ERR_FAIL_V(FAILED);
602 }
603
604 return OK;
605}
606
607Error NetSocketPosix::send(const uint8_t *p_buffer, int p_len, int &r_sent) {
608 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
609
610 int flags = 0;
611#ifdef MSG_NOSIGNAL
612 if (_is_stream) {
613 flags = MSG_NOSIGNAL;
614 }
615#endif
616 r_sent = ::send(_sock, SOCK_CBUF(p_buffer), p_len, flags);
617
618 if (r_sent < 0) {
619 NetError err = _get_socket_error();
620 if (err == ERR_NET_WOULD_BLOCK) {
621 return ERR_BUSY;
622 }
623 if (err == ERR_NET_BUFFER_TOO_SMALL) {
624 return ERR_OUT_OF_MEMORY;
625 }
626
627 return FAILED;
628 }
629
630 return OK;
631}
632
633Error NetSocketPosix::sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
634 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
635
636 struct sockaddr_storage addr;
637 size_t addr_size = _set_addr_storage(&addr, p_ip, p_port, _ip_type);
638 r_sent = ::sendto(_sock, SOCK_CBUF(p_buffer), p_len, 0, (struct sockaddr *)&addr, addr_size);
639
640 if (r_sent < 0) {
641 NetError err = _get_socket_error();
642 if (err == ERR_NET_WOULD_BLOCK) {
643 return ERR_BUSY;
644 }
645 if (err == ERR_NET_BUFFER_TOO_SMALL) {
646 return ERR_OUT_OF_MEMORY;
647 }
648
649 return FAILED;
650 }
651
652 return OK;
653}
654
655Error NetSocketPosix::set_broadcasting_enabled(bool p_enabled) {
656 ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
657 // IPv6 has no broadcast support.
658 if (_ip_type == IP::TYPE_IPV6) {
659 return ERR_UNAVAILABLE;
660 }
661
662 int par = p_enabled ? 1 : 0;
663 if (setsockopt(_sock, SOL_SOCKET, SO_BROADCAST, SOCK_CBUF(&par), sizeof(int)) != 0) {
664 WARN_PRINT("Unable to change broadcast setting");
665 return FAILED;
666 }
667 return OK;
668}
669
670void NetSocketPosix::set_blocking_enabled(bool p_enabled) {
671 ERR_FAIL_COND(!is_open());
672
673 int ret = 0;
674#if defined(WINDOWS_ENABLED)
675 unsigned long par = p_enabled ? 0 : 1;
676 ret = SOCK_IOCTL(_sock, FIONBIO, &par);
677#else
678 int opts = fcntl(_sock, F_GETFL);
679 if (p_enabled) {
680 ret = fcntl(_sock, F_SETFL, opts & ~O_NONBLOCK);
681 } else {
682 ret = fcntl(_sock, F_SETFL, opts | O_NONBLOCK);
683 }
684#endif
685
686 if (ret != 0) {
687 WARN_PRINT("Unable to change non-block mode");
688 }
689}
690
691void NetSocketPosix::set_ipv6_only_enabled(bool p_enabled) {
692 ERR_FAIL_COND(!is_open());
693 // This option is only available in IPv6 sockets.
694 ERR_FAIL_COND(_ip_type == IP::TYPE_IPV4);
695
696 int par = p_enabled ? 1 : 0;
697 if (setsockopt(_sock, IPPROTO_IPV6, IPV6_V6ONLY, SOCK_CBUF(&par), sizeof(int)) != 0) {
698 WARN_PRINT("Unable to change IPv4 address mapping over IPv6 option");
699 }
700}
701
702void NetSocketPosix::set_tcp_no_delay_enabled(bool p_enabled) {
703 ERR_FAIL_COND(!is_open());
704 ERR_FAIL_COND(!_is_stream); // Not TCP
705
706 int par = p_enabled ? 1 : 0;
707 if (setsockopt(_sock, IPPROTO_TCP, TCP_NODELAY, SOCK_CBUF(&par), sizeof(int)) < 0) {
708 ERR_PRINT("Unable to set TCP no delay option");
709 }
710}
711
712void NetSocketPosix::set_reuse_address_enabled(bool p_enabled) {
713 ERR_FAIL_COND(!is_open());
714
715// On Windows, enabling SO_REUSEADDR actually would also enable reuse port, very bad on TCP. Denying...
716// Windows does not have this option, SO_REUSEADDR in this magical world means SO_REUSEPORT
717#ifndef WINDOWS_ENABLED
718 int par = p_enabled ? 1 : 0;
719 if (setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, SOCK_CBUF(&par), sizeof(int)) < 0) {
720 WARN_PRINT("Unable to set socket REUSEADDR option!");
721 }
722#endif
723}
724
725void NetSocketPosix::set_reuse_port_enabled(bool p_enabled) {
726 ERR_FAIL_COND(!is_open());
727
728// See comment above...
729#ifdef WINDOWS_ENABLED
730#define SO_REUSEPORT SO_REUSEADDR
731#endif
732 int par = p_enabled ? 1 : 0;
733 if (setsockopt(_sock, SOL_SOCKET, SO_REUSEPORT, SOCK_CBUF(&par), sizeof(int)) < 0) {
734 WARN_PRINT("Unable to set socket REUSEPORT option!");
735 }
736}
737
738bool NetSocketPosix::is_open() const {
739 return _sock != SOCK_EMPTY;
740}
741
742int NetSocketPosix::get_available_bytes() const {
743 ERR_FAIL_COND_V(!is_open(), -1);
744
745 unsigned long len;
746 int ret = SOCK_IOCTL(_sock, FIONREAD, &len);
747 if (ret == -1) {
748 _get_socket_error();
749 print_verbose("Error when checking available bytes on socket.");
750 return -1;
751 }
752 return len;
753}
754
755Error NetSocketPosix::get_socket_address(IPAddress *r_ip, uint16_t *r_port) const {
756 ERR_FAIL_COND_V(!is_open(), FAILED);
757
758 struct sockaddr_storage saddr;
759 socklen_t len = sizeof(saddr);
760 if (getsockname(_sock, (struct sockaddr *)&saddr, &len) != 0) {
761 _get_socket_error();
762 print_verbose("Error when reading local socket address.");
763 return FAILED;
764 }
765 _set_ip_port(&saddr, r_ip, r_port);
766 return OK;
767}
768
769Ref<NetSocket> NetSocketPosix::accept(IPAddress &r_ip, uint16_t &r_port) {
770 Ref<NetSocket> out;
771 ERR_FAIL_COND_V(!is_open(), out);
772
773 struct sockaddr_storage their_addr;
774 socklen_t size = sizeof(their_addr);
775 SOCKET_TYPE fd = ::accept(_sock, (struct sockaddr *)&their_addr, &size);
776 if (fd == SOCK_EMPTY) {
777 _get_socket_error();
778 print_verbose("Error when accepting socket connection.");
779 return out;
780 }
781
782 _set_ip_port(&their_addr, &r_ip, &r_port);
783
784 NetSocketPosix *ns = memnew(NetSocketPosix);
785 ns->_set_socket(fd, _ip_type, _is_stream);
786 ns->set_blocking_enabled(false);
787 return Ref<NetSocket>(ns);
788}
789
790Error NetSocketPosix::join_multicast_group(const IPAddress &p_multi_address, String p_if_name) {
791 return _change_multicast_group(p_multi_address, p_if_name, true);
792}
793
794Error NetSocketPosix::leave_multicast_group(const IPAddress &p_multi_address, String p_if_name) {
795 return _change_multicast_group(p_multi_address, p_if_name, false);
796}
797
798#endif // UNIX_SOCKET_UNAVAILABLE
799