compat.c 27 KB

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