compat.c 28 KB

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