socket.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #define SOCKET_PRIVATE
  6. #include "lib/net/socket.h"
  7. #include "lib/net/address.h"
  8. #include "lib/cc/compat_compiler.h"
  9. #include "lib/lock/compat_mutex.h"
  10. #include "lib/log/torlog.h"
  11. #include "lib/log/util_bug.h"
  12. #ifdef _WIN32
  13. #include <winsock2.h>
  14. #include <windows.h>
  15. #endif
  16. #ifdef HAVE_UNISTD_H
  17. #include <unistd.h>
  18. #endif
  19. #ifdef HAVE_FCNTL_H
  20. #include <fcntl.h>
  21. #endif
  22. #include <stddef.h>
  23. #include <string.h>
  24. /* When set_max_file_sockets() is called, update this with the max file
  25. * descriptor value so we can use it to check the limit when opening a new
  26. * socket. Default value is what Debian sets as the default hard limit. */
  27. static int max_sockets = 1024;
  28. /** Return the maximum number of allowed sockets. */
  29. int
  30. get_max_sockets(void)
  31. {
  32. return max_sockets;
  33. }
  34. /** Set the maximum number of allowed sockets to <b>n</b> */
  35. void
  36. set_max_sockets(int n)
  37. {
  38. max_sockets = n;
  39. }
  40. #undef DEBUG_SOCKET_COUNTING
  41. #ifdef DEBUG_SOCKET_COUNTING
  42. #include "lib/container/bitarray.h"
  43. /** A bitarray of all fds that should be passed to tor_socket_close(). Only
  44. * used if DEBUG_SOCKET_COUNTING is defined. */
  45. static bitarray_t *open_sockets = NULL;
  46. /** The size of <b>open_sockets</b>, in bits. */
  47. static int max_socket = -1;
  48. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  49. /** Count of number of sockets currently open. (Undercounts sockets opened by
  50. * eventdns and libevent.) */
  51. static int n_sockets_open = 0;
  52. /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
  53. static tor_mutex_t *socket_accounting_mutex = NULL;
  54. /** Helper: acquire the socket accounting lock. */
  55. static inline void
  56. socket_accounting_lock(void)
  57. {
  58. if (PREDICT_UNLIKELY(!socket_accounting_mutex))
  59. socket_accounting_mutex = tor_mutex_new();
  60. tor_mutex_acquire(socket_accounting_mutex);
  61. }
  62. /** Helper: release the socket accounting lock. */
  63. static inline void
  64. socket_accounting_unlock(void)
  65. {
  66. tor_mutex_release(socket_accounting_mutex);
  67. }
  68. /** As close(), but guaranteed to work for sockets across platforms (including
  69. * Windows, where close()ing a socket doesn't work. Returns 0 on success and
  70. * the socket error code on failure. */
  71. int
  72. tor_close_socket_simple(tor_socket_t s)
  73. {
  74. int r = 0;
  75. /* On Windows, you have to call close() on fds returned by open(),
  76. * and closesocket() on fds returned by socket(). On Unix, everything
  77. * gets close()'d. We abstract this difference by always using
  78. * tor_close_socket to close sockets, and always using close() on
  79. * files.
  80. */
  81. #if defined(_WIN32)
  82. r = closesocket(s);
  83. #else
  84. r = close(s);
  85. #endif
  86. if (r != 0) {
  87. int err = tor_socket_errno(-1);
  88. log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
  89. return err;
  90. }
  91. return r;
  92. }
  93. /** As tor_close_socket_simple(), but keeps track of the number
  94. * of open sockets. Returns 0 on success, -1 on failure. */
  95. MOCK_IMPL(int,
  96. tor_close_socket,(tor_socket_t s))
  97. {
  98. int r = tor_close_socket_simple(s);
  99. socket_accounting_lock();
  100. #ifdef DEBUG_SOCKET_COUNTING
  101. if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
  102. log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
  103. "socket(), or that was already closed or something.", s);
  104. } else {
  105. tor_assert(open_sockets && s <= max_socket);
  106. bitarray_clear(open_sockets, s);
  107. }
  108. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  109. if (r == 0) {
  110. --n_sockets_open;
  111. } else {
  112. #ifdef _WIN32
  113. if (r != WSAENOTSOCK)
  114. --n_sockets_open;
  115. #else
  116. if (r != EBADF)
  117. --n_sockets_open; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
  118. #endif /* defined(_WIN32) */
  119. r = -1;
  120. }
  121. tor_assert_nonfatal(n_sockets_open >= 0);
  122. socket_accounting_unlock();
  123. return r;
  124. }
  125. /** @{ */
  126. #ifdef DEBUG_SOCKET_COUNTING
  127. /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
  128. * now an open socket. */
  129. static inline void
  130. mark_socket_open(tor_socket_t s)
  131. {
  132. /* XXXX This bitarray business will NOT work on windows: sockets aren't
  133. small ints there. */
  134. if (s > max_socket) {
  135. if (max_socket == -1) {
  136. open_sockets = bitarray_init_zero(s+128);
  137. max_socket = s+128;
  138. } else {
  139. open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
  140. max_socket = s+128;
  141. }
  142. }
  143. if (bitarray_is_set(open_sockets, s)) {
  144. log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
  145. "gave it to me!", s);
  146. }
  147. bitarray_set(open_sockets, s);
  148. }
  149. #else /* !(defined(DEBUG_SOCKET_COUNTING)) */
  150. #define mark_socket_open(s) ((void) (s))
  151. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  152. /** @} */
  153. /** As socket(), but counts the number of open sockets. */
  154. MOCK_IMPL(tor_socket_t,
  155. tor_open_socket,(int domain, int type, int protocol))
  156. {
  157. return tor_open_socket_with_extensions(domain, type, protocol, 1, 0);
  158. }
  159. /** Mockable wrapper for connect(). */
  160. MOCK_IMPL(tor_socket_t,
  161. tor_connect_socket,(tor_socket_t sock, const struct sockaddr *address,
  162. socklen_t address_len))
  163. {
  164. return connect(sock,address,address_len);
  165. }
  166. /** As socket(), but creates a nonblocking socket and
  167. * counts the number of open sockets. */
  168. tor_socket_t
  169. tor_open_socket_nonblocking(int domain, int type, int protocol)
  170. {
  171. return tor_open_socket_with_extensions(domain, type, protocol, 1, 1);
  172. }
  173. /** As socket(), but counts the number of open sockets and handles
  174. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  175. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  176. * if the corresponding extension should be used.*/
  177. tor_socket_t
  178. tor_open_socket_with_extensions(int domain, int type, int protocol,
  179. int cloexec, int nonblock)
  180. {
  181. tor_socket_t s;
  182. /* We are about to create a new file descriptor so make sure we have
  183. * enough of them. */
  184. if (get_n_open_sockets() >= max_sockets - 1) {
  185. #ifdef _WIN32
  186. WSASetLastError(WSAEMFILE);
  187. #else
  188. errno = EMFILE;
  189. #endif
  190. return TOR_INVALID_SOCKET;
  191. }
  192. #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
  193. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  194. (nonblock ? SOCK_NONBLOCK : 0);
  195. s = socket(domain, type|ext_flags, protocol);
  196. if (SOCKET_OK(s))
  197. goto socket_ok;
  198. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  199. * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
  200. * support, we are running on one without. */
  201. if (errno != EINVAL)
  202. return s;
  203. #endif /* defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK) */
  204. s = socket(domain, type, protocol);
  205. if (! SOCKET_OK(s))
  206. return s;
  207. #if defined(FD_CLOEXEC)
  208. if (cloexec) {
  209. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  210. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  211. tor_close_socket_simple(s);
  212. return TOR_INVALID_SOCKET;
  213. }
  214. }
  215. #else /* !(defined(FD_CLOEXEC)) */
  216. (void)cloexec;
  217. #endif /* defined(FD_CLOEXEC) */
  218. if (nonblock) {
  219. if (set_socket_nonblocking(s) == -1) {
  220. tor_close_socket_simple(s);
  221. return TOR_INVALID_SOCKET;
  222. }
  223. }
  224. goto socket_ok; /* So that socket_ok will not be unused. */
  225. socket_ok:
  226. tor_take_socket_ownership(s);
  227. return s;
  228. }
  229. /**
  230. * For socket accounting: remember that we are the owner of the socket
  231. * <b>s</b>. This will prevent us from overallocating sockets, and prevent us
  232. * from asserting later when we close the socket <b>s</b>.
  233. */
  234. void
  235. tor_take_socket_ownership(tor_socket_t s)
  236. {
  237. socket_accounting_lock();
  238. ++n_sockets_open;
  239. mark_socket_open(s);
  240. socket_accounting_unlock();
  241. }
  242. /** As accept(), but counts the number of open sockets. */
  243. tor_socket_t
  244. tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
  245. {
  246. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0);
  247. }
  248. /** As accept(), but returns a nonblocking socket and
  249. * counts the number of open sockets. */
  250. tor_socket_t
  251. tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr,
  252. socklen_t *len)
  253. {
  254. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1);
  255. }
  256. /** As accept(), but counts the number of open sockets and handles
  257. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  258. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  259. * if the corresponding extension should be used.*/
  260. tor_socket_t
  261. tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr,
  262. socklen_t *len, int cloexec, int nonblock)
  263. {
  264. tor_socket_t s;
  265. /* We are about to create a new file descriptor so make sure we have
  266. * enough of them. */
  267. if (get_n_open_sockets() >= max_sockets - 1) {
  268. #ifdef _WIN32
  269. WSASetLastError(WSAEMFILE);
  270. #else
  271. errno = EMFILE;
  272. #endif
  273. return TOR_INVALID_SOCKET;
  274. }
  275. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) \
  276. && defined(SOCK_NONBLOCK)
  277. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  278. (nonblock ? SOCK_NONBLOCK : 0);
  279. s = accept4(sockfd, addr, len, ext_flags);
  280. if (SOCKET_OK(s))
  281. goto socket_ok;
  282. /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
  283. * even though we were built on a system with accept4 support, we
  284. * are running on one without. Also, check for EINVAL, which indicates that
  285. * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
  286. if (errno != EINVAL && errno != ENOSYS)
  287. return s;
  288. #endif /* defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) ... */
  289. s = accept(sockfd, addr, len);
  290. if (!SOCKET_OK(s))
  291. return s;
  292. #if defined(FD_CLOEXEC)
  293. if (cloexec) {
  294. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  295. log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno));
  296. tor_close_socket_simple(s);
  297. return TOR_INVALID_SOCKET;
  298. }
  299. }
  300. #else /* !(defined(FD_CLOEXEC)) */
  301. (void)cloexec;
  302. #endif /* defined(FD_CLOEXEC) */
  303. if (nonblock) {
  304. if (set_socket_nonblocking(s) == -1) {
  305. tor_close_socket_simple(s);
  306. return TOR_INVALID_SOCKET;
  307. }
  308. }
  309. goto socket_ok; /* So that socket_ok will not be unused. */
  310. socket_ok:
  311. tor_take_socket_ownership(s);
  312. return s;
  313. }
  314. /** Return the number of sockets we currently have opened. */
  315. int
  316. get_n_open_sockets(void)
  317. {
  318. int n;
  319. socket_accounting_lock();
  320. n = n_sockets_open;
  321. socket_accounting_unlock();
  322. return n;
  323. }
  324. /**
  325. * Allocate a pair of connected sockets. (Like socketpair(family,
  326. * type,protocol,fd), but works on systems that don't have
  327. * socketpair.)
  328. *
  329. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  330. *
  331. * Note that on systems without socketpair, this call will fail if
  332. * localhost is inaccessible (for example, if the networking
  333. * stack is down). And even if it succeeds, the socket pair will not
  334. * be able to read while localhost is down later (the socket pair may
  335. * even close, depending on OS-specific timeouts).
  336. *
  337. * Returns 0 on success and -errno on failure; do not rely on the value
  338. * of errno or WSAGetLastError().
  339. **/
  340. /* It would be nicer just to set errno, but that won't work for windows. */
  341. int
  342. tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  343. {
  344. //don't use win32 socketpairs (they are always bad)
  345. #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  346. int r;
  347. #ifdef SOCK_CLOEXEC
  348. r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd);
  349. if (r == 0)
  350. goto sockets_ok;
  351. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  352. * even though we were built on a system with SOCK_CLOEXEC support, we
  353. * are running on one without. */
  354. if (errno != EINVAL)
  355. return -errno;
  356. #endif /* defined(SOCK_CLOEXEC) */
  357. r = socketpair(family, type, protocol, fd);
  358. if (r < 0)
  359. return -errno;
  360. #if defined(FD_CLOEXEC)
  361. if (SOCKET_OK(fd[0])) {
  362. r = fcntl(fd[0], F_SETFD, FD_CLOEXEC);
  363. if (r == -1) {
  364. close(fd[0]);
  365. close(fd[1]);
  366. return -errno;
  367. }
  368. }
  369. if (SOCKET_OK(fd[1])) {
  370. r = fcntl(fd[1], F_SETFD, FD_CLOEXEC);
  371. if (r == -1) {
  372. close(fd[0]);
  373. close(fd[1]);
  374. return -errno;
  375. }
  376. }
  377. #endif /* defined(FD_CLOEXEC) */
  378. goto sockets_ok; /* So that sockets_ok will not be unused. */
  379. sockets_ok:
  380. socket_accounting_lock();
  381. if (SOCKET_OK(fd[0])) {
  382. ++n_sockets_open;
  383. mark_socket_open(fd[0]);
  384. }
  385. if (SOCKET_OK(fd[1])) {
  386. ++n_sockets_open;
  387. mark_socket_open(fd[1]);
  388. }
  389. socket_accounting_unlock();
  390. return 0;
  391. #else /* !(defined(HAVE_SOCKETPAIR) && !defined(_WIN32)) */
  392. return tor_ersatz_socketpair(family, type, protocol, fd);
  393. #endif /* defined(HAVE_SOCKETPAIR) && !defined(_WIN32) */
  394. }
  395. #ifdef NEED_ERSATZ_SOCKETPAIR
  396. static inline socklen_t
  397. SIZEOF_SOCKADDR(int domain)
  398. {
  399. switch (domain) {
  400. case AF_INET:
  401. return sizeof(struct sockaddr_in);
  402. case AF_INET6:
  403. return sizeof(struct sockaddr_in6);
  404. default:
  405. return 0;
  406. }
  407. }
  408. /**
  409. * Helper used to implement socketpair on systems that lack it, by
  410. * making a direct connection to localhost.
  411. */
  412. STATIC int
  413. tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  414. {
  415. /* This socketpair does not work when localhost is down. So
  416. * it's really not the same thing at all. But it's close enough
  417. * for now, and really, when localhost is down sometimes, we
  418. * have other problems too.
  419. */
  420. tor_socket_t listener = TOR_INVALID_SOCKET;
  421. tor_socket_t connector = TOR_INVALID_SOCKET;
  422. tor_socket_t acceptor = TOR_INVALID_SOCKET;
  423. tor_addr_t listen_tor_addr;
  424. struct sockaddr_storage connect_addr_ss, listen_addr_ss;
  425. struct sockaddr *listen_addr = (struct sockaddr *) &listen_addr_ss;
  426. uint16_t listen_port = 0;
  427. tor_addr_t connect_tor_addr;
  428. uint16_t connect_port = 0;
  429. struct sockaddr *connect_addr = (struct sockaddr *) &connect_addr_ss;
  430. socklen_t size;
  431. int saved_errno = -1;
  432. int ersatz_domain = AF_INET;
  433. memset(&connect_tor_addr, 0, sizeof(connect_tor_addr));
  434. memset(&connect_addr_ss, 0, sizeof(connect_addr_ss));
  435. memset(&listen_tor_addr, 0, sizeof(listen_tor_addr));
  436. memset(&listen_addr_ss, 0, sizeof(listen_addr_ss));
  437. if (protocol
  438. #ifdef AF_UNIX
  439. || family != AF_UNIX
  440. #endif
  441. ) {
  442. #ifdef _WIN32
  443. return -WSAEAFNOSUPPORT;
  444. #else
  445. return -EAFNOSUPPORT;
  446. #endif
  447. }
  448. if (!fd) {
  449. return -EINVAL;
  450. }
  451. listener = tor_open_socket(ersatz_domain, type, 0);
  452. if (!SOCKET_OK(listener)) {
  453. int first_errno = tor_socket_errno(-1);
  454. if (first_errno == SOCK_ERRNO(EPROTONOSUPPORT)
  455. && ersatz_domain == AF_INET) {
  456. /* Assume we're on an IPv6-only system */
  457. ersatz_domain = AF_INET6;
  458. listener = tor_open_socket(ersatz_domain, type, 0);
  459. if (!SOCKET_OK(listener)) {
  460. /* Keep the previous behaviour, which was to return the IPv4 error.
  461. * (This may be less informative on IPv6-only systems.)
  462. * XX/teor - is there a better way to decide which errno to return?
  463. * (I doubt we care much either way, once there is an error.)
  464. */
  465. return -first_errno;
  466. }
  467. }
  468. }
  469. /* If there is no 127.0.0.1 or ::1, this will and must fail. Otherwise, we
  470. * risk exposing a socketpair on a routable IP address. (Some BSD jails
  471. * use a routable address for localhost. Fortunately, they have the real
  472. * AF_UNIX socketpair.) */
  473. if (ersatz_domain == AF_INET) {
  474. tor_addr_from_ipv4h(&listen_tor_addr, INADDR_LOOPBACK);
  475. } else {
  476. tor_addr_parse(&listen_tor_addr, "[::1]");
  477. }
  478. tor_assert(tor_addr_is_loopback(&listen_tor_addr));
  479. size = tor_addr_to_sockaddr(&listen_tor_addr,
  480. 0 /* kernel chooses port. */,
  481. listen_addr,
  482. sizeof(listen_addr_ss));
  483. if (bind(listener, listen_addr, size) == -1)
  484. goto tidy_up_and_fail;
  485. if (listen(listener, 1) == -1)
  486. goto tidy_up_and_fail;
  487. connector = tor_open_socket(ersatz_domain, type, 0);
  488. if (!SOCKET_OK(connector))
  489. goto tidy_up_and_fail;
  490. /* We want to find out the port number to connect to. */
  491. size = sizeof(connect_addr_ss);
  492. if (getsockname(listener, connect_addr, &size) == -1)
  493. goto tidy_up_and_fail;
  494. if (size != SIZEOF_SOCKADDR (connect_addr->sa_family))
  495. goto abort_tidy_up_and_fail;
  496. if (connect(connector, connect_addr, size) == -1)
  497. goto tidy_up_and_fail;
  498. size = sizeof(listen_addr_ss);
  499. acceptor = tor_accept_socket(listener, listen_addr, &size);
  500. if (!SOCKET_OK(acceptor))
  501. goto tidy_up_and_fail;
  502. if (size != SIZEOF_SOCKADDR(listen_addr->sa_family))
  503. goto abort_tidy_up_and_fail;
  504. /* Now check we are talking to ourself by matching port and host on the
  505. two sockets. */
  506. if (getsockname(connector, connect_addr, &size) == -1)
  507. goto tidy_up_and_fail;
  508. /* Set *_tor_addr and *_port to the address and port that was used */
  509. tor_addr_from_sockaddr(&listen_tor_addr, listen_addr, &listen_port);
  510. tor_addr_from_sockaddr(&connect_tor_addr, connect_addr, &connect_port);
  511. if (size != SIZEOF_SOCKADDR (connect_addr->sa_family)
  512. || tor_addr_compare(&listen_tor_addr, &connect_tor_addr, CMP_SEMANTIC)
  513. || listen_port != connect_port) {
  514. goto abort_tidy_up_and_fail;
  515. }
  516. tor_close_socket(listener);
  517. fd[0] = connector;
  518. fd[1] = acceptor;
  519. return 0;
  520. abort_tidy_up_and_fail:
  521. #ifdef _WIN32
  522. saved_errno = WSAECONNABORTED;
  523. #else
  524. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  525. #endif
  526. tidy_up_and_fail:
  527. if (saved_errno < 0)
  528. saved_errno = errno;
  529. if (SOCKET_OK(listener))
  530. tor_close_socket(listener);
  531. if (SOCKET_OK(connector))
  532. tor_close_socket(connector);
  533. if (SOCKET_OK(acceptor))
  534. tor_close_socket(acceptor);
  535. return -saved_errno;
  536. }
  537. #endif /* defined(NEED_ERSATZ_SOCKETPAIR) */
  538. /** Mockable wrapper for getsockname(). */
  539. MOCK_IMPL(int,
  540. tor_getsockname,(tor_socket_t sock, struct sockaddr *address,
  541. socklen_t *address_len))
  542. {
  543. return getsockname(sock, address, address_len);
  544. }
  545. /**
  546. * Find the local address associated with the socket <b>sock</b>, and
  547. * place it in *<b>addr_out</b>. Return 0 on success, -1 on failure.
  548. *
  549. * (As tor_getsockname, but instead places the result in a tor_addr_t.) */
  550. int
  551. tor_addr_from_getsockname(struct tor_addr_t *addr_out, tor_socket_t sock)
  552. {
  553. struct sockaddr_storage ss;
  554. socklen_t ss_len = sizeof(ss);
  555. memset(&ss, 0, sizeof(ss));
  556. if (tor_getsockname(sock, (struct sockaddr *) &ss, &ss_len) < 0)
  557. return -1;
  558. return tor_addr_from_sockaddr(addr_out, (struct sockaddr *)&ss, NULL);
  559. }
  560. /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
  561. * on failure.
  562. */
  563. int
  564. set_socket_nonblocking(tor_socket_t sock)
  565. {
  566. #if defined(_WIN32)
  567. unsigned long nonblocking = 1;
  568. ioctlsocket(sock, FIONBIO, (unsigned long*) &nonblocking);
  569. #else
  570. int flags;
  571. flags = fcntl(sock, F_GETFL, 0);
  572. if (flags == -1) {
  573. log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno));
  574. return -1;
  575. }
  576. flags |= O_NONBLOCK;
  577. if (fcntl(sock, F_SETFL, flags) == -1) {
  578. log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno));
  579. return -1;
  580. }
  581. #endif /* defined(_WIN32) */
  582. return 0;
  583. }