compat.c 35 KB

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