compat.c 30 KB

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