compat.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. /* Copyright 2003-2004 Roger Dingledine
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char compat_c_id[] =
  6. "$Id$";
  7. /**
  8. * \file compat.c
  9. * \brief Wrappers to make calls more portable. This code defines
  10. * functions such as tor_malloc, tor_snprintf, get/set various data types,
  11. * renaming, setting socket options, switching user IDs. It is basically
  12. * where the non-portable items are conditionally included depending on
  13. * the platform.
  14. **/
  15. /* This is required on rh7 to make strptime not complain.
  16. * We also need it to make memmem get defined (where available)
  17. */
  18. #define _GNU_SOURCE
  19. #include "orconfig.h"
  20. #include "compat.h"
  21. #ifdef MS_WINDOWS
  22. #include <process.h>
  23. #endif
  24. #ifdef HAVE_UNAME
  25. #include <sys/utsname.h>
  26. #endif
  27. #ifdef HAVE_SYS_TIME_H
  28. #include <sys/time.h>
  29. #endif
  30. #ifdef HAVE_UNISTD_H
  31. #include <unistd.h>
  32. #endif
  33. #ifdef HAVE_SYS_FCNTL_H
  34. #include <sys/fcntl.h>
  35. #endif
  36. #ifdef HAVE_PWD_H
  37. #include <pwd.h>
  38. #endif
  39. #ifdef HAVE_GRP_H
  40. #include <grp.h>
  41. #endif
  42. #ifdef HAVE_FCNTL_H
  43. #include <fcntl.h>
  44. #endif
  45. #ifdef HAVE_SYS_RESOURCE_H
  46. #include <sys/resource.h>
  47. #endif
  48. #ifdef HAVE_ERRNO_H
  49. #include <errno.h>
  50. #endif
  51. #ifdef HAVE_NETINET_IN_H
  52. #include <netinet/in.h>
  53. #endif
  54. #ifdef HAVE_ARPA_INET_H
  55. #include <arpa/inet.h>
  56. #endif
  57. #ifndef HAVE_GETTIMEOFDAY
  58. #ifdef HAVE_FTIME
  59. #include <sys/timeb.h>
  60. #endif
  61. #endif
  62. #ifdef HAVE_SYS_SOCKET_H
  63. #include <sys/socket.h>
  64. #endif
  65. #ifdef HAVE_NETDB_H
  66. #include <netdb.h>
  67. #endif
  68. #ifdef HAVE_SYS_PARAM_H
  69. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  70. #endif
  71. #include <stdarg.h>
  72. #include <stdio.h>
  73. #include <stdlib.h>
  74. #include <string.h>
  75. #include <assert.h>
  76. #ifdef HAVE_PTHREAD_H
  77. #include <pthread.h>
  78. #endif
  79. #ifdef HAVE_UTIME_H
  80. #include <utime.h>
  81. #endif
  82. #ifdef HAVE_SYS_UTIME_H
  83. #include <sys/utime.h>
  84. #endif
  85. #include "log.h"
  86. #include "util.h"
  87. /* Inline the strl functions if the platform doesn't have them. */
  88. #ifndef HAVE_STRLCPY
  89. #include "strlcpy.c"
  90. #endif
  91. #ifndef HAVE_STRLCAT
  92. #include "strlcat.c"
  93. #endif
  94. /* used by inet_addr, not defined on solaris anywhere!? */
  95. #ifndef INADDR_NONE
  96. #define INADDR_NONE ((unsigned long) -1)
  97. #endif
  98. /** Replacement for snprintf. Differs from platform snprintf in two
  99. * ways: First, always NUL-terminates its output. Second, always
  100. * returns -1 if the result is truncated. (Note that this return
  101. * behavior does <i>not</i> conform to C99; it just happens to be the
  102. * easiest to emulate "return -1" with conformant implementations than
  103. * it is to emulate "return number that would be written" with
  104. * non-conformant implementations.) */
  105. int
  106. tor_snprintf(char *str, size_t size, const char *format, ...)
  107. {
  108. va_list ap;
  109. int r;
  110. va_start(ap,format);
  111. r = tor_vsnprintf(str,size,format,ap);
  112. va_end(ap);
  113. return r;
  114. }
  115. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  116. * snprintf.
  117. */
  118. int
  119. tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  120. {
  121. int r;
  122. if (size == 0)
  123. return -1; /* no place for the NUL */
  124. if (size > SIZE_T_CEILING)
  125. return -1;
  126. #ifdef MS_WINDOWS
  127. r = _vsnprintf(str, size, format, args);
  128. #else
  129. r = vsnprintf(str, size, format, args);
  130. #endif
  131. str[size-1] = '\0';
  132. if (r < 0 || ((size_t)r) >= size)
  133. return -1;
  134. return r;
  135. }
  136. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  137. * <b>needle</b>, return a pointer to the first occurrence of the needle
  138. * within the haystack, or NULL if there is no such occurrence.
  139. *
  140. * Requires that nlen be greater than zero.
  141. */
  142. const void *
  143. tor_memmem(const void *_haystack, size_t hlen,
  144. const void *_needle, size_t nlen)
  145. {
  146. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  147. tor_assert(nlen);
  148. return memmem(_haystack, hlen, _needle, nlen);
  149. #else
  150. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  151. * be. */
  152. const char *p, *end;
  153. const char *haystack = (const char*)_haystack;
  154. const char *needle = (const char*)_needle;
  155. char first;
  156. tor_assert(nlen);
  157. p = haystack;
  158. end = haystack + hlen;
  159. first = *(const char*)needle;
  160. while ((p = memchr(p, first, end-p))) {
  161. if (p+nlen > end)
  162. return NULL;
  163. if (!memcmp(p, needle, nlen))
  164. return p;
  165. ++p;
  166. }
  167. return NULL;
  168. #endif
  169. }
  170. #ifdef MS_WINDOWS
  171. /** Take a filename and return a pointer to its final element. This
  172. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  173. * contains the full path to the file. This is bad, because it
  174. * confuses users to find the home directory of the person who
  175. * compiled the binary in their warrning messages.
  176. */
  177. const char *
  178. tor_fix_source_file(const char *fname)
  179. {
  180. const char *cp1, *cp2, *r;
  181. cp1 = strrchr(fname, '/');
  182. cp2 = strrchr(fname, '\\');
  183. if (cp1 && cp2) {
  184. r = (cp1<cp2)?(cp2+1):(cp1+1);
  185. } else if (cp1) {
  186. r = cp1+1;
  187. } else if (cp2) {
  188. r = cp2+1;
  189. } else {
  190. r = fname;
  191. }
  192. return r;
  193. }
  194. #endif
  195. #ifndef UNALIGNED_INT_ACCESS_OK
  196. /**
  197. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  198. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  199. * unaligned memory access.
  200. */
  201. uint16_t
  202. get_uint16(const char *cp)
  203. {
  204. uint16_t v;
  205. memcpy(&v,cp,2);
  206. return v;
  207. }
  208. /**
  209. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  210. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  211. * unaligned memory access.
  212. */
  213. uint32_t
  214. get_uint32(const char *cp)
  215. {
  216. uint32_t v;
  217. memcpy(&v,cp,4);
  218. return v;
  219. }
  220. /**
  221. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  222. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  223. * unaligned memory access. */
  224. void
  225. set_uint16(char *cp, uint16_t v)
  226. {
  227. memcpy(cp,&v,2);
  228. }
  229. /**
  230. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  231. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  232. * unaligned memory access. */
  233. void
  234. set_uint32(char *cp, uint32_t v)
  235. {
  236. memcpy(cp,&v,4);
  237. }
  238. #endif
  239. /**
  240. * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
  241. * the same as rename(2). On windows, this removes <b>to</b> first if
  242. * it already exists.
  243. * Returns 0 on success. Returns -1 and sets errno on failure.
  244. */
  245. int
  246. replace_file(const char *from, const char *to)
  247. {
  248. #ifndef MS_WINDOWS
  249. return rename(from,to);
  250. #else
  251. switch (file_status(to))
  252. {
  253. case FN_NOENT:
  254. break;
  255. case FN_FILE:
  256. if (unlink(to)) return -1;
  257. break;
  258. case FN_ERROR:
  259. return -1;
  260. case FN_DIR:
  261. errno = EISDIR;
  262. return -1;
  263. }
  264. return rename(from,to);
  265. #endif
  266. }
  267. /** Change <b>fname</b>'s modification time to now. */
  268. int
  269. touch_file(const char *fname)
  270. {
  271. if (utime(fname, NULL)!=0)
  272. return -1;
  273. return 0;
  274. }
  275. /** Turn <b>socket</b> into a nonblocking socket.
  276. */
  277. void
  278. set_socket_nonblocking(int socket)
  279. {
  280. #ifdef MS_WINDOWS
  281. int nonblocking = 1;
  282. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  283. #else
  284. fcntl(socket, F_SETFL, O_NONBLOCK);
  285. #endif
  286. }
  287. /**
  288. * Allocate a pair of connected sockets. (Like socketpair(family,
  289. * type,protocol,fd), but works on systems that don't have
  290. * socketpair.)
  291. *
  292. * Currently, only (AF_UNIX, SOCK_STREAM, 0 ) sockets are supported.
  293. *
  294. * Note that on systems without socketpair, this call will fail if
  295. * localhost is inaccessible (for example, if the networking
  296. * stack is down). And even if it succeeds, the socket pair will not
  297. * be able to read while localhost is down later (the socket pair may
  298. * even close, depending on OS-specific timeouts).
  299. *
  300. * Returns 0 on success and -errno on failure; do not rely on the value
  301. * of errno or WSAGetLastSocketError().
  302. **/
  303. /* It would be nicer just to set errno, but that won't work for windows. */
  304. int
  305. tor_socketpair(int family, int type, int protocol, int fd[2])
  306. {
  307. #ifdef HAVE_SOCKETPAIR
  308. int r;
  309. r = socketpair(family, type, protocol, fd);
  310. return r < 0 ? -errno : r;
  311. #else
  312. /* This socketpair does not work when localhost is down. So
  313. * it's really not the same thing at all. But it's close enough
  314. * for now, and really, when localhost is down sometimes, we
  315. * have other problems too.
  316. */
  317. int listener = -1;
  318. int connector = -1;
  319. int acceptor = -1;
  320. struct sockaddr_in listen_addr;
  321. struct sockaddr_in connect_addr;
  322. int size;
  323. int saved_errno = -1;
  324. if (protocol
  325. #ifdef AF_UNIX
  326. || family != AF_UNIX
  327. #endif
  328. ) {
  329. #ifdef MS_WINDOWS
  330. return -WSAEAFNOSUPPORT;
  331. #else
  332. return -EAFNOSUPPORT;
  333. #endif
  334. }
  335. if (!fd) {
  336. return -EINVAL;
  337. }
  338. listener = socket(AF_INET, type, 0);
  339. if (listener == -1)
  340. return -tor_socket_errno(-1);
  341. if (!SOCKET_IS_POLLABLE(listener)) {
  342. warn(LD_NET, "Too many connections; can't open socketpair");
  343. tor_close_socket(listener);
  344. #ifdef MS_WINDOWS
  345. return -ENFILE;
  346. #else
  347. return -ENCONN;
  348. #endif
  349. }
  350. memset(&listen_addr, 0, sizeof(listen_addr));
  351. listen_addr.sin_family = AF_INET;
  352. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  353. listen_addr.sin_port = 0; /* kernel chooses port. */
  354. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  355. == -1)
  356. goto tidy_up_and_fail;
  357. if (listen(listener, 1) == -1)
  358. goto tidy_up_and_fail;
  359. connector = socket(AF_INET, type, 0);
  360. if (connector == -1)
  361. goto tidy_up_and_fail;
  362. if (!SOCKET_IS_POLLABLE(connector)) {
  363. warn(LD_NET, "Too many connections; can't open socketpair");
  364. goto tidy_up_and_fail;
  365. }
  366. /* We want to find out the port number to connect to. */
  367. size = sizeof(connect_addr);
  368. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  369. goto tidy_up_and_fail;
  370. if (size != sizeof (connect_addr))
  371. goto abort_tidy_up_and_fail;
  372. if (connect(connector, (struct sockaddr *) &connect_addr,
  373. sizeof(connect_addr)) == -1)
  374. goto tidy_up_and_fail;
  375. size = sizeof(listen_addr);
  376. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  377. if (acceptor == -1)
  378. goto tidy_up_and_fail;
  379. if (!SOCKET_IS_POLLABLE(acceptor)) {
  380. warn(LD_NET, "Too many connections; can't open socketpair");
  381. goto tidy_up_and_fail;
  382. }
  383. if (size != sizeof(listen_addr))
  384. goto abort_tidy_up_and_fail;
  385. tor_close_socket(listener);
  386. /* Now check we are talking to ourself by matching port and host on the
  387. two sockets. */
  388. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  389. goto tidy_up_and_fail;
  390. if (size != sizeof (connect_addr)
  391. || listen_addr.sin_family != connect_addr.sin_family
  392. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  393. || listen_addr.sin_port != connect_addr.sin_port) {
  394. goto abort_tidy_up_and_fail;
  395. }
  396. fd[0] = connector;
  397. fd[1] = acceptor;
  398. return 0;
  399. abort_tidy_up_and_fail:
  400. #ifdef MS_WINDOWS
  401. saved_errno = WSAECONNABORTED;
  402. #else
  403. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  404. #endif
  405. tidy_up_and_fail:
  406. if (saved_errno < 0)
  407. saved_errno = errno;
  408. if (listener != -1)
  409. tor_close_socket(listener);
  410. if (connector != -1)
  411. tor_close_socket(connector);
  412. if (acceptor != -1)
  413. tor_close_socket(acceptor);
  414. return -saved_errno;
  415. #endif
  416. }
  417. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  418. /** Get the maximum allowed number of file descriptors. (Some systems
  419. * have a low soft limit.) Make sure we set it to at least
  420. * <b>limit</b>. Return a new limit if we can, or -1 if we fail. */
  421. int
  422. set_max_file_descriptors(unsigned long limit, unsigned long cap)
  423. {
  424. #ifndef HAVE_GETRLIMIT
  425. log_fn(LOG_INFO, LD_NET,
  426. "This platform is missing getrlimit(). Proceeding.");
  427. if (limit > cap) {
  428. log(LOG_INFO, LD_CONFIG, "ConnLimit must be at most %d. Capping it.", cap);
  429. limit = cap;
  430. }
  431. #else
  432. struct rlimit rlim;
  433. unsigned long most;
  434. tor_assert(limit > 0);
  435. tor_assert(cap > 0);
  436. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  437. warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  438. strerror(errno));
  439. return -1;
  440. }
  441. if (rlim.rlim_max < limit) {
  442. warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  443. "limited to %lu. Please change your ulimit -n.",
  444. limit, (unsigned long)rlim.rlim_max);
  445. return -1;
  446. }
  447. most = (rlim.rlim_max > cap) ? cap : (unsigned) rlim.rlim_max;
  448. if (most > rlim.rlim_cur) {
  449. info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  450. (unsigned long)rlim.rlim_cur, most);
  451. }
  452. rlim.rlim_cur = most;
  453. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  454. warn(LD_CONFIG, "Could not set maximum number of file descriptors: %s",
  455. strerror(errno));
  456. return -1;
  457. }
  458. /* leave some overhead for logs, etc, */
  459. limit = most;
  460. #endif
  461. if (limit < ULIMIT_BUFFER) {
  462. warn(LD_CONFIG,"ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  463. return -1;
  464. }
  465. return limit - ULIMIT_BUFFER;
  466. }
  467. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  468. * success. On failure, log and return -1.
  469. */
  470. int
  471. switch_id(char *user, char *group)
  472. {
  473. #ifndef MS_WINDOWS
  474. struct passwd *pw = NULL;
  475. struct group *gr = NULL;
  476. if (user) {
  477. pw = getpwnam(user);
  478. if (pw == NULL) {
  479. err(LD_CONFIG,"User '%s' not found.", user);
  480. return -1;
  481. }
  482. }
  483. /* switch the group first, while we still have the privileges to do so */
  484. if (group) {
  485. gr = getgrnam(group);
  486. if (gr == NULL) {
  487. err(LD_CONFIG,"Group '%s' not found.", group);
  488. return -1;
  489. }
  490. if (setgid(gr->gr_gid) != 0) {
  491. err(LD_GENERAL,"Error setting GID: %s", strerror(errno));
  492. return -1;
  493. }
  494. } else if (user) {
  495. if (setgid(pw->pw_gid) != 0) {
  496. err(LD_GENERAL,"Error setting GID: %s", strerror(errno));
  497. return -1;
  498. }
  499. }
  500. /* now that the group is switched, we can switch users and lose
  501. privileges */
  502. if (user) {
  503. if (setuid(pw->pw_uid) != 0) {
  504. err(LD_GENERAL,"Error setting UID: %s", strerror(errno));
  505. return -1;
  506. }
  507. }
  508. return 0;
  509. #endif
  510. err(LD_CONFIG,
  511. "User or group specified, but switching users is not supported.");
  512. return -1;
  513. }
  514. #ifdef HAVE_PWD_H
  515. /** Allocate and return a string containing the home directory for the
  516. * user <b>username</b>. Only works on posix-like systems */
  517. char *
  518. get_user_homedir(const char *username)
  519. {
  520. struct passwd *pw;
  521. tor_assert(username);
  522. if (!(pw = getpwnam(username))) {
  523. err(LD_CONFIG,"User \"%s\" not found.", username);
  524. return NULL;
  525. }
  526. return tor_strdup(pw->pw_dir);
  527. }
  528. #endif
  529. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  530. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  531. * but works on Windows and Solaris.)
  532. */
  533. int
  534. tor_inet_aton(const char *c, struct in_addr* addr)
  535. {
  536. #ifdef HAVE_INET_ATON
  537. return inet_aton(c, addr);
  538. #else
  539. uint32_t r;
  540. tor_assert(c);
  541. tor_assert(addr);
  542. if (strcmp(c, "255.255.255.255") == 0) {
  543. addr->s_addr = 0xFFFFFFFFu;
  544. return 1;
  545. }
  546. r = inet_addr(c);
  547. if (r == INADDR_NONE)
  548. return 0;
  549. addr->s_addr = r;
  550. return 1;
  551. #endif
  552. }
  553. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  554. * *addr to the proper IP address, in network byte order. Returns 0
  555. * on success, -1 on failure; 1 on transient failure.
  556. *
  557. * (This function exists because standard windows gethostbyname
  558. * doesn't treat raw IP addresses properly.)
  559. */
  560. int
  561. tor_lookup_hostname(const char *name, uint32_t *addr)
  562. {
  563. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  564. * something.
  565. */
  566. struct in_addr iaddr;
  567. tor_assert(name);
  568. tor_assert(addr);
  569. if (!*name) {
  570. /* Empty address is an error. */
  571. return -1;
  572. } else if (tor_inet_aton(name, &iaddr)) {
  573. /* It's an IP. */
  574. memcpy(addr, &iaddr.s_addr, 4);
  575. return 0;
  576. } else {
  577. #ifdef HAVE_GETADDRINFO
  578. int err;
  579. struct addrinfo *res=NULL, *res_p;
  580. struct addrinfo hints;
  581. int result = -1;
  582. memset(&hints, 0, sizeof(hints));
  583. hints.ai_family = PF_INET;
  584. hints.ai_socktype = SOCK_STREAM;
  585. err = getaddrinfo(name, NULL, NULL, &res);
  586. if (!err) {
  587. for (res_p = res; res_p; res_p = res_p->ai_next) {
  588. if (res_p->ai_family == AF_INET) {
  589. struct sockaddr_in *sin = (struct sockaddr_in *)res_p->ai_addr;
  590. memcpy(addr, &sin->sin_addr, 4);
  591. result = 0;
  592. break;
  593. }
  594. }
  595. freeaddrinfo(res);
  596. return result;
  597. }
  598. return (err == EAI_AGAIN) ? 1 : -1;
  599. #else
  600. struct hostent *ent;
  601. int err;
  602. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  603. char buf[2048];
  604. struct hostent hostent;
  605. int r;
  606. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  607. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  608. char buf[2048];
  609. struct hostent hostent;
  610. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  611. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  612. struct hostent_data data;
  613. struct hostent hent;
  614. memset(&data, 0, sizeof(data));
  615. err = gethostbyname_r(name, &hent, &data);
  616. ent = err ? NULL : &hent;
  617. #else
  618. ent = gethostbyname(name);
  619. #ifdef MS_WINDOWS
  620. err = WSAGetLastError();
  621. #else
  622. err = h_errno;
  623. #endif
  624. #endif
  625. if (ent) {
  626. /* break to remind us if we move away from IPv4 */
  627. tor_assert(ent->h_length == 4);
  628. memcpy(addr, ent->h_addr, 4);
  629. return 0;
  630. }
  631. memset(addr, 0, 4);
  632. #ifdef MS_WINDOWS
  633. return (err == WSATRY_AGAIN) ? 1 : -1;
  634. #else
  635. return (err == TRY_AGAIN) ? 1 : -1;
  636. #endif
  637. #endif
  638. }
  639. }
  640. /** Hold the result of our call to <b>uname</b>. */
  641. static char uname_result[256];
  642. /** True iff uname_result is set. */
  643. static int uname_result_is_set = 0;
  644. /** Return a pointer to a description of our platform.
  645. */
  646. const char *
  647. get_uname(void)
  648. {
  649. #ifdef HAVE_UNAME
  650. struct utsname u;
  651. #endif
  652. if (!uname_result_is_set) {
  653. #ifdef HAVE_UNAME
  654. if (uname(&u) != -1) {
  655. /* (linux says 0 is success, solaris says 1 is success) */
  656. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  657. u.sysname, u.machine);
  658. } else
  659. #endif
  660. {
  661. #ifdef MS_WINDOWS
  662. OSVERSIONINFOEX info;
  663. int i;
  664. unsigned int leftover_mask;
  665. const char *plat = NULL;
  666. static struct {
  667. int major; int minor; const char *version;
  668. } win_version_table[] = {
  669. { 6, 0, "Windows \"Longhorn\"" },
  670. { 5, 2, "Windows Server 2003" },
  671. { 5, 1, "Windows XP" },
  672. { 5, 0, "Windows 2000" },
  673. /* { 4, 0, "Windows NT 4.0" }, */
  674. { 4, 90, "Windows Me" },
  675. { 4, 10, "Windows 98" },
  676. /* { 4, 0, "Windows 95" } */
  677. { 3, 51, "Windows NT 3.51" },
  678. { -1, -1, NULL }
  679. };
  680. static struct {
  681. unsigned int mask; const char *str;
  682. } win_mask_table[] = {
  683. { VER_SUITE_BACKOFFICE, " {backoffice}" },
  684. { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
  685. { VER_SUITE_DATACENTER, " {datacenter}" },
  686. { VER_SUITE_ENTERPRISE, " {enterprise}" },
  687. { VER_SUITE_EMBEDDEDNT, " {embedded}" },
  688. { VER_SUITE_PERSONAL, " {personal}" },
  689. { VER_SUITE_SINGLEUSERTS,
  690. " {terminal services, single user}" },
  691. { VER_SUITE_SMALLBUSINESS, " {small business}" },
  692. { VER_SUITE_SMALLBUSINESS_RESTRICTED,
  693. " {small business, restricted}" },
  694. { VER_SUITE_TERMINAL, " {terminal services}" },
  695. { 0, NULL },
  696. };
  697. info.dwOSVersionInfoSize = sizeof(info);
  698. GetVersionEx((LPOSVERSIONINFO)&info);
  699. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  700. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  701. plat = "Windows NT 4.0";
  702. else
  703. plat = "Windows 95";
  704. } else {
  705. for (i=0; win_version_table[i].major>=0; ++i) {
  706. if (win_version_table[i].major == info.dwMajorVersion &&
  707. win_version_table[i].minor == info.dwMinorVersion) {
  708. plat = win_version_table[i].version;
  709. break;
  710. }
  711. }
  712. }
  713. if (plat) {
  714. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  715. plat, info.szCSDVersion);
  716. } else {
  717. if (info.dwMajorVersion > 6 ||
  718. (info.dwMajorVersion==6 && info.dwMinorVersion>0))
  719. tor_snprintf(uname_result, sizeof(uname_result),
  720. "Very recent version of Windows [major=%d,minor=%d] %s",
  721. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  722. info.szCSDVersion);
  723. else
  724. tor_snprintf(uname_result, sizeof(uname_result),
  725. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  726. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  727. info.szCSDVersion);
  728. }
  729. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  730. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  731. } else if (info.wProductType == VER_NT_SERVER) {
  732. strlcat(uname_result, " [server]", sizeof(uname_result));
  733. } else if (info.wProductType == VER_NT_WORKSTATION) {
  734. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  735. }
  736. leftover_mask = info.wSuiteMask;
  737. for (i = 0; win_mask_table[i].mask; ++i) {
  738. if (info.wSuiteMask & win_mask_table[i].mask) {
  739. strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
  740. leftover_mask &= ~win_mask_table[i].mask;
  741. }
  742. }
  743. if (leftover_mask) {
  744. size_t len = strlen(uname_result);
  745. tor_snprintf(uname_result+len, sizeof(uname_result)-len,
  746. " {0x%x}", info.wSuiteMask);
  747. }
  748. #else
  749. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  750. #endif
  751. }
  752. uname_result_is_set = 1;
  753. }
  754. return uname_result;
  755. }
  756. /*
  757. * Process control
  758. */
  759. #if defined(USE_PTHREADS)
  760. /** Wraps a an int (*)(void*) function and its argument so we can
  761. * invoke them in a way pthreads would expect.
  762. */
  763. typedef struct tor_pthread_data_t {
  764. int (*func)(void *);
  765. void *data;
  766. } tor_pthread_data_t;
  767. static void *
  768. tor_pthread_helper_fn(void *_data)
  769. {
  770. tor_pthread_data_t *data = _data;
  771. int (*func)(void*);
  772. void *arg;
  773. func = data->func;
  774. arg = data->data;
  775. tor_free(_data);
  776. func(arg);
  777. return NULL;
  778. }
  779. #endif
  780. /** Minimalist interface to run a void function in the background. On
  781. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  782. * func should not return, but rather should call spawn_exit.
  783. *
  784. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  785. * since in a multithreaded environment, there is no way to be sure that
  786. * the caller's stack will still be around when the called function is
  787. * running.
  788. */
  789. int
  790. spawn_func(int (*func)(void *), void *data)
  791. {
  792. #if defined(USE_WIN32_THREADS)
  793. int rv;
  794. rv = _beginthread(func, 0, data);
  795. if (rv == (unsigned long) -1)
  796. return -1;
  797. return 0;
  798. #elif defined(USE_PTHREADS)
  799. pthread_t thread;
  800. tor_pthread_data_t *d;
  801. d = tor_malloc(sizeof(tor_pthread_data_t));
  802. d->data = data;
  803. d->func = func;
  804. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  805. return -1;
  806. if (pthread_detach(thread))
  807. return -1;
  808. return 0;
  809. #else
  810. pid_t pid;
  811. pid = fork();
  812. if (pid<0)
  813. return -1;
  814. if (pid==0) {
  815. /* Child */
  816. func(data);
  817. tor_assert(0); /* Should never reach here. */
  818. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  819. } else {
  820. /* Parent */
  821. return 0;
  822. }
  823. #endif
  824. }
  825. /** End the current thread/process.
  826. */
  827. void
  828. spawn_exit(void)
  829. {
  830. #if defined(USE_WIN32_THREADS)
  831. _endthread();
  832. #elif defined(USE_PTHREADS)
  833. pthread_exit(NULL);
  834. #else
  835. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  836. * call _exit, not exit, from child processes. */
  837. _exit(0);
  838. #endif
  839. }
  840. /** Set *timeval to the current time of day. On error, log and terminate.
  841. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  842. */
  843. void
  844. tor_gettimeofday(struct timeval *timeval)
  845. {
  846. #ifdef MS_WINDOWS
  847. /* Epoch bias copied from perl: number of units between windows epoch and
  848. * unix epoch. */
  849. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  850. #define UNITS_PER_SEC U64_LITERAL(10000000)
  851. #define USEC_PER_SEC U64_LITERAL(1000000)
  852. #define UNITS_PER_USEC U64_LITERAL(10)
  853. union {
  854. uint64_t ft_64;
  855. FILETIME ft_ft;
  856. } ft;
  857. /* number of 100-nsec units since Jan 1, 1601 */
  858. GetSystemTimeAsFileTime(&ft.ft_ft);
  859. if (ft.ft_64 < EPOCH_BIAS) {
  860. err(LD_GENERAL,"System time is before 1970; failing.");
  861. exit(1);
  862. }
  863. ft.ft_64 -= EPOCH_BIAS;
  864. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  865. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  866. #elif defined(HAVE_GETTIMEOFDAY)
  867. if (gettimeofday(timeval, NULL)) {
  868. err(LD_GENERAL,"gettimeofday failed.");
  869. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  870. or segfaulted.*/
  871. exit(1);
  872. }
  873. #elif defined(HAVE_FTIME)
  874. struct timeb tb;
  875. ftime(&tb);
  876. timeval->tv_sec = tb.time;
  877. timeval->tv_usec = tb.millitm * 1000;
  878. #else
  879. #error "No way to get time."
  880. #endif
  881. return;
  882. }
  883. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  884. #define TIME_FNS_NEED_LOCKS
  885. #endif
  886. #ifndef HAVE_LOCALTIME_R
  887. #ifdef TIME_FNS_NEED_LOCKS
  888. struct tm *
  889. tor_localtime_r(const time_t *timep, struct tm *result)
  890. {
  891. struct tm *r;
  892. static tor_mutex_t *m=NULL;
  893. if (!m) { m=tor_mutex_new(); }
  894. tor_assert(result);
  895. tor_mutex_acquire(m);
  896. r = localtime(timep);
  897. memcpy(result, r, sizeof(struct tm));
  898. tor_mutex_release(m);
  899. return result;
  900. }
  901. #else
  902. struct tm *
  903. tor_localtime_r(const time_t *timep, struct tm *result)
  904. {
  905. struct tm *r;
  906. tor_assert(result);
  907. r = localtime(timep);
  908. memcpy(result, r, sizeof(struct tm));
  909. return result;
  910. }
  911. #endif
  912. #endif
  913. #ifndef HAVE_GMTIME_R
  914. #ifdef TIME_FNS_NEED_LOCKS
  915. struct tm *
  916. tor_gmtime_r(const time_t *timep, struct tm *result)
  917. {
  918. struct tm *r;
  919. static tor_mutex_t *m=NULL;
  920. if (!m) { m=tor_mutex_new(); }
  921. tor_assert(result);
  922. tor_mutex_acquire(m);
  923. r = gmtime(timep);
  924. memcpy(result, r, sizeof(struct tm));
  925. tor_mutex_release(m);
  926. return result;
  927. }
  928. #else
  929. struct tm *
  930. tor_gmtime_r(const time_t *timep, struct tm *result)
  931. {
  932. struct tm *r;
  933. tor_assert(result);
  934. r = gmtime(timep);
  935. memcpy(result, r, sizeof(struct tm));
  936. return result;
  937. }
  938. #endif
  939. #endif
  940. #ifdef USE_WIN32_THREADS
  941. /** A generic lock structure for multithreaded builds. */
  942. struct tor_mutex_t {
  943. HANDLE handle;
  944. };
  945. tor_mutex_t *
  946. tor_mutex_new(void)
  947. {
  948. tor_mutex_t *m;
  949. m = tor_malloc_zero(sizeof(tor_mutex_t));
  950. m->handle = CreateMutex(NULL, FALSE, NULL);
  951. tor_assert(m->handle != NULL);
  952. return m;
  953. }
  954. void
  955. tor_mutex_free(tor_mutex_t *m)
  956. {
  957. CloseHandle(m->handle);
  958. tor_free(m);
  959. }
  960. void
  961. tor_mutex_acquire(tor_mutex_t *m)
  962. {
  963. DWORD r;
  964. r = WaitForSingleObject(m->handle, INFINITE);
  965. switch (r) {
  966. case WAIT_ABANDONED: /* holding thread exited. */
  967. case WAIT_OBJECT_0: /* we got the mutex normally. */
  968. break;
  969. case WAIT_TIMEOUT: /* Should never happen. */
  970. tor_assert(0);
  971. break;
  972. case WAIT_FAILED:
  973. warn(LD_GENERAL, "Failed to acquire mutex: %d", GetLastError());
  974. }
  975. }
  976. void
  977. tor_mutex_release(tor_mutex_t *m)
  978. {
  979. BOOL r;
  980. r = ReleaseMutex(m->handle);
  981. if (!r) {
  982. warn(LD_GENERAL, "Failed to release mutex: %d", GetLastError());
  983. }
  984. }
  985. unsigned long
  986. tor_get_thread_id(void)
  987. {
  988. return (unsigned long)GetCurrentThreadId();
  989. }
  990. #elif defined(USE_PTHREADS)
  991. /** A generic lock structure for multithreaded builds. */
  992. struct tor_mutex_t {
  993. pthread_mutex_t mutex;
  994. };
  995. tor_mutex_t *
  996. tor_mutex_new(void)
  997. {
  998. tor_mutex_t *mutex = tor_malloc_zero(sizeof(tor_mutex_t));
  999. pthread_mutex_init(&mutex->mutex, NULL);
  1000. return mutex;
  1001. }
  1002. void
  1003. tor_mutex_acquire(tor_mutex_t *m)
  1004. {
  1005. tor_assert(m);
  1006. pthread_mutex_lock(&m->mutex);
  1007. }
  1008. void
  1009. tor_mutex_release(tor_mutex_t *m)
  1010. {
  1011. tor_assert(m);
  1012. pthread_mutex_unlock(&m->mutex);
  1013. }
  1014. void
  1015. tor_mutex_free(tor_mutex_t *m)
  1016. {
  1017. tor_assert(m);
  1018. pthread_mutex_destroy(&m->mutex);
  1019. tor_free(m);
  1020. }
  1021. unsigned long
  1022. tor_get_thread_id(void)
  1023. {
  1024. union {
  1025. pthread_t thr;
  1026. unsigned long id;
  1027. } r;
  1028. r.thr = pthread_self();
  1029. return r.id;
  1030. }
  1031. #else
  1032. /** A generic lock structure for multithreaded builds. */
  1033. struct tor_mutex_t {
  1034. int _unused;
  1035. };
  1036. #endif
  1037. /**
  1038. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1039. * you need to ask the socket for its actual errno. Also, you need to
  1040. * get your errors from WSAGetLastError, not errno. (If you supply a
  1041. * socket of -1, we check WSAGetLastError, but don't correct
  1042. * WSAEWOULDBLOCKs.)
  1043. *
  1044. * The upshot of all of this is that when a socket call fails, you
  1045. * should call tor_socket_errno <em>at most once</em> on the failing
  1046. * socket to get the error.
  1047. */
  1048. #ifdef MS_WINDOWS
  1049. int
  1050. tor_socket_errno(int sock)
  1051. {
  1052. int optval, optvallen=sizeof(optval);
  1053. int err = WSAGetLastError();
  1054. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1055. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1056. return err;
  1057. if (optval)
  1058. return optval;
  1059. }
  1060. return err;
  1061. }
  1062. #endif
  1063. #ifdef MS_WINDOWS
  1064. #define E(code, s) { code, (s " [" #code " ]") }
  1065. struct { int code; const char *msg; } windows_socket_errors[] = {
  1066. E(WSAEINTR, "Interrupted function call"),
  1067. E(WSAEACCES, "Permission denied"),
  1068. E(WSAEFAULT, "Bad address"),
  1069. E(WSAEINVAL, "Invalid argument"),
  1070. E(WSAEMFILE, "Too many open files"),
  1071. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1072. E(WSAEINPROGRESS, "Operation now in progress"),
  1073. E(WSAEALREADY, "Operation already in progress"),
  1074. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1075. E(WSAEDESTADDRREQ, "Destination address required"),
  1076. E(WSAEMSGSIZE, "Message too long"),
  1077. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1078. E(WSAENOPROTOOPT, "Bad protocol option"),
  1079. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1080. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1081. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1082. E(WSAEOPNOTSUPP, "Operation not supported"),
  1083. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1084. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1085. E(WSAEADDRINUSE, "Address already in use"),
  1086. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1087. E(WSAENETDOWN, "Network is down"),
  1088. E(WSAENETUNREACH, "Network is unreachable"),
  1089. E(WSAENETRESET, "Network dropped connection on reset"),
  1090. E(WSAECONNABORTED, "Software caused connection abort"),
  1091. E(WSAECONNRESET, "Connection reset by peer"),
  1092. E(WSAENOBUFS, "No buffer space available"),
  1093. E(WSAEISCONN, "Socket is already connected"),
  1094. E(WSAENOTCONN, "Socket is not connected"),
  1095. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1096. E(WSAETIMEDOUT, "Connection timed out"),
  1097. E(WSAECONNREFUSED, "Connection refused"),
  1098. E(WSAEHOSTDOWN, "Host is down"),
  1099. E(WSAEHOSTUNREACH, "No route to host"),
  1100. E(WSAEPROCLIM, "Too many processes"),
  1101. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1102. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1103. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1104. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1105. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1106. #ifdef WSATYPE_NOT_FOUND
  1107. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1108. #endif
  1109. E(WSAHOST_NOT_FOUND, "Host not found"),
  1110. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1111. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1112. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1113. /* There are some more error codes whose numeric values are marked
  1114. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1115. * reason that practitioners of some craft traditions deliberately
  1116. * introduce imperfections into their baskets and rugs "to allow the
  1117. * evil spirits to escape." If we catch them, then our binaries
  1118. * might not report consistent results across versions of Windows.
  1119. * Thus, I'm going to let them all fall through.
  1120. */
  1121. { -1, NULL },
  1122. };
  1123. /** There does not seem to be a strerror equivalent for winsock errors.
  1124. * Naturally, we have to roll our own.
  1125. */
  1126. const char *
  1127. tor_socket_strerror(int e)
  1128. {
  1129. int i;
  1130. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1131. if (e == windows_socket_errors[i].code)
  1132. return windows_socket_errors[i].msg;
  1133. }
  1134. return strerror(e);
  1135. }
  1136. #endif
  1137. /** Called before we make any calls to network-related functions.
  1138. * (Some operating systems require their network libraries to be
  1139. * initialized.) */
  1140. int
  1141. network_init(void)
  1142. {
  1143. #ifdef MS_WINDOWS
  1144. /* This silly exercise is necessary before windows will allow
  1145. * gethostbyname to work. */
  1146. WSADATA WSAData;
  1147. int r;
  1148. r = WSAStartup(0x101,&WSAData);
  1149. if (r) {
  1150. warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1151. return -1;
  1152. }
  1153. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1154. * We might use it to complain if we're trying to be a server but have
  1155. * too few sockets available. */
  1156. #endif
  1157. return 0;
  1158. }