compat.c 36 KB

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