net_socket_posix.cpp 19 KB

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