net_socket_posix.cpp 21 KB

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