compat.c 28 KB

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