net_socket_posix.cpp 20 KB

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