compat.c 23 KB

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