socket.c 25 KB

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