net_socket_posix.cpp 22 KB

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