compat.c 37 KB

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