socket.c 20 KB

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