net_socket_posix.cpp 23 KB

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