socket.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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/err/torerr.h"
  10. #include "lib/lock/compat_mutex.h"
  11. #include "lib/log/torlog.h"
  12. #include "lib/log/util_bug.h"
  13. #ifdef _WIN32
  14. #include <winsock2.h>
  15. #include <windows.h>
  16. #endif
  17. #ifdef HAVE_UNISTD_H
  18. #include <unistd.h>
  19. #endif
  20. #ifdef HAVE_FCNTL_H
  21. #include <fcntl.h>
  22. #endif
  23. #include <stddef.h>
  24. #include <string.h>
  25. /* When set_max_file_sockets() is called, update this with the max file
  26. * descriptor value so we can use it to check the limit when opening a new
  27. * socket. Default value is what Debian sets as the default hard limit. */
  28. static int max_sockets = 1024;
  29. /** Return the maximum number of allowed sockets. */
  30. int
  31. get_max_sockets(void)
  32. {
  33. return max_sockets;
  34. }
  35. /** Set the maximum number of allowed sockets to <b>n</b> */
  36. void
  37. set_max_sockets(int n)
  38. {
  39. max_sockets = n;
  40. }
  41. #undef DEBUG_SOCKET_COUNTING
  42. #ifdef DEBUG_SOCKET_COUNTING
  43. #include "lib/container/bitarray.h"
  44. /** A bitarray of all fds that should be passed to tor_socket_close(). Only
  45. * used if DEBUG_SOCKET_COUNTING is defined. */
  46. static bitarray_t *open_sockets = NULL;
  47. /** The size of <b>open_sockets</b>, in bits. */
  48. static int max_socket = -1;
  49. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  50. /** Count of number of sockets currently open. (Undercounts sockets opened by
  51. * eventdns and libevent.) */
  52. static int n_sockets_open = 0;
  53. /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
  54. static tor_mutex_t *socket_accounting_mutex = NULL;
  55. /** Helper: acquire the socket accounting lock. */
  56. static inline void
  57. socket_accounting_lock(void)
  58. {
  59. if (PREDICT_UNLIKELY(!socket_accounting_mutex))
  60. socket_accounting_mutex = tor_mutex_new();
  61. tor_mutex_acquire(socket_accounting_mutex);
  62. }
  63. /** Helper: release the socket accounting lock. */
  64. static inline void
  65. socket_accounting_unlock(void)
  66. {
  67. tor_mutex_release(socket_accounting_mutex);
  68. }
  69. /** As close(), but guaranteed to work for sockets across platforms (including
  70. * Windows, where close()ing a socket doesn't work. Returns 0 on success and
  71. * the socket error code on failure. */
  72. int
  73. tor_close_socket_simple(tor_socket_t s)
  74. {
  75. int r = 0;
  76. /* On Windows, you have to call close() on fds returned by open(),
  77. * and closesocket() on fds returned by socket(). On Unix, everything
  78. * gets close()'d. We abstract this difference by always using
  79. * tor_close_socket to close sockets, and always using close() on
  80. * files.
  81. */
  82. #if defined(_WIN32)
  83. r = closesocket(s);
  84. #else
  85. r = close(s);
  86. #endif
  87. if (r != 0) {
  88. int err = tor_socket_errno(-1);
  89. log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
  90. return err;
  91. }
  92. return r;
  93. }
  94. /** As tor_close_socket_simple(), but keeps track of the number
  95. * of open sockets. Returns 0 on success, -1 on failure. */
  96. MOCK_IMPL(int,
  97. tor_close_socket,(tor_socket_t s))
  98. {
  99. int r = tor_close_socket_simple(s);
  100. socket_accounting_lock();
  101. #ifdef DEBUG_SOCKET_COUNTING
  102. if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
  103. log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
  104. "socket(), or that was already closed or something.", s);
  105. } else {
  106. tor_assert(open_sockets && s <= max_socket);
  107. bitarray_clear(open_sockets, s);
  108. }
  109. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  110. if (r == 0) {
  111. --n_sockets_open;
  112. } else {
  113. #ifdef _WIN32
  114. if (r != WSAENOTSOCK)
  115. --n_sockets_open;
  116. #else
  117. if (r != EBADF)
  118. --n_sockets_open; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
  119. #endif /* defined(_WIN32) */
  120. r = -1;
  121. }
  122. tor_assert_nonfatal(n_sockets_open >= 0);
  123. socket_accounting_unlock();
  124. return r;
  125. }
  126. /** @{ */
  127. #ifdef DEBUG_SOCKET_COUNTING
  128. /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
  129. * now an open socket. */
  130. static inline void
  131. mark_socket_open(tor_socket_t s)
  132. {
  133. /* XXXX This bitarray business will NOT work on windows: sockets aren't
  134. small ints there. */
  135. if (s > max_socket) {
  136. if (max_socket == -1) {
  137. open_sockets = bitarray_init_zero(s+128);
  138. max_socket = s+128;
  139. } else {
  140. open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
  141. max_socket = s+128;
  142. }
  143. }
  144. if (bitarray_is_set(open_sockets, s)) {
  145. log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
  146. "gave it to me!", s);
  147. }
  148. bitarray_set(open_sockets, s);
  149. }
  150. #else /* !(defined(DEBUG_SOCKET_COUNTING)) */
  151. #define mark_socket_open(s) ((void) (s))
  152. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  153. /** @} */
  154. /** As socket(), but counts the number of open sockets. */
  155. MOCK_IMPL(tor_socket_t,
  156. tor_open_socket,(int domain, int type, int protocol))
  157. {
  158. return tor_open_socket_with_extensions(domain, type, protocol, 1, 0);
  159. }
  160. /** Mockable wrapper for connect(). */
  161. MOCK_IMPL(tor_socket_t,
  162. tor_connect_socket,(tor_socket_t sock, const struct sockaddr *address,
  163. socklen_t address_len))
  164. {
  165. return connect(sock,address,address_len);
  166. }
  167. /** As socket(), but creates a nonblocking socket and
  168. * counts the number of open sockets. */
  169. tor_socket_t
  170. tor_open_socket_nonblocking(int domain, int type, int protocol)
  171. {
  172. return tor_open_socket_with_extensions(domain, type, protocol, 1, 1);
  173. }
  174. /** As socket(), but counts the number of open sockets and handles
  175. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  176. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  177. * if the corresponding extension should be used.*/
  178. tor_socket_t
  179. tor_open_socket_with_extensions(int domain, int type, int protocol,
  180. int cloexec, int nonblock)
  181. {
  182. tor_socket_t s;
  183. /* We are about to create a new file descriptor so make sure we have
  184. * enough of them. */
  185. if (get_n_open_sockets() >= max_sockets - 1) {
  186. #ifdef _WIN32
  187. WSASetLastError(WSAEMFILE);
  188. #else
  189. errno = EMFILE;
  190. #endif
  191. return TOR_INVALID_SOCKET;
  192. }
  193. #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
  194. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  195. (nonblock ? SOCK_NONBLOCK : 0);
  196. s = socket(domain, type|ext_flags, protocol);
  197. if (SOCKET_OK(s))
  198. goto socket_ok;
  199. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  200. * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
  201. * support, we are running on one without. */
  202. if (errno != EINVAL)
  203. return s;
  204. #endif /* defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK) */
  205. s = socket(domain, type, protocol);
  206. if (! SOCKET_OK(s))
  207. return s;
  208. #if defined(FD_CLOEXEC)
  209. if (cloexec) {
  210. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  211. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  212. tor_close_socket_simple(s);
  213. return TOR_INVALID_SOCKET;
  214. }
  215. }
  216. #else /* !(defined(FD_CLOEXEC)) */
  217. (void)cloexec;
  218. #endif /* defined(FD_CLOEXEC) */
  219. if (nonblock) {
  220. if (set_socket_nonblocking(s) == -1) {
  221. tor_close_socket_simple(s);
  222. return TOR_INVALID_SOCKET;
  223. }
  224. }
  225. goto socket_ok; /* So that socket_ok will not be unused. */
  226. socket_ok:
  227. tor_take_socket_ownership(s);
  228. return s;
  229. }
  230. /**
  231. * For socket accounting: remember that we are the owner of the socket
  232. * <b>s</b>. This will prevent us from overallocating sockets, and prevent us
  233. * from asserting later when we close the socket <b>s</b>.
  234. */
  235. void
  236. tor_take_socket_ownership(tor_socket_t s)
  237. {
  238. socket_accounting_lock();
  239. ++n_sockets_open;
  240. mark_socket_open(s);
  241. socket_accounting_unlock();
  242. }
  243. /** As accept(), but counts the number of open sockets. */
  244. tor_socket_t
  245. tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
  246. {
  247. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0);
  248. }
  249. /** As accept(), but returns a nonblocking socket and
  250. * counts the number of open sockets. */
  251. tor_socket_t
  252. tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr,
  253. socklen_t *len)
  254. {
  255. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1);
  256. }
  257. /** As accept(), but counts the number of open sockets and handles
  258. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  259. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  260. * if the corresponding extension should be used.*/
  261. tor_socket_t
  262. tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr,
  263. socklen_t *len, int cloexec, int nonblock)
  264. {
  265. tor_socket_t s;
  266. /* We are about to create a new file descriptor so make sure we have
  267. * enough of them. */
  268. if (get_n_open_sockets() >= max_sockets - 1) {
  269. #ifdef _WIN32
  270. WSASetLastError(WSAEMFILE);
  271. #else
  272. errno = EMFILE;
  273. #endif
  274. return TOR_INVALID_SOCKET;
  275. }
  276. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) \
  277. && defined(SOCK_NONBLOCK)
  278. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  279. (nonblock ? SOCK_NONBLOCK : 0);
  280. s = accept4(sockfd, addr, len, ext_flags);
  281. if (SOCKET_OK(s))
  282. goto socket_ok;
  283. /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
  284. * even though we were built on a system with accept4 support, we
  285. * are running on one without. Also, check for EINVAL, which indicates that
  286. * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
  287. if (errno != EINVAL && errno != ENOSYS)
  288. return s;
  289. #endif /* defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) ... */
  290. s = accept(sockfd, addr, len);
  291. if (!SOCKET_OK(s))
  292. return s;
  293. #if defined(FD_CLOEXEC)
  294. if (cloexec) {
  295. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  296. log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno));
  297. tor_close_socket_simple(s);
  298. return TOR_INVALID_SOCKET;
  299. }
  300. }
  301. #else /* !(defined(FD_CLOEXEC)) */
  302. (void)cloexec;
  303. #endif /* defined(FD_CLOEXEC) */
  304. if (nonblock) {
  305. if (set_socket_nonblocking(s) == -1) {
  306. tor_close_socket_simple(s);
  307. return TOR_INVALID_SOCKET;
  308. }
  309. }
  310. goto socket_ok; /* So that socket_ok will not be unused. */
  311. socket_ok:
  312. tor_take_socket_ownership(s);
  313. return s;
  314. }
  315. /** Return the number of sockets we currently have opened. */
  316. int
  317. get_n_open_sockets(void)
  318. {
  319. int n;
  320. socket_accounting_lock();
  321. n = n_sockets_open;
  322. socket_accounting_unlock();
  323. return n;
  324. }
  325. /**
  326. * Allocate a pair of connected sockets. (Like socketpair(family,
  327. * type,protocol,fd), but works on systems that don't have
  328. * socketpair.)
  329. *
  330. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  331. *
  332. * Note that on systems without socketpair, this call will fail if
  333. * localhost is inaccessible (for example, if the networking
  334. * stack is down). And even if it succeeds, the socket pair will not
  335. * be able to read while localhost is down later (the socket pair may
  336. * even close, depending on OS-specific timeouts).
  337. *
  338. * Returns 0 on success and -errno on failure; do not rely on the value
  339. * of errno or WSAGetLastError().
  340. **/
  341. /* It would be nicer just to set errno, but that won't work for windows. */
  342. int
  343. tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  344. {
  345. //don't use win32 socketpairs (they are always bad)
  346. #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  347. int r;
  348. #ifdef SOCK_CLOEXEC
  349. r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd);
  350. if (r == 0)
  351. goto sockets_ok;
  352. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  353. * even though we were built on a system with SOCK_CLOEXEC support, we
  354. * are running on one without. */
  355. if (errno != EINVAL)
  356. return -errno;
  357. #endif /* defined(SOCK_CLOEXEC) */
  358. r = socketpair(family, type, protocol, fd);
  359. if (r < 0)
  360. return -errno;
  361. #if defined(FD_CLOEXEC)
  362. if (SOCKET_OK(fd[0])) {
  363. r = fcntl(fd[0], F_SETFD, FD_CLOEXEC);
  364. if (r == -1) {
  365. close(fd[0]);
  366. close(fd[1]);
  367. return -errno;
  368. }
  369. }
  370. if (SOCKET_OK(fd[1])) {
  371. r = fcntl(fd[1], F_SETFD, FD_CLOEXEC);
  372. if (r == -1) {
  373. close(fd[0]);
  374. close(fd[1]);
  375. return -errno;
  376. }
  377. }
  378. #endif /* defined(FD_CLOEXEC) */
  379. goto sockets_ok; /* So that sockets_ok will not be unused. */
  380. sockets_ok:
  381. socket_accounting_lock();
  382. if (SOCKET_OK(fd[0])) {
  383. ++n_sockets_open;
  384. mark_socket_open(fd[0]);
  385. }
  386. if (SOCKET_OK(fd[1])) {
  387. ++n_sockets_open;
  388. mark_socket_open(fd[1]);
  389. }
  390. socket_accounting_unlock();
  391. return 0;
  392. #else /* !(defined(HAVE_SOCKETPAIR) && !defined(_WIN32)) */
  393. return tor_ersatz_socketpair(family, type, protocol, fd);
  394. #endif /* defined(HAVE_SOCKETPAIR) && !defined(_WIN32) */
  395. }
  396. #ifdef NEED_ERSATZ_SOCKETPAIR
  397. static inline socklen_t
  398. SIZEOF_SOCKADDR(int domain)
  399. {
  400. switch (domain) {
  401. case AF_INET:
  402. return sizeof(struct sockaddr_in);
  403. case AF_INET6:
  404. return sizeof(struct sockaddr_in6);
  405. default:
  406. return 0;
  407. }
  408. }
  409. /**
  410. * Helper used to implement socketpair on systems that lack it, by
  411. * making a direct connection to localhost.
  412. */
  413. STATIC int
  414. tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  415. {
  416. /* This socketpair does not work when localhost is down. So
  417. * it's really not the same thing at all. But it's close enough
  418. * for now, and really, when localhost is down sometimes, we
  419. * have other problems too.
  420. */
  421. tor_socket_t listener = TOR_INVALID_SOCKET;
  422. tor_socket_t connector = TOR_INVALID_SOCKET;
  423. tor_socket_t acceptor = TOR_INVALID_SOCKET;
  424. tor_addr_t listen_tor_addr;
  425. struct sockaddr_storage connect_addr_ss, listen_addr_ss;
  426. struct sockaddr *listen_addr = (struct sockaddr *) &listen_addr_ss;
  427. uint16_t listen_port = 0;
  428. tor_addr_t connect_tor_addr;
  429. uint16_t connect_port = 0;
  430. struct sockaddr *connect_addr = (struct sockaddr *) &connect_addr_ss;
  431. socklen_t size;
  432. int saved_errno = -1;
  433. int ersatz_domain = AF_INET;
  434. memset(&connect_tor_addr, 0, sizeof(connect_tor_addr));
  435. memset(&connect_addr_ss, 0, sizeof(connect_addr_ss));
  436. memset(&listen_tor_addr, 0, sizeof(listen_tor_addr));
  437. memset(&listen_addr_ss, 0, sizeof(listen_addr_ss));
  438. if (protocol
  439. #ifdef AF_UNIX
  440. || family != AF_UNIX
  441. #endif
  442. ) {
  443. #ifdef _WIN32
  444. return -WSAEAFNOSUPPORT;
  445. #else
  446. return -EAFNOSUPPORT;
  447. #endif
  448. }
  449. if (!fd) {
  450. return -EINVAL;
  451. }
  452. listener = tor_open_socket(ersatz_domain, type, 0);
  453. if (!SOCKET_OK(listener)) {
  454. int first_errno = tor_socket_errno(-1);
  455. if (first_errno == SOCK_ERRNO(EPROTONOSUPPORT)
  456. && ersatz_domain == AF_INET) {
  457. /* Assume we're on an IPv6-only system */
  458. ersatz_domain = AF_INET6;
  459. listener = tor_open_socket(ersatz_domain, type, 0);
  460. if (!SOCKET_OK(listener)) {
  461. /* Keep the previous behaviour, which was to return the IPv4 error.
  462. * (This may be less informative on IPv6-only systems.)
  463. * XX/teor - is there a better way to decide which errno to return?
  464. * (I doubt we care much either way, once there is an error.)
  465. */
  466. return -first_errno;
  467. }
  468. }
  469. }
  470. /* If there is no 127.0.0.1 or ::1, this will and must fail. Otherwise, we
  471. * risk exposing a socketpair on a routable IP address. (Some BSD jails
  472. * use a routable address for localhost. Fortunately, they have the real
  473. * AF_UNIX socketpair.) */
  474. if (ersatz_domain == AF_INET) {
  475. tor_addr_from_ipv4h(&listen_tor_addr, INADDR_LOOPBACK);
  476. } else {
  477. tor_addr_parse(&listen_tor_addr, "[::1]");
  478. }
  479. tor_assert(tor_addr_is_loopback(&listen_tor_addr));
  480. size = tor_addr_to_sockaddr(&listen_tor_addr,
  481. 0 /* kernel chooses port. */,
  482. listen_addr,
  483. sizeof(listen_addr_ss));
  484. if (bind(listener, listen_addr, size) == -1)
  485. goto tidy_up_and_fail;
  486. if (listen(listener, 1) == -1)
  487. goto tidy_up_and_fail;
  488. connector = tor_open_socket(ersatz_domain, type, 0);
  489. if (!SOCKET_OK(connector))
  490. goto tidy_up_and_fail;
  491. /* We want to find out the port number to connect to. */
  492. size = sizeof(connect_addr_ss);
  493. if (getsockname(listener, connect_addr, &size) == -1)
  494. goto tidy_up_and_fail;
  495. if (size != SIZEOF_SOCKADDR (connect_addr->sa_family))
  496. goto abort_tidy_up_and_fail;
  497. if (connect(connector, connect_addr, size) == -1)
  498. goto tidy_up_and_fail;
  499. size = sizeof(listen_addr_ss);
  500. acceptor = tor_accept_socket(listener, listen_addr, &size);
  501. if (!SOCKET_OK(acceptor))
  502. goto tidy_up_and_fail;
  503. if (size != SIZEOF_SOCKADDR(listen_addr->sa_family))
  504. goto abort_tidy_up_and_fail;
  505. /* Now check we are talking to ourself by matching port and host on the
  506. two sockets. */
  507. if (getsockname(connector, connect_addr, &size) == -1)
  508. goto tidy_up_and_fail;
  509. /* Set *_tor_addr and *_port to the address and port that was used */
  510. tor_addr_from_sockaddr(&listen_tor_addr, listen_addr, &listen_port);
  511. tor_addr_from_sockaddr(&connect_tor_addr, connect_addr, &connect_port);
  512. if (size != SIZEOF_SOCKADDR (connect_addr->sa_family)
  513. || tor_addr_compare(&listen_tor_addr, &connect_tor_addr, CMP_SEMANTIC)
  514. || listen_port != connect_port) {
  515. goto abort_tidy_up_and_fail;
  516. }
  517. tor_close_socket(listener);
  518. fd[0] = connector;
  519. fd[1] = acceptor;
  520. return 0;
  521. abort_tidy_up_and_fail:
  522. #ifdef _WIN32
  523. saved_errno = WSAECONNABORTED;
  524. #else
  525. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  526. #endif
  527. tidy_up_and_fail:
  528. if (saved_errno < 0)
  529. saved_errno = errno;
  530. if (SOCKET_OK(listener))
  531. tor_close_socket(listener);
  532. if (SOCKET_OK(connector))
  533. tor_close_socket(connector);
  534. if (SOCKET_OK(acceptor))
  535. tor_close_socket(acceptor);
  536. return -saved_errno;
  537. }
  538. #endif /* defined(NEED_ERSATZ_SOCKETPAIR) */
  539. /** Mockable wrapper for getsockname(). */
  540. MOCK_IMPL(int,
  541. tor_getsockname,(tor_socket_t sock, struct sockaddr *address,
  542. socklen_t *address_len))
  543. {
  544. return getsockname(sock, address, address_len);
  545. }
  546. /**
  547. * Find the local address associated with the socket <b>sock</b>, and
  548. * place it in *<b>addr_out</b>. Return 0 on success, -1 on failure.
  549. *
  550. * (As tor_getsockname, but instead places the result in a tor_addr_t.) */
  551. int
  552. tor_addr_from_getsockname(struct tor_addr_t *addr_out, tor_socket_t sock)
  553. {
  554. struct sockaddr_storage ss;
  555. socklen_t ss_len = sizeof(ss);
  556. memset(&ss, 0, sizeof(ss));
  557. if (tor_getsockname(sock, (struct sockaddr *) &ss, &ss_len) < 0)
  558. return -1;
  559. return tor_addr_from_sockaddr(addr_out, (struct sockaddr *)&ss, NULL);
  560. }
  561. /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
  562. * on failure.
  563. */
  564. int
  565. set_socket_nonblocking(tor_socket_t sock)
  566. {
  567. #if defined(_WIN32)
  568. unsigned long nonblocking = 1;
  569. ioctlsocket(sock, FIONBIO, (unsigned long*) &nonblocking);
  570. #else
  571. int flags;
  572. flags = fcntl(sock, F_GETFL, 0);
  573. if (flags == -1) {
  574. log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno));
  575. return -1;
  576. }
  577. flags |= O_NONBLOCK;
  578. if (fcntl(sock, F_SETFL, flags) == -1) {
  579. log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno));
  580. return -1;
  581. }
  582. #endif /* defined(_WIN32) */
  583. return 0;
  584. }
  585. /** Read from <b>sock</b> to <b>buf</b>, until we get <b>count</b> bytes or
  586. * reach the end of the file. Return the number of bytes read, or -1 on
  587. * error. Only use if fd is a blocking fd. */
  588. ssize_t
  589. read_all_from_socket(tor_socket_t sock, char *buf, size_t count)
  590. {
  591. size_t numread = 0;
  592. ssize_t result;
  593. if (count > SIZE_T_CEILING || count > SSIZE_MAX) {
  594. errno = EINVAL;
  595. return -1;
  596. }
  597. while (numread < count) {
  598. result = tor_socket_recv(sock, buf+numread, count-numread, 0);
  599. if (result<0)
  600. return -1;
  601. else if (result == 0)
  602. break;
  603. numread += result;
  604. }
  605. return (ssize_t)numread;
  606. }
  607. /** Write <b>count</b> bytes from <b>buf</b> to <b>sock</b>. Return the number
  608. * of bytes written, or -1 on error. Only use if fd is a blocking fd. */
  609. ssize_t
  610. write_all_to_socket(tor_socket_t fd, const char *buf, size_t count)
  611. {
  612. size_t written = 0;
  613. ssize_t result;
  614. raw_assert(count < SSIZE_MAX);
  615. while (written != count) {
  616. result = tor_socket_send(fd, buf+written, count-written, 0);
  617. if (result<0)
  618. return -1;
  619. written += result;
  620. }
  621. return (ssize_t)count;
  622. }
  623. /**
  624. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  625. * you need to ask the socket for its actual errno. Also, you need to
  626. * get your errors from WSAGetLastError, not errno. (If you supply a
  627. * socket of -1, we check WSAGetLastError, but don't correct
  628. * WSAEWOULDBLOCKs.)
  629. *
  630. * The upshot of all of this is that when a socket call fails, you
  631. * should call tor_socket_errno <em>at most once</em> on the failing
  632. * socket to get the error.
  633. */
  634. #if defined(_WIN32)
  635. int
  636. tor_socket_errno(tor_socket_t sock)
  637. {
  638. int optval, optvallen=sizeof(optval);
  639. int err = WSAGetLastError();
  640. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  641. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  642. return err;
  643. if (optval)
  644. return optval;
  645. }
  646. return err;
  647. }
  648. #endif /* defined(_WIN32) */
  649. #if defined(_WIN32)
  650. #define E(code, s) { code, (s " [" #code " ]") }
  651. struct { int code; const char *msg; } windows_socket_errors[] = {
  652. E(WSAEINTR, "Interrupted function call"),
  653. E(WSAEACCES, "Permission denied"),
  654. E(WSAEFAULT, "Bad address"),
  655. E(WSAEINVAL, "Invalid argument"),
  656. E(WSAEMFILE, "Too many open files"),
  657. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  658. E(WSAEINPROGRESS, "Operation now in progress"),
  659. E(WSAEALREADY, "Operation already in progress"),
  660. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  661. E(WSAEDESTADDRREQ, "Destination address required"),
  662. E(WSAEMSGSIZE, "Message too long"),
  663. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  664. E(WSAENOPROTOOPT, "Bad protocol option"),
  665. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  666. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  667. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  668. E(WSAEOPNOTSUPP, "Operation not supported"),
  669. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  670. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  671. E(WSAEADDRINUSE, "Address already in use"),
  672. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  673. E(WSAENETDOWN, "Network is down"),
  674. E(WSAENETUNREACH, "Network is unreachable"),
  675. E(WSAENETRESET, "Network dropped connection on reset"),
  676. E(WSAECONNABORTED, "Software caused connection abort"),
  677. E(WSAECONNRESET, "Connection reset by peer"),
  678. E(WSAENOBUFS, "No buffer space available"),
  679. E(WSAEISCONN, "Socket is already connected"),
  680. E(WSAENOTCONN, "Socket is not connected"),
  681. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  682. E(WSAETIMEDOUT, "Connection timed out"),
  683. E(WSAECONNREFUSED, "Connection refused"),
  684. E(WSAEHOSTDOWN, "Host is down"),
  685. E(WSAEHOSTUNREACH, "No route to host"),
  686. E(WSAEPROCLIM, "Too many processes"),
  687. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  688. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  689. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  690. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  691. E(WSAEDISCON, "Graceful shutdown now in progress"),
  692. #ifdef WSATYPE_NOT_FOUND
  693. E(WSATYPE_NOT_FOUND, "Class type not found"),
  694. #endif
  695. E(WSAHOST_NOT_FOUND, "Host not found"),
  696. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  697. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  698. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  699. /* There are some more error codes whose numeric values are marked
  700. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  701. * reason that practitioners of some craft traditions deliberately
  702. * introduce imperfections into their baskets and rugs "to allow the
  703. * evil spirits to escape." If we catch them, then our binaries
  704. * might not report consistent results across versions of Windows.
  705. * Thus, I'm going to let them all fall through.
  706. */
  707. { -1, NULL },
  708. };
  709. /** There does not seem to be a strerror equivalent for Winsock errors.
  710. * Naturally, we have to roll our own.
  711. */
  712. const char *
  713. tor_socket_strerror(int e)
  714. {
  715. int i;
  716. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  717. if (e == windows_socket_errors[i].code)
  718. return windows_socket_errors[i].msg;
  719. }
  720. return strerror(e);
  721. }
  722. #endif /* defined(_WIN32) */