net_socket_posix.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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. #ifdef __HAIKU__
  43. #include <fcntl.h>
  44. #else
  45. #include <sys/fcntl.h>
  46. #endif
  47. #else
  48. #include <sys/ioctl.h>
  49. #endif
  50. #include <netinet/in.h>
  51. #include <sys/socket.h>
  52. #ifdef JAVASCRIPT_ENABLED
  53. #include <arpa/inet.h>
  54. #endif
  55. #include <netinet/tcp.h>
  56. #if defined(OSX_ENABLED) || defined(IPHONE_ENABLED)
  57. #define MSG_NOSIGNAL SO_NOSIGPIPE
  58. #endif
  59. // Some custom defines to minimize ifdefs
  60. #define SOCK_EMPTY -1
  61. #define SOCK_BUF(x) x
  62. #define SOCK_CBUF(x) x
  63. #define SOCK_IOCTL ioctl
  64. #define SOCK_POLL ::poll
  65. #define SOCK_CLOSE ::close
  66. /* Windows */
  67. #elif defined(WINDOWS_ENABLED)
  68. #include <winsock2.h>
  69. #include <ws2tcpip.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_POLL WSAPoll
  76. #define SOCK_CLOSE closesocket
  77. // Windows doesn't have this flag
  78. #ifndef MSG_NOSIGNAL
  79. #define MSG_NOSIGNAL 0
  80. #endif
  81. #endif
  82. static size_t _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_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. copymem(&addr4->sin_addr.s_addr, p_ip.get_ipv4(), 16);
  108. return sizeof(sockaddr_in);
  109. }
  110. }
  111. static void _set_ip_port(IP_Address &r_ip, uint16_t &r_port, struct sockaddr_storage *p_addr) {
  112. if (p_addr->ss_family == AF_INET) {
  113. struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
  114. r_ip.set_ipv4((uint8_t *)&(addr4->sin_addr.s_addr));
  115. r_port = ntohs(addr4->sin_port);
  116. } else if (p_addr->ss_family == AF_INET6) {
  117. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
  118. r_ip.set_ipv6(addr6->sin6_addr.s6_addr);
  119. r_port = ntohs(addr6->sin6_port);
  120. };
  121. }
  122. NetSocket *NetSocketPosix::_create_func() {
  123. return memnew(NetSocketPosix);
  124. }
  125. void NetSocketPosix::make_default() {
  126. #if defined(WINDOWS_ENABLED)
  127. if (_create == NULL) {
  128. WSADATA data;
  129. WSAStartup(MAKEWORD(2, 2), &data);
  130. }
  131. #endif
  132. _create = _create_func;
  133. }
  134. void NetSocketPosix::cleanup() {
  135. #if defined(WINDOWS_ENABLED)
  136. if (_create != NULL) {
  137. WSACleanup();
  138. }
  139. _create = NULL;
  140. #endif
  141. }
  142. NetSocketPosix::NetSocketPosix() {
  143. _sock = SOCK_EMPTY;
  144. _ip_type = IP::TYPE_NONE;
  145. _is_stream = false;
  146. }
  147. NetSocketPosix::~NetSocketPosix() {
  148. close();
  149. }
  150. NetSocketPosix::NetError NetSocketPosix::_get_socket_error() {
  151. #if defined(WINDOWS_ENABLED)
  152. int err = WSAGetLastError();
  153. if (err == WSAEISCONN)
  154. return ERR_NET_IS_CONNECTED;
  155. if (err == WSAEINPROGRESS || err == WSAEALREADY)
  156. return ERR_NET_IN_PROGRESS;
  157. if (err == WSAEWOULDBLOCK)
  158. return ERR_NET_WOULD_BLOCK;
  159. ERR_PRINTS("Socket error: " + itos(err));
  160. return ERR_NET_OTHER;
  161. #else
  162. if (errno == EISCONN)
  163. return ERR_NET_IS_CONNECTED;
  164. if (errno == EINPROGRESS || errno == EALREADY)
  165. return ERR_NET_IN_PROGRESS;
  166. if (errno == EAGAIN || errno == EWOULDBLOCK)
  167. return ERR_NET_WOULD_BLOCK;
  168. ERR_PRINTS("Socket error: " + itos(errno));
  169. return ERR_NET_OTHER;
  170. #endif
  171. }
  172. bool NetSocketPosix::_can_use_ip(const IP_Address p_ip, const bool p_for_bind) const {
  173. if (p_for_bind && !(p_ip.is_valid() || p_ip.is_wildcard())) {
  174. return false;
  175. } else if (!p_for_bind && !p_ip.is_valid()) {
  176. return false;
  177. }
  178. // Check if socket support this IP type.
  179. IP::Type type = p_ip.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
  180. if (_ip_type != IP::TYPE_ANY && !p_ip.is_wildcard() && _ip_type != type) {
  181. return false;
  182. }
  183. return true;
  184. }
  185. void NetSocketPosix::_set_socket(SOCKET_TYPE p_sock, IP::Type p_ip_type, bool p_is_stream) {
  186. _sock = p_sock;
  187. _ip_type = p_ip_type;
  188. _is_stream = p_is_stream;
  189. }
  190. Error NetSocketPosix::open(Type p_sock_type, IP::Type &ip_type) {
  191. ERR_FAIL_COND_V(is_open(), ERR_ALREADY_IN_USE);
  192. ERR_FAIL_COND_V(ip_type > IP::TYPE_ANY || ip_type < IP::TYPE_NONE, ERR_INVALID_PARAMETER);
  193. #if defined(__OpenBSD__)
  194. // OpenBSD does not support dual stacking, fallback to IPv4 only.
  195. if (ip_type == IP::TYPE_ANY)
  196. ip_type = IP::TYPE_IPV4;
  197. #endif
  198. int family = ip_type == IP::TYPE_IPV4 ? AF_INET : AF_INET6;
  199. int protocol = p_sock_type == TYPE_TCP ? IPPROTO_TCP : IPPROTO_UDP;
  200. int type = p_sock_type == TYPE_TCP ? SOCK_STREAM : SOCK_DGRAM;
  201. _sock = socket(family, type, protocol);
  202. if (_sock == SOCK_EMPTY && ip_type == IP::TYPE_ANY) {
  203. // Careful here, changing the referenced parameter so the caller knows that we are using an IPv4 socket
  204. // in place of a dual stack one, and further calls to _set_sock_addr will work as expected.
  205. ip_type = IP::TYPE_IPV4;
  206. family = AF_INET;
  207. _sock = socket(family, type, protocol);
  208. }
  209. ERR_FAIL_COND_V(_sock == SOCK_EMPTY, FAILED);
  210. _ip_type = ip_type;
  211. if (family == AF_INET6) {
  212. // Select IPv4 over IPv6 mapping
  213. set_ipv6_only_enabled(ip_type != IP::TYPE_ANY);
  214. }
  215. if (protocol == IPPROTO_UDP && ip_type != IP::TYPE_IPV6) {
  216. // Enable broadcasting for UDP sockets if it's not IPv6 only (IPv6 has no broadcast option).
  217. set_broadcasting_enabled(true);
  218. }
  219. _is_stream = p_sock_type == TYPE_TCP;
  220. return OK;
  221. }
  222. void NetSocketPosix::close() {
  223. if (_sock != SOCK_EMPTY)
  224. SOCK_CLOSE(_sock);
  225. _sock = SOCK_EMPTY;
  226. _ip_type = IP::TYPE_NONE;
  227. _is_stream = false;
  228. }
  229. Error NetSocketPosix::bind(IP_Address p_addr, uint16_t p_port) {
  230. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  231. ERR_FAIL_COND_V(!_can_use_ip(p_addr, true), ERR_INVALID_PARAMETER);
  232. sockaddr_storage addr;
  233. size_t addr_size = _set_addr_storage(&addr, p_addr, p_port, _ip_type);
  234. if (::bind(_sock, (struct sockaddr *)&addr, addr_size) == SOCK_EMPTY) {
  235. close();
  236. ERR_FAIL_V(ERR_UNAVAILABLE);
  237. }
  238. return OK;
  239. }
  240. Error NetSocketPosix::listen(int p_max_pending) {
  241. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  242. if (::listen(_sock, p_max_pending) == SOCK_EMPTY) {
  243. close();
  244. ERR_FAIL_V(FAILED);
  245. };
  246. return OK;
  247. }
  248. Error NetSocketPosix::connect_to_host(IP_Address p_host, uint16_t p_port) {
  249. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  250. ERR_FAIL_COND_V(!_can_use_ip(p_host, false), ERR_INVALID_PARAMETER);
  251. struct sockaddr_storage addr;
  252. size_t addr_size = _set_addr_storage(&addr, p_host, p_port, _ip_type);
  253. if (::connect(_sock, (struct sockaddr *)&addr, addr_size) == SOCK_EMPTY) {
  254. NetError err = _get_socket_error();
  255. switch (err) {
  256. // We are already connected
  257. case ERR_NET_IS_CONNECTED:
  258. return OK;
  259. // Still waiting to connect, try again in a while
  260. case ERR_NET_WOULD_BLOCK:
  261. case ERR_NET_IN_PROGRESS:
  262. return ERR_BUSY;
  263. default:
  264. ERR_PRINT("Connection to remote host failed!");
  265. close();
  266. return FAILED;
  267. }
  268. }
  269. return OK;
  270. }
  271. Error NetSocketPosix::poll(PollType p_type, int timeout) const {
  272. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  273. struct pollfd pfd;
  274. pfd.fd = _sock;
  275. pfd.events = POLLIN;
  276. pfd.revents = 0;
  277. switch (p_type) {
  278. case POLL_TYPE_IN:
  279. pfd.events = POLLIN;
  280. break;
  281. case POLL_TYPE_OUT:
  282. pfd.events = POLLOUT;
  283. break;
  284. case POLL_TYPE_IN_OUT:
  285. pfd.events = POLLOUT || POLLIN;
  286. }
  287. int ret = SOCK_POLL(&pfd, 1, timeout);
  288. ERR_FAIL_COND_V(ret < 0, FAILED);
  289. if (ret == 0)
  290. return ERR_BUSY;
  291. return OK;
  292. }
  293. Error NetSocketPosix::recv(uint8_t *p_buffer, int p_len, int &r_read) {
  294. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  295. r_read = ::recv(_sock, SOCK_BUF(p_buffer), p_len, 0);
  296. if (r_read < 0) {
  297. NetError err = _get_socket_error();
  298. if (err == ERR_NET_WOULD_BLOCK)
  299. return ERR_BUSY;
  300. return FAILED;
  301. }
  302. return OK;
  303. }
  304. Error NetSocketPosix::recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IP_Address &r_ip, uint16_t &r_port) {
  305. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  306. struct sockaddr_storage from;
  307. socklen_t len = sizeof(struct sockaddr_storage);
  308. memset(&from, 0, len);
  309. r_read = ::recvfrom(_sock, SOCK_BUF(p_buffer), p_len, 0, (struct sockaddr *)&from, &len);
  310. if (r_read < 0) {
  311. NetError err = _get_socket_error();
  312. if (err == ERR_NET_WOULD_BLOCK)
  313. return ERR_BUSY;
  314. return FAILED;
  315. }
  316. if (from.ss_family == AF_INET) {
  317. struct sockaddr_in *sin_from = (struct sockaddr_in *)&from;
  318. r_ip.set_ipv4((uint8_t *)&sin_from->sin_addr);
  319. r_port = ntohs(sin_from->sin_port);
  320. } else if (from.ss_family == AF_INET6) {
  321. struct sockaddr_in6 *s6_from = (struct sockaddr_in6 *)&from;
  322. r_ip.set_ipv6((uint8_t *)&s6_from->sin6_addr);
  323. r_port = ntohs(s6_from->sin6_port);
  324. } else {
  325. // Unsupported socket family, should never happen.
  326. ERR_FAIL_V(FAILED);
  327. }
  328. return OK;
  329. }
  330. Error NetSocketPosix::send(const uint8_t *p_buffer, int p_len, int &r_sent) {
  331. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  332. int flags = 0;
  333. if (_is_stream)
  334. flags = MSG_NOSIGNAL;
  335. r_sent = ::send(_sock, SOCK_CBUF(p_buffer), p_len, flags);
  336. if (r_sent < 0) {
  337. NetError err = _get_socket_error();
  338. if (err == ERR_NET_WOULD_BLOCK)
  339. return ERR_BUSY;
  340. return FAILED;
  341. }
  342. return OK;
  343. }
  344. Error NetSocketPosix::sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IP_Address p_ip, uint16_t p_port) {
  345. ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
  346. struct sockaddr_storage addr;
  347. size_t addr_size = _set_addr_storage(&addr, p_ip, p_port, _ip_type);
  348. r_sent = ::sendto(_sock, SOCK_CBUF(p_buffer), p_len, 0, (struct sockaddr *)&addr, addr_size);
  349. if (r_sent < 0) {
  350. NetError err = _get_socket_error();
  351. if (err == ERR_NET_WOULD_BLOCK)
  352. return ERR_BUSY;
  353. return FAILED;
  354. }
  355. return OK;
  356. }
  357. void NetSocketPosix::set_broadcasting_enabled(bool p_enabled) {
  358. ERR_FAIL_COND(!is_open());
  359. // IPv6 has no broadcast support.
  360. ERR_FAIL_COND(_ip_type == IP::TYPE_IPV6);
  361. int par = p_enabled ? 1 : 0;
  362. if (setsockopt(_sock, SOL_SOCKET, SO_BROADCAST, SOCK_CBUF(&par), sizeof(int)) != 0) {
  363. WARN_PRINT("Unable to change broadcast setting");
  364. }
  365. }
  366. void NetSocketPosix::set_blocking_enabled(bool p_enabled) {
  367. ERR_FAIL_COND(!is_open());
  368. int ret = 0;
  369. #if defined(WINDOWS_ENABLED) || defined(NO_FCNTL)
  370. unsigned long par = p_enabled ? 0 : 1;
  371. ret = SOCK_IOCTL(_sock, FIONBIO, &par);
  372. #else
  373. int opts = fcntl(_sock, F_GETFL);
  374. if (p_enabled)
  375. ret = fcntl(_sock, F_SETFL, opts & ~O_NONBLOCK);
  376. else
  377. ret = fcntl(_sock, F_SETFL, opts | O_NONBLOCK);
  378. #endif
  379. if (ret != 0)
  380. WARN_PRINT("Unable to change non-block mode");
  381. }
  382. void NetSocketPosix::set_ipv6_only_enabled(bool p_enabled) {
  383. ERR_FAIL_COND(!is_open());
  384. // This option is only avaiable in IPv6 sockets.
  385. ERR_FAIL_COND(_ip_type == IP::TYPE_IPV4);
  386. int par = p_enabled ? 1 : 0;
  387. if (setsockopt(_sock, IPPROTO_IPV6, IPV6_V6ONLY, SOCK_CBUF(&par), sizeof(int)) != 0) {
  388. WARN_PRINT("Unable to change IPv4 address mapping over IPv6 option");
  389. }
  390. }
  391. void NetSocketPosix::set_tcp_no_delay_enabled(bool p_enabled) {
  392. ERR_FAIL_COND(!is_open());
  393. ERR_FAIL_COND(_ip_type != TYPE_TCP);
  394. int par = p_enabled ? 1 : 0;
  395. if (setsockopt(_sock, IPPROTO_TCP, TCP_NODELAY, SOCK_CBUF(&par), sizeof(int)) < 0) {
  396. ERR_PRINT("Unable to set TCP no delay option");
  397. }
  398. }
  399. void NetSocketPosix::set_reuse_address_enabled(bool p_enabled) {
  400. ERR_FAIL_COND(!is_open());
  401. int par = p_enabled ? 1 : 0;
  402. if (setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, SOCK_CBUF(&par), sizeof(int)) < 0) {
  403. WARN_PRINT("Unable to set socket REUSEADDR option!");
  404. }
  405. }
  406. void NetSocketPosix::set_reuse_port_enabled(bool p_enabled) {
  407. // Windows does not have this option, as it is always ON when setting REUSEADDR.
  408. #ifndef WINDOWS_ENABLED
  409. ERR_FAIL_COND(!is_open());
  410. int par = p_enabled ? 1 : 0;
  411. if (setsockopt(_sock, SOL_SOCKET, SO_REUSEPORT, SOCK_CBUF(&par), sizeof(int)) < 0) {
  412. WARN_PRINT("Unable to set socket REUSEPORT option!");
  413. }
  414. #endif
  415. }
  416. bool NetSocketPosix::is_open() const {
  417. return _sock != SOCK_EMPTY;
  418. }
  419. int NetSocketPosix::get_available_bytes() const {
  420. ERR_FAIL_COND_V(_sock == SOCK_EMPTY, -1);
  421. unsigned long len;
  422. int ret = SOCK_IOCTL(_sock, FIONREAD, &len);
  423. ERR_FAIL_COND_V(ret == -1, 0);
  424. return len;
  425. }
  426. Ref<NetSocket> NetSocketPosix::accept(IP_Address &r_ip, uint16_t &r_port) {
  427. Ref<NetSocket> out;
  428. ERR_FAIL_COND_V(!is_open(), out);
  429. struct sockaddr_storage their_addr;
  430. socklen_t size = sizeof(their_addr);
  431. SOCKET_TYPE fd = ::accept(_sock, (struct sockaddr *)&their_addr, &size);
  432. ERR_FAIL_COND_V(fd == SOCK_EMPTY, out);
  433. _set_ip_port(r_ip, r_port, &their_addr);
  434. NetSocketPosix *ns = memnew(NetSocketPosix);
  435. ns->_set_socket(fd, _ip_type, _is_stream);
  436. ns->set_blocking_enabled(false);
  437. return Ref<NetSocket>(ns);
  438. }