socket.c 21 KB

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