compat.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. /* Copyright 2003-2004 Roger Dingledine; Copyright 2004 Nick Mathewson */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char compat_c_id[] = "$Id$";
  5. /* This is required on rh7 to make strptime not complain.
  6. */
  7. #define _GNU_SOURCE
  8. #include "orconfig.h"
  9. #include "fakepoll.h"
  10. #include "compat.h"
  11. #ifdef MS_WINDOWS
  12. #include <process.h>
  13. #endif
  14. #ifdef HAVE_UNAME
  15. #include <sys/utsname.h>
  16. #endif
  17. #ifdef HAVE_SYS_TIME_H
  18. #include <sys/time.h>
  19. #endif
  20. #ifdef HAVE_UNISTD_H
  21. #include <unistd.h>
  22. #endif
  23. #ifdef HAVE_SYS_FCNTL_H
  24. #include <sys/fcntl.h>
  25. #endif
  26. #ifdef HAVE_PWD_H
  27. #include <pwd.h>
  28. #endif
  29. #ifdef HAVE_GRP_H
  30. #include <grp.h>
  31. #endif
  32. #ifdef HAVE_FCNTL_H
  33. #include <fcntl.h>
  34. #endif
  35. #ifdef HAVE_SYS_RESOURCE_H
  36. #include <sys/resource.h>
  37. #endif
  38. #ifdef HAVE_ERRNO_H
  39. #include <errno.h>
  40. #endif
  41. #ifdef HAVE_NETINET_IN_H
  42. #include <netinet/in.h>
  43. #endif
  44. #ifdef HAVE_ARPA_INET_H
  45. #include <arpa/inet.h>
  46. #endif
  47. #ifndef HAVE_GETTIMEOFDAY
  48. #ifdef HAVE_FTIME
  49. #include <sys/timeb.h>
  50. #endif
  51. #endif
  52. #ifdef HAVE_SYS_SOCKET_H
  53. #include <sys/socket.h>
  54. #endif
  55. #ifdef HAVE_NETDB_H
  56. #include <netdb.h>
  57. #endif
  58. #ifdef HAVE_SYS_PARAM_H
  59. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  60. #endif
  61. #include <stdarg.h>
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64. #include <string.h>
  65. #include <assert.h>
  66. #include "log.h"
  67. #include "util.h"
  68. /* Inline the strl functions if the platform doesn't have them. */
  69. #ifndef HAVE_STRLCPY
  70. #include "strlcpy.c"
  71. #endif
  72. #ifndef HAVE_STRLCAT
  73. #include "strlcat.c"
  74. #endif
  75. /* used by inet_addr, not defined on solaris anywhere!? */
  76. #ifndef INADDR_NONE
  77. #define INADDR_NONE ((unsigned long) -1)
  78. #endif
  79. /** Replacement for snprintf. Differs from platform snprintf in two
  80. * ways: First, always NUL-terminates its output. Second, always
  81. * returns -1 if the result is truncated. (Note that this return
  82. * behavior does <i>not</i> conform to C99; it just happens to be the
  83. * easiest to emulate "return -1" with conformant implementations than
  84. * it is to emulate "return number that would be written" with
  85. * non-conformant implementations.) */
  86. int tor_snprintf(char *str, size_t size, const char *format, ...)
  87. {
  88. va_list ap;
  89. int r;
  90. va_start(ap,format);
  91. r = tor_vsnprintf(str,size,format,ap);
  92. va_end(ap);
  93. return r;
  94. }
  95. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  96. * snprintf.
  97. */
  98. int tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  99. {
  100. int r;
  101. if (size == 0)
  102. return -1; /* no place for the NUL */
  103. if (size > SIZE_T_CEILING)
  104. return -1;
  105. #ifdef MS_WINDOWS
  106. r = _vsnprintf(str, size, format, args);
  107. #else
  108. r = vsnprintf(str, size, format, args);
  109. #endif
  110. str[size-1] = '\0';
  111. if (r < 0 || ((size_t)r) >= size)
  112. return -1;
  113. return r;
  114. }
  115. /** Take a filename and return a pointer to its final element. This
  116. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  117. * contains the full path to the file. This is bad, because it
  118. * confuses users to find the home directory of the person who
  119. * compiled the binary in their warrning messages.
  120. */
  121. const char *
  122. _tor_fix_source_file(const char *fname)
  123. {
  124. const char *cp1, *cp2, *r;
  125. cp1 = strrchr(fname, '/');
  126. cp2 = strrchr(fname, '\\');
  127. if (cp1 && cp2) {
  128. r = (cp1<cp2)?(cp2+1):(cp1+1);
  129. } else if (cp1) {
  130. r = cp1+1;
  131. } else if (cp2) {
  132. r = cp2+1;
  133. } else {
  134. r = fname;
  135. }
  136. return r;
  137. }
  138. #ifndef UNALIGNED_INT_ACCESS_OK
  139. /**
  140. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  141. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  142. * unaligned memory access.
  143. */
  144. uint16_t get_uint16(const char *cp)
  145. {
  146. uint16_t v;
  147. memcpy(&v,cp,2);
  148. return v;
  149. }
  150. /**
  151. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  152. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  153. * unaligned memory access.
  154. */
  155. uint32_t get_uint32(const char *cp)
  156. {
  157. uint32_t v;
  158. memcpy(&v,cp,4);
  159. return v;
  160. }
  161. /**
  162. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  163. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  164. * unaligned memory access. */
  165. void set_uint16(char *cp, uint16_t v)
  166. {
  167. memcpy(cp,&v,2);
  168. }
  169. /**
  170. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  171. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  172. * unaligned memory access. */
  173. void set_uint32(char *cp, uint32_t v)
  174. {
  175. memcpy(cp,&v,4);
  176. }
  177. #endif
  178. /**
  179. * Rename the file 'from' to the file 'to'. On unix, this is the same as
  180. * rename(2). On windows, this removes 'to' first if it already exists.
  181. * Returns 0 on success. Returns -1 and sets errno on failure.
  182. */
  183. int replace_file(const char *from, const char *to)
  184. {
  185. #ifndef MS_WINDOWS
  186. return rename(from,to);
  187. #else
  188. switch (file_status(to))
  189. {
  190. case FN_NOENT:
  191. break;
  192. case FN_FILE:
  193. if (unlink(to)) return -1;
  194. break;
  195. case FN_ERROR:
  196. return -1;
  197. case FN_DIR:
  198. errno = EISDIR;
  199. return -1;
  200. }
  201. return rename(from,to);
  202. #endif
  203. }
  204. /** Turn <b>socket</b> into a nonblocking socket.
  205. */
  206. void set_socket_nonblocking(int socket)
  207. {
  208. #ifdef MS_WINDOWS
  209. int nonblocking = 1;
  210. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  211. #else
  212. fcntl(socket, F_SETFL, O_NONBLOCK);
  213. #endif
  214. }
  215. /**
  216. * Allocate a pair of connected sockets. (Like socketpair(family,
  217. * type,protocol,fd), but works on systems that don't have
  218. * socketpair.)
  219. *
  220. * Currently, only (AF_UNIX, SOCK_STREAM, 0 ) sockets are supported.
  221. *
  222. * Note that on systems without socketpair, this call will fail if
  223. * localhost is inaccessible (for example, if the networking
  224. * stack is down). And even if it succeeds, the socket pair will not
  225. * be able to read while localhost is down later (the socket pair may
  226. * even close, depending on OS-specific timeouts).
  227. **/
  228. int
  229. tor_socketpair(int family, int type, int protocol, int fd[2])
  230. {
  231. #ifdef HAVE_SOCKETPAIR
  232. return socketpair(family, type, protocol, fd);
  233. #else
  234. /* This socketpair does not work when localhost is down. So
  235. * it's really not the same thing at all. But it's close enough
  236. * for now, and really, when localhost is down sometimes, we
  237. * have other problems too.
  238. */
  239. int listener = -1;
  240. int connector = -1;
  241. int acceptor = -1;
  242. struct sockaddr_in listen_addr;
  243. struct sockaddr_in connect_addr;
  244. int size;
  245. if (protocol
  246. #ifdef AF_UNIX
  247. || family != AF_UNIX
  248. #endif
  249. ) {
  250. #ifdef MS_WINDOWS
  251. errno = WSAEAFNOSUPPORT;
  252. #else
  253. errno = EAFNOSUPPORT;
  254. #endif
  255. return -1;
  256. }
  257. if (!fd) {
  258. errno = EINVAL;
  259. return -1;
  260. }
  261. listener = socket(AF_INET, type, 0);
  262. if (listener == -1)
  263. return -1;
  264. if (!SOCKET_IS_POLLABLE(listener)) {
  265. log_fn(LOG_WARN, "Too many connections; can't open socketpair");
  266. tor_close_socket(listener);
  267. return -1;
  268. }
  269. memset(&listen_addr, 0, sizeof(listen_addr));
  270. listen_addr.sin_family = AF_INET;
  271. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  272. listen_addr.sin_port = 0; /* kernel chooses port. */
  273. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  274. == -1)
  275. goto tidy_up_and_fail;
  276. if (listen(listener, 1) == -1)
  277. goto tidy_up_and_fail;
  278. connector = socket(AF_INET, type, 0);
  279. if (connector == -1)
  280. goto tidy_up_and_fail;
  281. if (!SOCKET_IS_POLLABLE(connector)) {
  282. log_fn(LOG_WARN, "Too many connections; can't open socketpair");
  283. goto tidy_up_and_fail;
  284. }
  285. /* We want to find out the port number to connect to. */
  286. size = sizeof(connect_addr);
  287. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  288. goto tidy_up_and_fail;
  289. if (size != sizeof (connect_addr))
  290. goto abort_tidy_up_and_fail;
  291. if (connect(connector, (struct sockaddr *) &connect_addr,
  292. sizeof(connect_addr)) == -1)
  293. goto tidy_up_and_fail;
  294. size = sizeof(listen_addr);
  295. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  296. if (acceptor == -1)
  297. goto tidy_up_and_fail;
  298. if (!SOCKET_IS_POLLABLE(acceptor)) {
  299. log_fn(LOG_WARN, "Too many connections; can't open socketpair");
  300. goto tidy_up_and_fail;
  301. }
  302. if (size != sizeof(listen_addr))
  303. goto abort_tidy_up_and_fail;
  304. tor_close_socket(listener);
  305. /* Now check we are talking to ourself by matching port and host on the
  306. two sockets. */
  307. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  308. goto tidy_up_and_fail;
  309. if (size != sizeof (connect_addr)
  310. || listen_addr.sin_family != connect_addr.sin_family
  311. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  312. || listen_addr.sin_port != connect_addr.sin_port) {
  313. goto abort_tidy_up_and_fail;
  314. }
  315. fd[0] = connector;
  316. fd[1] = acceptor;
  317. return 0;
  318. abort_tidy_up_and_fail:
  319. #ifdef MS_WINDOWS
  320. errno = WSAECONNABORTED;
  321. #else
  322. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  323. #endif
  324. tidy_up_and_fail:
  325. {
  326. int save_errno = errno;
  327. if (listener != -1)
  328. tor_close_socket(listener);
  329. if (connector != -1)
  330. tor_close_socket(connector);
  331. if (acceptor != -1)
  332. tor_close_socket(acceptor);
  333. errno = save_errno;
  334. return -1;
  335. }
  336. #endif
  337. }
  338. /** Get the maximum allowed number of file descriptors. (Some systems
  339. * have a low soft limit.) Make sure we set it to at least
  340. * <b>required_min</b>. Return 0 if we can, or -1 if we fail. */
  341. int set_max_file_descriptors(unsigned int required_min) {
  342. #ifndef HAVE_GETRLIMIT
  343. log_fn(LOG_INFO,"This platform is missing getrlimit(). Proceeding.");
  344. return 0; /* hope we'll be ok */
  345. #else
  346. struct rlimit rlim;
  347. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  348. log_fn(LOG_WARN, "Could not get maximum number of file descriptors: %s",
  349. strerror(errno));
  350. return -1;
  351. }
  352. if (required_min > rlim.rlim_max) {
  353. log_fn(LOG_WARN,"We need %u file descriptors available, and we're limited to %lu. Please change your ulimit.", required_min, (unsigned long int)rlim.rlim_max);
  354. return -1;
  355. }
  356. if (required_min > rlim.rlim_cur) {
  357. log_fn(LOG_INFO,"Raising max file descriptors from %lu to %lu.",
  358. (unsigned long int)rlim.rlim_cur, (unsigned long int)rlim.rlim_max);
  359. }
  360. rlim.rlim_cur = rlim.rlim_max;
  361. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  362. log_fn(LOG_WARN, "Could not set maximum number of file descriptors: %s",
  363. strerror(errno));
  364. return -1;
  365. }
  366. return 0;
  367. #endif
  368. }
  369. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  370. * success. On failure, log and return -1.
  371. */
  372. int switch_id(char *user, char *group) {
  373. #ifndef MS_WINDOWS
  374. struct passwd *pw = NULL;
  375. struct group *gr = NULL;
  376. if (user) {
  377. pw = getpwnam(user);
  378. if (pw == NULL) {
  379. log_fn(LOG_ERR,"User '%s' not found.", user);
  380. return -1;
  381. }
  382. }
  383. /* switch the group first, while we still have the privileges to do so */
  384. if (group) {
  385. gr = getgrnam(group);
  386. if (gr == NULL) {
  387. log_fn(LOG_ERR,"Group '%s' not found.", group);
  388. return -1;
  389. }
  390. if (setgid(gr->gr_gid) != 0) {
  391. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  392. return -1;
  393. }
  394. } else if (user) {
  395. if (setgid(pw->pw_gid) != 0) {
  396. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  397. return -1;
  398. }
  399. }
  400. /* now that the group is switched, we can switch users and lose
  401. privileges */
  402. if (user) {
  403. if (setuid(pw->pw_uid) != 0) {
  404. log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
  405. return -1;
  406. }
  407. }
  408. return 0;
  409. #endif
  410. log_fn(LOG_ERR,
  411. "User or group specified, but switching users is not supported.");
  412. return -1;
  413. }
  414. #ifdef HAVE_PWD_H
  415. /** Allocate and return a string containing the home directory for the
  416. * user <b>username</b>. Only works on posix-like systems */
  417. char *
  418. get_user_homedir(const char *username)
  419. {
  420. struct passwd *pw;
  421. tor_assert(username);
  422. if (!(pw = getpwnam(username))) {
  423. log_fn(LOG_ERR,"User '%s' not found.", username);
  424. return NULL;
  425. }
  426. return tor_strdup(pw->pw_dir);
  427. }
  428. #endif
  429. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  430. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  431. * but works on Windows and Solaris.)
  432. */
  433. int tor_inet_aton(const char *c, struct in_addr* addr)
  434. {
  435. #ifdef HAVE_INET_ATON
  436. return inet_aton(c, addr);
  437. #else
  438. uint32_t r;
  439. tor_assert(c);
  440. tor_assert(addr);
  441. if (strcmp(c, "255.255.255.255") == 0) {
  442. addr->s_addr = 0xFFFFFFFFu;
  443. return 1;
  444. }
  445. r = inet_addr(c);
  446. if (r == INADDR_NONE)
  447. return 0;
  448. addr->s_addr = r;
  449. return 1;
  450. #endif
  451. }
  452. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  453. * *addr to the proper IP address, in network byte order. Returns 0
  454. * on success, -1 on failure; 1 on transient failure.
  455. *
  456. * (This function exists because standard windows gethostbyname
  457. * doesn't treat raw IP addresses properly.)
  458. */
  459. int tor_lookup_hostname(const char *name, uint32_t *addr)
  460. {
  461. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  462. * something.
  463. */
  464. struct in_addr iaddr;
  465. struct hostent *ent;
  466. tor_assert(addr);
  467. if (!*name) {
  468. /* Empty address is an error. */
  469. return -1;
  470. } else if (tor_inet_aton(name, &iaddr)) {
  471. /* It's an IP. */
  472. memcpy(addr, &iaddr.s_addr, 4);
  473. return 0;
  474. } else {
  475. ent = gethostbyname(name);
  476. if (ent) {
  477. /* break to remind us if we move away from IPv4 */
  478. tor_assert(ent->h_length == 4);
  479. memcpy(addr, ent->h_addr, 4);
  480. return 0;
  481. }
  482. memset(addr, 0, 4);
  483. #ifdef MS_WINDOWS
  484. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  485. #else
  486. return (h_errno == TRY_AGAIN) ? 1 : -1;
  487. #endif
  488. }
  489. }
  490. /* Hold the result of our call to <b>uname</b>. */
  491. static char uname_result[256];
  492. /* True iff uname_result is set. */
  493. static int uname_result_is_set = 0;
  494. /* Return a pointer to a description of our platform.
  495. */
  496. const char *
  497. get_uname(void)
  498. {
  499. #ifdef HAVE_UNAME
  500. struct utsname u;
  501. #endif
  502. if (!uname_result_is_set) {
  503. #ifdef HAVE_UNAME
  504. if (uname(&u) != -1) {
  505. /* (linux says 0 is success, solaris says 1 is success) */
  506. tor_snprintf(uname_result, sizeof(uname_result), "%s %s %s",
  507. u.sysname, u.nodename, u.machine);
  508. } else
  509. #endif
  510. {
  511. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  512. /* XXX win32 doesn't have uname, but we can still ifdef windows sprint "windows" */
  513. }
  514. uname_result_is_set = 1;
  515. }
  516. return uname_result;
  517. }
  518. /*
  519. * Process control
  520. */
  521. /** Minimalist interface to run a void function in the background. On
  522. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  523. * func should not return, but rather should call spawn_exit.
  524. */
  525. int
  526. spawn_func(int (*func)(void *), void *data)
  527. {
  528. #ifdef MS_WINDOWS
  529. int rv;
  530. rv = _beginthread(func, 0, data);
  531. if (rv == (unsigned long) -1)
  532. return -1;
  533. return 0;
  534. #else
  535. pid_t pid;
  536. pid = fork();
  537. if (pid<0)
  538. return -1;
  539. if (pid==0) {
  540. /* Child */
  541. func(data);
  542. tor_assert(0); /* Should never reach here. */
  543. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  544. } else {
  545. /* Parent */
  546. return 0;
  547. }
  548. #endif
  549. }
  550. /** End the current thread/process.
  551. */
  552. void spawn_exit()
  553. {
  554. #ifdef MS_WINDOWS
  555. _endthread();
  556. #else
  557. exit(0);
  558. #endif
  559. }
  560. /** Set *timeval to the current time of day. On error, log and terminate.
  561. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  562. */
  563. void tor_gettimeofday(struct timeval *timeval) {
  564. #ifdef HAVE_GETTIMEOFDAY
  565. if (gettimeofday(timeval, NULL)) {
  566. log_fn(LOG_ERR, "gettimeofday failed.");
  567. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  568. or segfaulted.*/
  569. exit(1);
  570. }
  571. #elif defined(HAVE_FTIME)
  572. struct timeb tb;
  573. ftime(&tb);
  574. timeval->tv_sec = tb.time;
  575. timeval->tv_usec = tb.millitm * 1000;
  576. #else
  577. #error "No way to get time."
  578. #endif
  579. return;
  580. }
  581. #ifndef MS_WINDOWS
  582. struct tor_mutex_t {
  583. };
  584. tor_mutex_t *tor_mutex_new(void) { return NULL; }
  585. void tor_mutex_acquire(tor_mutex_t *m) { }
  586. void tor_mutex_release(tor_mutex_t *m) { }
  587. void tor_mutex_free(tor_mutex_t *m) { }
  588. #else
  589. struct tor_mutex_t {
  590. HANDLE handle;
  591. };
  592. tor_mutex_t *tor_mutex_new(void)
  593. {
  594. tor_mutex_t *m;
  595. m = tor_malloc_zero(sizeof(tor_mutex_t));
  596. m->handle = CreateMutex(NULL, FALSE, NULL);
  597. tor_assert(m->handle != NULL);
  598. return m;
  599. }
  600. void tor_mutex_free(tor_mutex_t *m)
  601. {
  602. CloseHandle(m->handle);
  603. tor_free(m);
  604. }
  605. void tor_mutex_acquire(tor_mutex_t *m)
  606. {
  607. DWORD r;
  608. r = WaitForSingleObject(m->handle, INFINITE);
  609. switch (r) {
  610. case WAIT_ABANDONED: /* holding thread exited. */
  611. case WAIT_OBJECT_0: /* we got the mutex normally. */
  612. break;
  613. case WAIT_TIMEOUT: /* Should never happen. */
  614. tor_assert(0);
  615. break;
  616. case WAIT_FAILED:
  617. log_fn(LOG_WARN, "Failed to acquire mutex: %d", GetLastError());
  618. }
  619. }
  620. void tor_mutex_release(tor_mutex_t *m)
  621. {
  622. BOOL r;
  623. r = ReleaseMutex(m->handle);
  624. if (!r) {
  625. log_fn(LOG_WARN, "Failed to release mutex: %d", GetLastError());
  626. }
  627. }
  628. #endif
  629. /**
  630. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  631. * you need to ask the socket for its actual errno. Also, you need to
  632. * get your errors from WSAGetLastError, not errno. (If you supply a
  633. * socket of -1, we check WSAGetLastError, but don't correct
  634. * WSAEWOULDBLOCKs.)
  635. *
  636. * The upshot of all of this is that when a socket call fails, you
  637. * should call tor_socket_errno <em>at most once</em> on the failing
  638. * socket to get the error.
  639. */
  640. #ifdef MS_WINDOWS
  641. int tor_socket_errno(int sock)
  642. {
  643. int optval, optvallen=sizeof(optval);
  644. int err = WSAGetLastError();
  645. if (err == WSAEWOULDBLOCK && sock >= 0) {
  646. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  647. return err;
  648. if (optval)
  649. return optval;
  650. }
  651. return err;
  652. }
  653. #endif
  654. #ifdef MS_WINDOWS
  655. #define E(code, s) { code, (s " [" #code " ]") }
  656. struct { int code; const char *msg; } windows_socket_errors[] = {
  657. E(WSAEINTR, "Interrupted function call"),
  658. E(WSAEACCES, "Permission denied"),
  659. E(WSAEFAULT, "Bad address"),
  660. E(WSAEINVAL, "Invalid argument"),
  661. E(WSAEMFILE, "Too many open files"),
  662. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  663. E(WSAEINPROGRESS, "Operation now in progress"),
  664. E(WSAEALREADY, "Operation already in progress"),
  665. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  666. E(WSAEDESTADDRREQ, "Destination address required"),
  667. E(WSAEMSGSIZE, "Message too long"),
  668. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  669. E(WSAENOPROTOOPT, "Bad protocol option"),
  670. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  671. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  672. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  673. E(WSAEOPNOTSUPP, "Operation not supported"),
  674. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  675. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  676. E(WSAEADDRINUSE, "Address already in use"),
  677. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  678. E(WSAENETDOWN, "Network is down"),
  679. E(WSAENETUNREACH, "Network is unreachable"),
  680. E(WSAENETRESET, "Network dropped connection on reset"),
  681. E(WSAECONNABORTED, "Software caused connection abort"),
  682. E(WSAECONNRESET, "Connection reset by peer"),
  683. E(WSAENOBUFS, "No buffer space available"),
  684. E(WSAEISCONN, "Socket is already connected"),
  685. E(WSAENOTCONN, "Socket is not connected"),
  686. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  687. E(WSAETIMEDOUT, "Connection timed out"),
  688. E(WSAECONNREFUSED, "Connection refused"),
  689. E(WSAEHOSTDOWN, "Host is down"),
  690. E(WSAEHOSTUNREACH, "No route to host"),
  691. E(WSAEPROCLIM, "Too many processes"),
  692. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  693. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  694. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  695. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  696. E(WSAEDISCON, "Graceful shutdown now in progress"),
  697. #ifdef WSATYPE_NOT_FOUND
  698. E(WSATYPE_NOT_FOUND, "Class type not found"),
  699. #endif
  700. E(WSAHOST_NOT_FOUND, "Host not found"),
  701. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  702. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  703. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  704. /* There are some more error codes whose numeric values are marked
  705. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  706. * reason that practitioners of some craft traditions deliberately
  707. * introduce imperfections into their baskets and rugs "to allow the
  708. * evil spirits to escape." If we catch them, then our binaries
  709. * might not report consistent results across versions of Windows.
  710. * Thus, I'm going to let them all fall through.
  711. */
  712. { -1, NULL },
  713. };
  714. /** There does not seem to be a strerror equivalent for winsock errors.
  715. * Naturally, we have to roll our own.
  716. */
  717. const char *tor_socket_strerror(int e)
  718. {
  719. int i;
  720. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  721. if (e == windows_socket_errors[i].code)
  722. return windows_socket_errors[i].msg;
  723. }
  724. return strerror(e);
  725. }
  726. #endif
  727. /** Called before we make any calls to network-related functions.
  728. * (Some operating systems require their network libraries to be
  729. * initialized.) */
  730. int network_init(void)
  731. {
  732. #ifdef MS_WINDOWS
  733. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  734. */
  735. WSADATA WSAData;
  736. int r;
  737. r = WSAStartup(0x101,&WSAData);
  738. if (r) {
  739. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  740. return -1;
  741. }
  742. #endif
  743. return 0;
  744. }