compat.c 34 KB

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