socket.c 25 KB

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