compat.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. /* Copyright 2003-2004 Roger Dingledine
  2. * Copyright 2004-2006 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. log_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. log_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. log_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. /** Learn the maximum allowed number of file descriptors. (Some systems
  419. * have a low soft limit.
  420. *
  421. * We compute this by finding the largest number between <b>limit</b>
  422. * and <b>cap</b> that we can use. If we can't find a number greater
  423. * than or equal to <b>limit</b>, then we fail: return -1.
  424. *
  425. * Otherwise, return the number minus some buffer to allow for other
  426. * file descriptors we'll want available for ordinary use. */
  427. int
  428. set_max_file_descriptors(unsigned long limit, unsigned long cap)
  429. {
  430. #ifndef HAVE_GETRLIMIT
  431. log_fn(LOG_INFO, LD_NET,
  432. "This platform is missing getrlimit(). Proceeding.");
  433. if (limit < cap) {
  434. log_info(LD_CONFIG, "ConnLimit must be at most %d. Using that.", cap);
  435. limit = cap;
  436. }
  437. #else
  438. struct rlimit rlim;
  439. unsigned long most;
  440. tor_assert(limit > 0);
  441. tor_assert(cap > 0);
  442. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  443. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  444. strerror(errno));
  445. return -1;
  446. }
  447. if (rlim.rlim_max < limit) {
  448. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  449. "limited to %lu. Please change your ulimit -n.",
  450. limit, (unsigned long)rlim.rlim_max);
  451. return -1;
  452. }
  453. most = (rlim.rlim_max > cap) ? cap : (unsigned) rlim.rlim_max;
  454. if (most > rlim.rlim_cur) {
  455. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  456. (unsigned long)rlim.rlim_cur, most);
  457. }
  458. rlim.rlim_cur = most;
  459. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  460. log_warn(LD_CONFIG, "Could not set maximum number of file descriptors: %s",
  461. strerror(errno));
  462. return -1;
  463. }
  464. /* leave some overhead for logs, etc, */
  465. limit = most;
  466. #endif
  467. if (limit < ULIMIT_BUFFER) {
  468. log_warn(LD_CONFIG,
  469. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  470. return -1;
  471. }
  472. return limit - ULIMIT_BUFFER;
  473. }
  474. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  475. * success. On failure, log and return -1.
  476. */
  477. int
  478. switch_id(char *user, char *group)
  479. {
  480. #ifndef MS_WINDOWS
  481. struct passwd *pw = NULL;
  482. struct group *gr = NULL;
  483. if (user) {
  484. pw = getpwnam(user);
  485. if (pw == NULL) {
  486. log_err(LD_CONFIG,"User '%s' not found.", user);
  487. return -1;
  488. }
  489. }
  490. /* switch the group first, while we still have the privileges to do so */
  491. if (group) {
  492. gr = getgrnam(group);
  493. if (gr == NULL) {
  494. log_err(LD_CONFIG,"Group '%s' not found.", group);
  495. return -1;
  496. }
  497. if (setgid(gr->gr_gid) != 0) {
  498. log_err(LD_GENERAL,"Error setting GID: %s", strerror(errno));
  499. return -1;
  500. }
  501. } else if (user) {
  502. if (setgid(pw->pw_gid) != 0) {
  503. log_err(LD_GENERAL,"Error setting GID: %s", strerror(errno));
  504. return -1;
  505. }
  506. }
  507. /* now that the group is switched, we can switch users and lose
  508. privileges */
  509. if (user) {
  510. if (setuid(pw->pw_uid) != 0) {
  511. log_err(LD_GENERAL,"Error setting UID: %s", strerror(errno));
  512. return -1;
  513. }
  514. }
  515. return 0;
  516. #endif
  517. log_err(LD_CONFIG,
  518. "User or group specified, but switching users is not supported.");
  519. return -1;
  520. }
  521. #ifdef HAVE_PWD_H
  522. /** Allocate and return a string containing the home directory for the
  523. * user <b>username</b>. Only works on posix-like systems */
  524. char *
  525. get_user_homedir(const char *username)
  526. {
  527. struct passwd *pw;
  528. tor_assert(username);
  529. if (!(pw = getpwnam(username))) {
  530. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  531. return NULL;
  532. }
  533. return tor_strdup(pw->pw_dir);
  534. }
  535. #endif
  536. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  537. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  538. * but works on Windows and Solaris.)
  539. */
  540. int
  541. tor_inet_aton(const char *c, struct in_addr* addr)
  542. {
  543. #ifdef HAVE_INET_ATON
  544. return inet_aton(c, addr);
  545. #else
  546. uint32_t r;
  547. tor_assert(c);
  548. tor_assert(addr);
  549. if (strcmp(c, "255.255.255.255") == 0) {
  550. addr->s_addr = 0xFFFFFFFFu;
  551. return 1;
  552. }
  553. r = inet_addr(c);
  554. if (r == INADDR_NONE)
  555. return 0;
  556. addr->s_addr = r;
  557. return 1;
  558. #endif
  559. }
  560. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  561. * *addr to the proper IP address, in network byte order. Returns 0
  562. * on success, -1 on failure; 1 on transient failure.
  563. *
  564. * (This function exists because standard windows gethostbyname
  565. * doesn't treat raw IP addresses properly.)
  566. */
  567. int
  568. tor_lookup_hostname(const char *name, uint32_t *addr)
  569. {
  570. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  571. * something.
  572. */
  573. struct in_addr iaddr;
  574. tor_assert(name);
  575. tor_assert(addr);
  576. if (!*name) {
  577. /* Empty address is an error. */
  578. return -1;
  579. } else if (tor_inet_aton(name, &iaddr)) {
  580. /* It's an IP. */
  581. memcpy(addr, &iaddr.s_addr, 4);
  582. return 0;
  583. } else {
  584. #ifdef HAVE_GETADDRINFO
  585. int err;
  586. struct addrinfo *res=NULL, *res_p;
  587. struct addrinfo hints;
  588. int result = -1;
  589. memset(&hints, 0, sizeof(hints));
  590. hints.ai_family = PF_INET;
  591. hints.ai_socktype = SOCK_STREAM;
  592. err = getaddrinfo(name, NULL, NULL, &res);
  593. if (!err) {
  594. for (res_p = res; res_p; res_p = res_p->ai_next) {
  595. if (res_p->ai_family == AF_INET) {
  596. struct sockaddr_in *sin = (struct sockaddr_in *)res_p->ai_addr;
  597. memcpy(addr, &sin->sin_addr, 4);
  598. result = 0;
  599. break;
  600. }
  601. }
  602. freeaddrinfo(res);
  603. return result;
  604. }
  605. return (err == EAI_AGAIN) ? 1 : -1;
  606. #else
  607. struct hostent *ent;
  608. int err;
  609. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  610. char buf[2048];
  611. struct hostent hostent;
  612. int r;
  613. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  614. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  615. char buf[2048];
  616. struct hostent hostent;
  617. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  618. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  619. struct hostent_data data;
  620. struct hostent hent;
  621. memset(&data, 0, sizeof(data));
  622. err = gethostbyname_r(name, &hent, &data);
  623. ent = err ? NULL : &hent;
  624. #else
  625. ent = gethostbyname(name);
  626. #ifdef MS_WINDOWS
  627. err = WSAGetLastError();
  628. #else
  629. err = h_errno;
  630. #endif
  631. #endif
  632. if (ent) {
  633. /* break to remind us if we move away from IPv4 */
  634. tor_assert(ent->h_length == 4);
  635. memcpy(addr, ent->h_addr, 4);
  636. return 0;
  637. }
  638. memset(addr, 0, 4);
  639. #ifdef MS_WINDOWS
  640. return (err == WSATRY_AGAIN) ? 1 : -1;
  641. #else
  642. return (err == TRY_AGAIN) ? 1 : -1;
  643. #endif
  644. #endif
  645. }
  646. }
  647. /** Hold the result of our call to <b>uname</b>. */
  648. static char uname_result[256];
  649. /** True iff uname_result is set. */
  650. static int uname_result_is_set = 0;
  651. /** Return a pointer to a description of our platform.
  652. */
  653. const char *
  654. get_uname(void)
  655. {
  656. #ifdef HAVE_UNAME
  657. struct utsname u;
  658. #endif
  659. if (!uname_result_is_set) {
  660. #ifdef HAVE_UNAME
  661. if (uname(&u) != -1) {
  662. /* (linux says 0 is success, solaris says 1 is success) */
  663. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  664. u.sysname, u.machine);
  665. } else
  666. #endif
  667. {
  668. #ifdef MS_WINDOWS
  669. OSVERSIONINFOEX info;
  670. int i;
  671. unsigned int leftover_mask;
  672. const char *plat = NULL;
  673. static struct {
  674. int major; int minor; const char *version;
  675. } win_version_table[] = {
  676. { 6, 0, "Windows \"Longhorn\"" },
  677. { 5, 2, "Windows Server 2003" },
  678. { 5, 1, "Windows XP" },
  679. { 5, 0, "Windows 2000" },
  680. /* { 4, 0, "Windows NT 4.0" }, */
  681. { 4, 90, "Windows Me" },
  682. { 4, 10, "Windows 98" },
  683. /* { 4, 0, "Windows 95" } */
  684. { 3, 51, "Windows NT 3.51" },
  685. { -1, -1, NULL }
  686. };
  687. static struct {
  688. unsigned int mask; const char *str;
  689. } win_mask_table[] = {
  690. { VER_SUITE_BACKOFFICE, " {backoffice}" },
  691. { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
  692. { VER_SUITE_DATACENTER, " {datacenter}" },
  693. { VER_SUITE_ENTERPRISE, " {enterprise}" },
  694. { VER_SUITE_EMBEDDEDNT, " {embedded}" },
  695. { VER_SUITE_PERSONAL, " {personal}" },
  696. { VER_SUITE_SINGLEUSERTS,
  697. " {terminal services, single user}" },
  698. { VER_SUITE_SMALLBUSINESS, " {small business}" },
  699. { VER_SUITE_SMALLBUSINESS_RESTRICTED,
  700. " {small business, restricted}" },
  701. { VER_SUITE_TERMINAL, " {terminal services}" },
  702. { 0, NULL },
  703. };
  704. memset(&info, 0, sizeof(info));
  705. info.dwOSVersionInfoSize = sizeof(info);
  706. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  707. int err = GetLastError();
  708. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  709. " doesn't work.", sizeof(uname_result));
  710. uname_result_is_set = 1;
  711. return uname_result;
  712. }
  713. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  714. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  715. plat = "Windows NT 4.0";
  716. else
  717. plat = "Windows 95";
  718. } else {
  719. for (i=0; win_version_table[i].major>=0; ++i) {
  720. if (win_version_table[i].major == info.dwMajorVersion &&
  721. win_version_table[i].minor == info.dwMinorVersion) {
  722. plat = win_version_table[i].version;
  723. break;
  724. }
  725. }
  726. }
  727. if (plat) {
  728. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  729. plat, info.szCSDVersion);
  730. } else {
  731. if (info.dwMajorVersion > 6 ||
  732. (info.dwMajorVersion==6 && info.dwMinorVersion>0))
  733. tor_snprintf(uname_result, sizeof(uname_result),
  734. "Very recent version of Windows [major=%d,minor=%d] %s",
  735. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  736. info.szCSDVersion);
  737. else
  738. tor_snprintf(uname_result, sizeof(uname_result),
  739. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  740. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  741. info.szCSDVersion);
  742. }
  743. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  744. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  745. } else if (info.wProductType == VER_NT_SERVER) {
  746. strlcat(uname_result, " [server]", sizeof(uname_result));
  747. } else if (info.wProductType == VER_NT_WORKSTATION) {
  748. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  749. }
  750. leftover_mask = info.wSuiteMask;
  751. for (i = 0; win_mask_table[i].mask; ++i) {
  752. if (info.wSuiteMask & win_mask_table[i].mask) {
  753. strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
  754. leftover_mask &= ~win_mask_table[i].mask;
  755. }
  756. }
  757. if (leftover_mask) {
  758. size_t len = strlen(uname_result);
  759. tor_snprintf(uname_result+len, sizeof(uname_result)-len,
  760. " {0x%x}", info.wSuiteMask);
  761. }
  762. #else
  763. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  764. #endif
  765. }
  766. uname_result_is_set = 1;
  767. }
  768. return uname_result;
  769. }
  770. /*
  771. * Process control
  772. */
  773. #if defined(USE_PTHREADS)
  774. /** Wraps a an int (*)(void*) function and its argument so we can
  775. * invoke them in a way pthreads would expect.
  776. */
  777. typedef struct tor_pthread_data_t {
  778. int (*func)(void *);
  779. void *data;
  780. } tor_pthread_data_t;
  781. static void *
  782. tor_pthread_helper_fn(void *_data)
  783. {
  784. tor_pthread_data_t *data = _data;
  785. int (*func)(void*);
  786. void *arg;
  787. func = data->func;
  788. arg = data->data;
  789. tor_free(_data);
  790. func(arg);
  791. return NULL;
  792. }
  793. #endif
  794. /** Minimalist interface to run a void function in the background. On
  795. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  796. * func should not return, but rather should call spawn_exit.
  797. *
  798. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  799. * since in a multithreaded environment, there is no way to be sure that
  800. * the caller's stack will still be around when the called function is
  801. * running.
  802. */
  803. int
  804. spawn_func(int (*func)(void *), void *data)
  805. {
  806. #if defined(USE_WIN32_THREADS)
  807. int rv;
  808. rv = _beginthread(func, 0, data);
  809. if (rv == (unsigned long) -1)
  810. return -1;
  811. return 0;
  812. #elif defined(USE_PTHREADS)
  813. pthread_t thread;
  814. tor_pthread_data_t *d;
  815. d = tor_malloc(sizeof(tor_pthread_data_t));
  816. d->data = data;
  817. d->func = func;
  818. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  819. return -1;
  820. if (pthread_detach(thread))
  821. return -1;
  822. return 0;
  823. #else
  824. pid_t pid;
  825. pid = fork();
  826. if (pid<0)
  827. return -1;
  828. if (pid==0) {
  829. /* Child */
  830. func(data);
  831. tor_assert(0); /* Should never reach here. */
  832. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  833. } else {
  834. /* Parent */
  835. return 0;
  836. }
  837. #endif
  838. }
  839. /** End the current thread/process.
  840. */
  841. void
  842. spawn_exit(void)
  843. {
  844. #if defined(USE_WIN32_THREADS)
  845. _endthread();
  846. #elif defined(USE_PTHREADS)
  847. pthread_exit(NULL);
  848. #else
  849. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  850. * call _exit, not exit, from child processes. */
  851. _exit(0);
  852. #endif
  853. }
  854. /** Set *timeval to the current time of day. On error, log and terminate.
  855. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  856. */
  857. void
  858. tor_gettimeofday(struct timeval *timeval)
  859. {
  860. #ifdef MS_WINDOWS
  861. /* Epoch bias copied from perl: number of units between windows epoch and
  862. * unix epoch. */
  863. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  864. #define UNITS_PER_SEC U64_LITERAL(10000000)
  865. #define USEC_PER_SEC U64_LITERAL(1000000)
  866. #define UNITS_PER_USEC U64_LITERAL(10)
  867. union {
  868. uint64_t ft_64;
  869. FILETIME ft_ft;
  870. } ft;
  871. /* number of 100-nsec units since Jan 1, 1601 */
  872. GetSystemTimeAsFileTime(&ft.ft_ft);
  873. if (ft.ft_64 < EPOCH_BIAS) {
  874. log_err(LD_GENERAL,"System time is before 1970; failing.");
  875. exit(1);
  876. }
  877. ft.ft_64 -= EPOCH_BIAS;
  878. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  879. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  880. #elif defined(HAVE_GETTIMEOFDAY)
  881. if (gettimeofday(timeval, NULL)) {
  882. log_err(LD_GENERAL,"gettimeofday failed.");
  883. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  884. or segfaulted.*/
  885. exit(1);
  886. }
  887. #elif defined(HAVE_FTIME)
  888. struct timeb tb;
  889. ftime(&tb);
  890. timeval->tv_sec = tb.time;
  891. timeval->tv_usec = tb.millitm * 1000;
  892. #else
  893. #error "No way to get time."
  894. #endif
  895. return;
  896. }
  897. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  898. #define TIME_FNS_NEED_LOCKS
  899. #endif
  900. #ifndef HAVE_LOCALTIME_R
  901. #ifdef TIME_FNS_NEED_LOCKS
  902. struct tm *
  903. tor_localtime_r(const time_t *timep, struct tm *result)
  904. {
  905. struct tm *r;
  906. static tor_mutex_t *m=NULL;
  907. if (!m) { m=tor_mutex_new(); }
  908. tor_assert(result);
  909. tor_mutex_acquire(m);
  910. r = localtime(timep);
  911. memcpy(result, r, sizeof(struct tm));
  912. tor_mutex_release(m);
  913. return result;
  914. }
  915. #else
  916. struct tm *
  917. tor_localtime_r(const time_t *timep, struct tm *result)
  918. {
  919. struct tm *r;
  920. tor_assert(result);
  921. r = localtime(timep);
  922. memcpy(result, r, sizeof(struct tm));
  923. return result;
  924. }
  925. #endif
  926. #endif
  927. #ifndef HAVE_GMTIME_R
  928. #ifdef TIME_FNS_NEED_LOCKS
  929. struct tm *
  930. tor_gmtime_r(const time_t *timep, struct tm *result)
  931. {
  932. struct tm *r;
  933. static tor_mutex_t *m=NULL;
  934. if (!m) { m=tor_mutex_new(); }
  935. tor_assert(result);
  936. tor_mutex_acquire(m);
  937. r = gmtime(timep);
  938. memcpy(result, r, sizeof(struct tm));
  939. tor_mutex_release(m);
  940. return result;
  941. }
  942. #else
  943. struct tm *
  944. tor_gmtime_r(const time_t *timep, struct tm *result)
  945. {
  946. struct tm *r;
  947. tor_assert(result);
  948. r = gmtime(timep);
  949. memcpy(result, r, sizeof(struct tm));
  950. return result;
  951. }
  952. #endif
  953. #endif
  954. #ifdef USE_WIN32_THREADS
  955. /** A generic lock structure for multithreaded builds. */
  956. struct tor_mutex_t {
  957. HANDLE handle;
  958. };
  959. tor_mutex_t *
  960. tor_mutex_new(void)
  961. {
  962. tor_mutex_t *m;
  963. m = tor_malloc_zero(sizeof(tor_mutex_t));
  964. m->handle = CreateMutex(NULL, FALSE, NULL);
  965. tor_assert(m->handle != NULL);
  966. return m;
  967. }
  968. void
  969. tor_mutex_free(tor_mutex_t *m)
  970. {
  971. CloseHandle(m->handle);
  972. tor_free(m);
  973. }
  974. void
  975. tor_mutex_acquire(tor_mutex_t *m)
  976. {
  977. DWORD r;
  978. r = WaitForSingleObject(m->handle, INFINITE);
  979. switch (r) {
  980. case WAIT_ABANDONED: /* holding thread exited. */
  981. case WAIT_OBJECT_0: /* we got the mutex normally. */
  982. break;
  983. case WAIT_TIMEOUT: /* Should never happen. */
  984. tor_assert(0);
  985. break;
  986. case WAIT_FAILED:
  987. log_warn(LD_GENERAL, "Failed to acquire mutex: %d", GetLastError());
  988. }
  989. }
  990. void
  991. tor_mutex_release(tor_mutex_t *m)
  992. {
  993. BOOL r;
  994. r = ReleaseMutex(m->handle);
  995. if (!r) {
  996. log_warn(LD_GENERAL, "Failed to release mutex: %d", GetLastError());
  997. }
  998. }
  999. unsigned long
  1000. tor_get_thread_id(void)
  1001. {
  1002. return (unsigned long)GetCurrentThreadId();
  1003. }
  1004. #elif defined(USE_PTHREADS)
  1005. /** A generic lock structure for multithreaded builds. */
  1006. struct tor_mutex_t {
  1007. pthread_mutex_t mutex;
  1008. };
  1009. tor_mutex_t *
  1010. tor_mutex_new(void)
  1011. {
  1012. tor_mutex_t *mutex = tor_malloc_zero(sizeof(tor_mutex_t));
  1013. pthread_mutex_init(&mutex->mutex, NULL);
  1014. return mutex;
  1015. }
  1016. void
  1017. tor_mutex_acquire(tor_mutex_t *m)
  1018. {
  1019. tor_assert(m);
  1020. pthread_mutex_lock(&m->mutex);
  1021. }
  1022. void
  1023. tor_mutex_release(tor_mutex_t *m)
  1024. {
  1025. tor_assert(m);
  1026. pthread_mutex_unlock(&m->mutex);
  1027. }
  1028. void
  1029. tor_mutex_free(tor_mutex_t *m)
  1030. {
  1031. tor_assert(m);
  1032. pthread_mutex_destroy(&m->mutex);
  1033. tor_free(m);
  1034. }
  1035. unsigned long
  1036. tor_get_thread_id(void)
  1037. {
  1038. union {
  1039. pthread_t thr;
  1040. unsigned long id;
  1041. } r;
  1042. r.thr = pthread_self();
  1043. return r.id;
  1044. }
  1045. #else
  1046. /** A generic lock structure for multithreaded builds. */
  1047. struct tor_mutex_t {
  1048. int _unused;
  1049. };
  1050. #endif
  1051. /**
  1052. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1053. * you need to ask the socket for its actual errno. Also, you need to
  1054. * get your errors from WSAGetLastError, not errno. (If you supply a
  1055. * socket of -1, we check WSAGetLastError, but don't correct
  1056. * WSAEWOULDBLOCKs.)
  1057. *
  1058. * The upshot of all of this is that when a socket call fails, you
  1059. * should call tor_socket_errno <em>at most once</em> on the failing
  1060. * socket to get the error.
  1061. */
  1062. #ifdef MS_WINDOWS
  1063. int
  1064. tor_socket_errno(int sock)
  1065. {
  1066. int optval, optvallen=sizeof(optval);
  1067. int err = WSAGetLastError();
  1068. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1069. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1070. return err;
  1071. if (optval)
  1072. return optval;
  1073. }
  1074. return err;
  1075. }
  1076. #endif
  1077. #ifdef MS_WINDOWS
  1078. #define E(code, s) { code, (s " [" #code " ]") }
  1079. struct { int code; const char *msg; } windows_socket_errors[] = {
  1080. E(WSAEINTR, "Interrupted function call"),
  1081. E(WSAEACCES, "Permission denied"),
  1082. E(WSAEFAULT, "Bad address"),
  1083. E(WSAEINVAL, "Invalid argument"),
  1084. E(WSAEMFILE, "Too many open files"),
  1085. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1086. E(WSAEINPROGRESS, "Operation now in progress"),
  1087. E(WSAEALREADY, "Operation already in progress"),
  1088. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1089. E(WSAEDESTADDRREQ, "Destination address required"),
  1090. E(WSAEMSGSIZE, "Message too long"),
  1091. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1092. E(WSAENOPROTOOPT, "Bad protocol option"),
  1093. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1094. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1095. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1096. E(WSAEOPNOTSUPP, "Operation not supported"),
  1097. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1098. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1099. E(WSAEADDRINUSE, "Address already in use"),
  1100. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1101. E(WSAENETDOWN, "Network is down"),
  1102. E(WSAENETUNREACH, "Network is unreachable"),
  1103. E(WSAENETRESET, "Network dropped connection on reset"),
  1104. E(WSAECONNABORTED, "Software caused connection abort"),
  1105. E(WSAECONNRESET, "Connection reset by peer"),
  1106. E(WSAENOBUFS, "No buffer space available"),
  1107. E(WSAEISCONN, "Socket is already connected"),
  1108. E(WSAENOTCONN, "Socket is not connected"),
  1109. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1110. E(WSAETIMEDOUT, "Connection timed out"),
  1111. E(WSAECONNREFUSED, "Connection refused"),
  1112. E(WSAEHOSTDOWN, "Host is down"),
  1113. E(WSAEHOSTUNREACH, "No route to host"),
  1114. E(WSAEPROCLIM, "Too many processes"),
  1115. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1116. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1117. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1118. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1119. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1120. #ifdef WSATYPE_NOT_FOUND
  1121. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1122. #endif
  1123. E(WSAHOST_NOT_FOUND, "Host not found"),
  1124. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1125. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1126. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1127. /* There are some more error codes whose numeric values are marked
  1128. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1129. * reason that practitioners of some craft traditions deliberately
  1130. * introduce imperfections into their baskets and rugs "to allow the
  1131. * evil spirits to escape." If we catch them, then our binaries
  1132. * might not report consistent results across versions of Windows.
  1133. * Thus, I'm going to let them all fall through.
  1134. */
  1135. { -1, NULL },
  1136. };
  1137. /** There does not seem to be a strerror equivalent for winsock errors.
  1138. * Naturally, we have to roll our own.
  1139. */
  1140. const char *
  1141. tor_socket_strerror(int e)
  1142. {
  1143. int i;
  1144. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1145. if (e == windows_socket_errors[i].code)
  1146. return windows_socket_errors[i].msg;
  1147. }
  1148. return strerror(e);
  1149. }
  1150. #endif
  1151. /** Called before we make any calls to network-related functions.
  1152. * (Some operating systems require their network libraries to be
  1153. * initialized.) */
  1154. int
  1155. network_init(void)
  1156. {
  1157. #ifdef MS_WINDOWS
  1158. /* This silly exercise is necessary before windows will allow
  1159. * gethostbyname to work. */
  1160. WSADATA WSAData;
  1161. int r;
  1162. r = WSAStartup(0x101,&WSAData);
  1163. if (r) {
  1164. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1165. return -1;
  1166. }
  1167. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1168. * We might use it to complain if we're trying to be a server but have
  1169. * too few sockets available. */
  1170. #endif
  1171. return 0;
  1172. }