compat.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998
  1. /* Copyright 2003-2004 Roger Dingledine
  2. * Copyright 2004-2007 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_SIGNAL_H
  81. #include <signal.h>
  82. #endif
  83. #ifdef HAVE_UTIME_H
  84. #include <utime.h>
  85. #endif
  86. #ifdef HAVE_SYS_UTIME_H
  87. #include <sys/utime.h>
  88. #endif
  89. #ifdef HAVE_SYS_MMAN_H
  90. #include <sys/mman.h>
  91. #endif
  92. #ifdef HAVE_SYS_SYSLIMITS_H
  93. #include <sys/syslimits.h>
  94. #endif
  95. #ifdef USE_BSOCKETS
  96. #include <bsocket.h>
  97. #endif
  98. #include "log.h"
  99. #include "util.h"
  100. #include "container.h"
  101. /* Inline the strl functions if the platform doesn't have them. */
  102. #ifndef HAVE_STRLCPY
  103. #include "strlcpy.c"
  104. #endif
  105. #ifndef HAVE_STRLCAT
  106. #include "strlcat.c"
  107. #endif
  108. #ifndef INADDR_NONE
  109. /* This is used by inet_addr, but apparently Solaris doesn't define it
  110. * anyplace. */
  111. #define INADDR_NONE ((unsigned long) -1)
  112. #endif
  113. #ifdef HAVE_SYS_MMAN_H
  114. /** Implementation for tor_mmap_t: holds the regular tor_mmap_t, along
  115. * with extra fields needed for mmap()-based memory mapping. */
  116. typedef struct tor_mmap_impl_t {
  117. tor_mmap_t base;
  118. size_t mapping_size; /**< Size of the actual mapping. (This is this file
  119. * size, rounded up to the nearest page.) */
  120. } tor_mmap_impl_t;
  121. /** Try to create a memory mapping for <b>filename</b> and return it. On
  122. * failure, return NULL. Sets errno properly, using ERANGE to mean
  123. * "empty file". */
  124. tor_mmap_t *
  125. tor_mmap_file(const char *filename)
  126. {
  127. int fd; /* router file */
  128. char *string;
  129. int page_size;
  130. tor_mmap_impl_t *res;
  131. size_t size, filesize;
  132. tor_assert(filename);
  133. fd = open(filename, O_RDONLY, 0);
  134. if (fd<0) {
  135. int save_errno = errno;
  136. int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
  137. log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
  138. strerror(errno));
  139. errno = save_errno;
  140. return NULL;
  141. }
  142. size = filesize = (size_t) lseek(fd, 0, SEEK_END);
  143. lseek(fd, 0, SEEK_SET);
  144. /* ensure page alignment */
  145. page_size = getpagesize();
  146. size += (size%page_size) ? page_size-(size%page_size) : 0;
  147. if (!size) {
  148. /* Zero-length file. If we call mmap on it, it will succeed but
  149. * return NULL, and bad things will happen. So just fail. */
  150. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  151. errno = ERANGE;
  152. return NULL;
  153. }
  154. string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  155. if (string == MAP_FAILED) {
  156. int save_errno = errno;
  157. close(fd);
  158. log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
  159. strerror(errno));
  160. errno = save_errno;
  161. return NULL;
  162. }
  163. close(fd);
  164. res = tor_malloc_zero(sizeof(tor_mmap_impl_t));
  165. res->base.data = string;
  166. res->base.size = filesize;
  167. res->mapping_size = size;
  168. return &(res->base);
  169. }
  170. /** Release storage held for a memory mapping. */
  171. void
  172. tor_munmap_file(tor_mmap_t *handle)
  173. {
  174. tor_mmap_impl_t *h = SUBTYPE_P(handle, tor_mmap_impl_t, base);
  175. munmap((char*)h->base.data, h->mapping_size);
  176. tor_free(h);
  177. }
  178. #elif defined(MS_WINDOWS)
  179. /** Implementation for tor_mmap_t: holds the regular tor_mmap_t, along
  180. * with extra fields needed for WIN32 memory mapping. */
  181. typedef struct win_mmap_t {
  182. tor_mmap_t base;
  183. HANDLE file_handle;
  184. HANDLE mmap_handle;
  185. } win_mmap_t;
  186. tor_mmap_t *
  187. tor_mmap_file(const char *filename)
  188. {
  189. win_mmap_t *res = tor_malloc_zero(sizeof(win_mmap_t));
  190. int empty = 0;
  191. res->file_handle = INVALID_HANDLE_VALUE;
  192. res->mmap_handle = NULL;
  193. res->file_handle = CreateFile(filename,
  194. GENERIC_READ, FILE_SHARE_READ,
  195. NULL,
  196. OPEN_EXISTING,
  197. FILE_ATTRIBUTE_NORMAL,
  198. 0);
  199. if (res->file_handle == INVALID_HANDLE_VALUE)
  200. goto win_err;
  201. res->base.size = GetFileSize(res->file_handle, NULL);
  202. if (res->base.size == 0) {
  203. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  204. empty = 1;
  205. goto err;
  206. }
  207. res->mmap_handle = CreateFileMapping(res->file_handle,
  208. NULL,
  209. PAGE_READONLY,
  210. #if SIZEOF_SIZE_T > 4
  211. (res->base.size >> 32),
  212. #else
  213. 0,
  214. #endif
  215. (res->base.size & 0xfffffffful),
  216. NULL);
  217. if (res->mmap_handle == NULL)
  218. goto win_err;
  219. res->base.data = (char*) MapViewOfFile(res->mmap_handle,
  220. FILE_MAP_READ,
  221. 0, 0, 0);
  222. if (!res->base.data)
  223. goto win_err;
  224. return &(res->base);
  225. win_err: {
  226. DWORD e = GetLastError();
  227. int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
  228. LOG_INFO : LOG_WARN;
  229. char *msg = format_win32_error(e);
  230. log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
  231. tor_free(msg);
  232. if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
  233. errno = ENOENT;
  234. else
  235. errno = EINVAL;
  236. }
  237. err:
  238. if (empty)
  239. errno = ERANGE;
  240. tor_munmap_file(&res->base);
  241. return NULL;
  242. }
  243. void
  244. tor_munmap_file(tor_mmap_t *handle)
  245. {
  246. win_mmap_t *h = SUBTYPE_P(handle, win_mmap_t, base);
  247. if (handle->data)
  248. /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
  249. have to be redefined as non-const. */
  250. UnmapViewOfFile( (LPVOID) handle->data);
  251. if (h->mmap_handle != NULL)
  252. CloseHandle(h->mmap_handle);
  253. if (h->file_handle != INVALID_HANDLE_VALUE)
  254. CloseHandle(h->file_handle);
  255. tor_free(h);
  256. }
  257. #else
  258. tor_mmap_t *
  259. tor_mmap_file(const char *filename)
  260. {
  261. struct stat st;
  262. char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  263. tor_mmap_t *handle;
  264. if (! res)
  265. return NULL;
  266. handle = tor_malloc_zero(sizeof(tor_mmap_t));
  267. handle->data = res;
  268. handle->size = st.st_size;
  269. return handle;
  270. }
  271. void
  272. tor_munmap_file(tor_mmap_t *handle)
  273. {
  274. char *d = (char*)handle->data;
  275. tor_free(d);
  276. memset(handle, 0, sizeof(tor_mmap_t));
  277. tor_free(handle);
  278. }
  279. #endif
  280. /** Replacement for snprintf. Differs from platform snprintf in two
  281. * ways: First, always NUL-terminates its output. Second, always
  282. * returns -1 if the result is truncated. (Note that this return
  283. * behavior does <i>not</i> conform to C99; it just happens to be
  284. * easier to emulate "return -1" with conformant implementations than
  285. * it is to emulate "return number that would be written" with
  286. * non-conformant implementations.) */
  287. int
  288. tor_snprintf(char *str, size_t size, const char *format, ...)
  289. {
  290. va_list ap;
  291. int r;
  292. va_start(ap,format);
  293. r = tor_vsnprintf(str,size,format,ap);
  294. va_end(ap);
  295. return r;
  296. }
  297. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  298. * snprintf.
  299. */
  300. int
  301. tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  302. {
  303. int r;
  304. if (size == 0)
  305. return -1; /* no place for the NUL */
  306. if (size > SIZE_T_CEILING)
  307. return -1;
  308. #ifdef MS_WINDOWS
  309. r = _vsnprintf(str, size, format, args);
  310. #else
  311. r = vsnprintf(str, size, format, args);
  312. #endif
  313. str[size-1] = '\0';
  314. if (r < 0 || ((size_t)r) >= size)
  315. return -1;
  316. return r;
  317. }
  318. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  319. * <b>needle</b>, return a pointer to the first occurrence of the needle
  320. * within the haystack, or NULL if there is no such occurrence.
  321. *
  322. * Requires that nlen be greater than zero.
  323. */
  324. const void *
  325. tor_memmem(const void *_haystack, size_t hlen,
  326. const void *_needle, size_t nlen)
  327. {
  328. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  329. tor_assert(nlen);
  330. return memmem(_haystack, hlen, _needle, nlen);
  331. #else
  332. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  333. * be. */
  334. const char *p, *end;
  335. const char *haystack = (const char*)_haystack;
  336. const char *needle = (const char*)_needle;
  337. char first;
  338. tor_assert(nlen);
  339. p = haystack;
  340. end = haystack + hlen;
  341. first = *(const char*)needle;
  342. while ((p = memchr(p, first, end-p))) {
  343. if (p+nlen > end)
  344. return NULL;
  345. if (!memcmp(p, needle, nlen))
  346. return p;
  347. ++p;
  348. }
  349. return NULL;
  350. #endif
  351. }
  352. #ifdef MS_WINDOWS
  353. /** Take a filename and return a pointer to its final element. This
  354. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  355. * contains the full path to the file. This is bad, because it
  356. * confuses users to find the home directory of the person who
  357. * compiled the binary in their warrning messages.
  358. */
  359. const char *
  360. tor_fix_source_file(const char *fname)
  361. {
  362. const char *cp1, *cp2, *r;
  363. cp1 = strrchr(fname, '/');
  364. cp2 = strrchr(fname, '\\');
  365. if (cp1 && cp2) {
  366. r = (cp1<cp2)?(cp2+1):(cp1+1);
  367. } else if (cp1) {
  368. r = cp1+1;
  369. } else if (cp2) {
  370. r = cp2+1;
  371. } else {
  372. r = fname;
  373. }
  374. return r;
  375. }
  376. #endif
  377. /**
  378. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  379. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  380. * unaligned memory access.
  381. */
  382. uint16_t
  383. get_uint16(const char *cp)
  384. {
  385. uint16_t v;
  386. memcpy(&v,cp,2);
  387. return v;
  388. }
  389. /**
  390. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  391. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  392. * unaligned memory access.
  393. */
  394. uint32_t
  395. get_uint32(const char *cp)
  396. {
  397. uint32_t v;
  398. memcpy(&v,cp,4);
  399. return v;
  400. }
  401. /**
  402. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  403. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  404. * unaligned memory access. */
  405. void
  406. set_uint16(char *cp, uint16_t v)
  407. {
  408. memcpy(cp,&v,2);
  409. }
  410. /**
  411. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  412. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  413. * unaligned memory access. */
  414. void
  415. set_uint32(char *cp, uint32_t v)
  416. {
  417. memcpy(cp,&v,4);
  418. }
  419. /**
  420. * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
  421. * the same as rename(2). On windows, this removes <b>to</b> first if
  422. * it already exists.
  423. * Returns 0 on success. Returns -1 and sets errno on failure.
  424. */
  425. int
  426. replace_file(const char *from, const char *to)
  427. {
  428. #ifndef MS_WINDOWS
  429. return rename(from,to);
  430. #else
  431. switch (file_status(to))
  432. {
  433. case FN_NOENT:
  434. break;
  435. case FN_FILE:
  436. if (unlink(to)) return -1;
  437. break;
  438. case FN_ERROR:
  439. return -1;
  440. case FN_DIR:
  441. errno = EISDIR;
  442. return -1;
  443. }
  444. return rename(from,to);
  445. #endif
  446. }
  447. /** Change <b>fname</b>'s modification time to now. */
  448. int
  449. touch_file(const char *fname)
  450. {
  451. if (utime(fname, NULL)!=0)
  452. return -1;
  453. return 0;
  454. }
  455. /** Count of number of sockets currently open. (Undercounts sockets opened by
  456. * eventdns and libevent.) */
  457. static int n_sockets_open = 0;
  458. /** As close(), but guaranteed to work for sockets across platforms (including
  459. * Windows, where close()ing a socket doesn't work. */
  460. void
  461. tor_close_socket(int s)
  462. {
  463. /* On Windows, you have to call close() on fds returned by open(),
  464. * and closesocket() on fds returned by socket(). On Unix, everything
  465. * gets close()'d. We abstract this difference by always using
  466. * tor_close_socket to close sockets, and always using close() on
  467. * files.
  468. */
  469. #ifdef USE_BSOCKETS
  470. bclose(s);
  471. #elif defined(MS_WINDOWS)
  472. closesocket(s);
  473. #else
  474. close(s);
  475. #endif
  476. --n_sockets_open;
  477. }
  478. /** As socket(), but counts the number of open sockets. */
  479. int
  480. tor_open_socket(int domain, int type, int protocol)
  481. {
  482. int s = socket(domain, type, protocol);
  483. if (s >= 0)
  484. ++n_sockets_open;
  485. return s;
  486. }
  487. /** Return the number of sockets we currently have opened. */
  488. int
  489. get_n_open_sockets(void)
  490. {
  491. return n_sockets_open;
  492. }
  493. /** Turn <b>socket</b> into a nonblocking socket.
  494. */
  495. void
  496. set_socket_nonblocking(int socket)
  497. {
  498. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  499. unsigned long nonblocking = 1;
  500. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  501. #else
  502. fcntl(socket, F_SETFL, O_NONBLOCK);
  503. #endif
  504. }
  505. /**
  506. * Allocate a pair of connected sockets. (Like socketpair(family,
  507. * type,protocol,fd), but works on systems that don't have
  508. * socketpair.)
  509. *
  510. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  511. *
  512. * Note that on systems without socketpair, this call will fail if
  513. * localhost is inaccessible (for example, if the networking
  514. * stack is down). And even if it succeeds, the socket pair will not
  515. * be able to read while localhost is down later (the socket pair may
  516. * even close, depending on OS-specific timeouts).
  517. *
  518. * Returns 0 on success and -errno on failure; do not rely on the value
  519. * of errno or WSAGetLastError().
  520. **/
  521. /* It would be nicer just to set errno, but that won't work for windows. */
  522. int
  523. tor_socketpair(int family, int type, int protocol, int fd[2])
  524. {
  525. //don't use win32 socketpairs (they are always bad)
  526. #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
  527. int r;
  528. r = socketpair(family, type, protocol, fd);
  529. return r < 0 ? -errno : r;
  530. #elif defined(USE_BSOCKETS)
  531. return bsocketpair(family, type, protocol, fd);
  532. #else
  533. /* This socketpair does not work when localhost is down. So
  534. * it's really not the same thing at all. But it's close enough
  535. * for now, and really, when localhost is down sometimes, we
  536. * have other problems too.
  537. */
  538. int listener = -1;
  539. int connector = -1;
  540. int acceptor = -1;
  541. struct sockaddr_in listen_addr;
  542. struct sockaddr_in connect_addr;
  543. int size;
  544. int saved_errno = -1;
  545. if (protocol
  546. #ifdef AF_UNIX
  547. || family != AF_UNIX
  548. #endif
  549. ) {
  550. #ifdef MS_WINDOWS
  551. return -WSAEAFNOSUPPORT;
  552. #else
  553. return -EAFNOSUPPORT;
  554. #endif
  555. }
  556. if (!fd) {
  557. return -EINVAL;
  558. }
  559. listener = tor_open_socket(AF_INET, type, 0);
  560. if (listener < 0)
  561. return -tor_socket_errno(-1);
  562. memset(&listen_addr, 0, sizeof(listen_addr));
  563. listen_addr.sin_family = AF_INET;
  564. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  565. listen_addr.sin_port = 0; /* kernel chooses port. */
  566. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  567. == -1)
  568. goto tidy_up_and_fail;
  569. if (listen(listener, 1) == -1)
  570. goto tidy_up_and_fail;
  571. connector = tor_open_socket(AF_INET, type, 0);
  572. if (connector < 0)
  573. goto tidy_up_and_fail;
  574. /* We want to find out the port number to connect to. */
  575. size = sizeof(connect_addr);
  576. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  577. goto tidy_up_and_fail;
  578. if (size != sizeof (connect_addr))
  579. goto abort_tidy_up_and_fail;
  580. if (connect(connector, (struct sockaddr *) &connect_addr,
  581. sizeof(connect_addr)) == -1)
  582. goto tidy_up_and_fail;
  583. size = sizeof(listen_addr);
  584. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  585. if (acceptor < 0)
  586. goto tidy_up_and_fail;
  587. if (size != sizeof(listen_addr))
  588. goto abort_tidy_up_and_fail;
  589. tor_close_socket(listener);
  590. /* Now check we are talking to ourself by matching port and host on the
  591. two sockets. */
  592. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  593. goto tidy_up_and_fail;
  594. if (size != sizeof (connect_addr)
  595. || listen_addr.sin_family != connect_addr.sin_family
  596. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  597. || listen_addr.sin_port != connect_addr.sin_port) {
  598. goto abort_tidy_up_and_fail;
  599. }
  600. fd[0] = connector;
  601. fd[1] = acceptor;
  602. return 0;
  603. abort_tidy_up_and_fail:
  604. #ifdef MS_WINDOWS
  605. saved_errno = WSAECONNABORTED;
  606. #else
  607. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  608. #endif
  609. tidy_up_and_fail:
  610. if (saved_errno < 0)
  611. saved_errno = errno;
  612. if (listener != -1)
  613. tor_close_socket(listener);
  614. if (connector != -1)
  615. tor_close_socket(connector);
  616. if (acceptor != -1)
  617. tor_close_socket(acceptor);
  618. return -saved_errno;
  619. #endif
  620. }
  621. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  622. #if defined(HAVE_GETRLIMIT) && !defined(HAVE_RLIM_T)
  623. typedef unsigned long rlim_t;
  624. #endif
  625. /** Learn the maximum allowed number of file descriptors. (Some systems
  626. * have a low soft limit.
  627. *
  628. * We compute this by finding the largest number between <b>limit</b>
  629. * and <b>cap</b> that we can use. If we can't find a number greater
  630. * than or equal to <b>limit</b>, then we fail: return -1.
  631. *
  632. * Otherwise, return the number minus some buffer to allow for other
  633. * file descriptors we'll want available for ordinary use. */
  634. int
  635. set_max_file_descriptors(unsigned long limit, unsigned long cap)
  636. {
  637. #ifndef HAVE_GETRLIMIT
  638. log_fn(LOG_INFO, LD_NET,
  639. "This platform is missing getrlimit(). Proceeding.");
  640. if (limit < cap) {
  641. log_info(LD_CONFIG, "ConnLimit must be at most %d. Using that.", (int)cap);
  642. limit = cap;
  643. }
  644. #else
  645. struct rlimit rlim;
  646. rlim_t most;
  647. tor_assert(limit > 0);
  648. tor_assert(cap > 0);
  649. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  650. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  651. strerror(errno));
  652. return -1;
  653. }
  654. //log_notice(LD_CONFIG, "%llu %llu", rlim.rlim_cur, rlim.rlim_max);
  655. if ((unsigned long)rlim.rlim_max < limit) {
  656. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  657. "limited to %lu. Please change your ulimit -n.",
  658. limit, (unsigned long)rlim.rlim_max);
  659. return -1;
  660. }
  661. most = rlim.rlim_max > (rlim_t)cap ? (rlim_t)cap : rlim.rlim_max;
  662. if (most > (unsigned long)rlim.rlim_cur) {
  663. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  664. (unsigned long)rlim.rlim_cur, (unsigned long)most);
  665. }
  666. rlim.rlim_cur = most;
  667. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  668. int bad = 1;
  669. #ifdef OPEN_MAX
  670. if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
  671. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  672. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  673. rlim.rlim_cur = OPEN_MAX;
  674. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  675. if (rlim.rlim_cur < limit) {
  676. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  677. "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
  678. (unsigned long)OPEN_MAX, limit);
  679. } else {
  680. log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
  681. "Apparently, %lu was too high and rlimit lied to us.",
  682. (unsigned long)OPEN_MAX, (unsigned long)most);
  683. }
  684. most = rlim.rlim_cur;
  685. bad = 0;
  686. }
  687. }
  688. #endif
  689. if (bad) {
  690. log_warn(LD_CONFIG, "Couldn't set maximum number of file descriptors: %s",
  691. strerror(errno));
  692. return -1;
  693. }
  694. }
  695. /* leave some overhead for logs, etc, */
  696. limit = most;
  697. #endif
  698. if (limit < ULIMIT_BUFFER) {
  699. log_warn(LD_CONFIG,
  700. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  701. return -1;
  702. }
  703. return limit - ULIMIT_BUFFER;
  704. }
  705. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  706. * success. On failure, log and return -1.
  707. */
  708. int
  709. switch_id(const char *user, const char *group)
  710. {
  711. #ifndef MS_WINDOWS
  712. struct passwd *pw = NULL;
  713. struct group *gr = NULL;
  714. if (user) {
  715. pw = getpwnam(user);
  716. if (pw == NULL) {
  717. log_warn(LD_CONFIG,"User '%s' not found.", user);
  718. return -1;
  719. }
  720. }
  721. /* switch the group first, while we still have the privileges to do so */
  722. if (group) {
  723. gr = getgrnam(group);
  724. if (gr == NULL) {
  725. log_warn(LD_CONFIG,"Group '%s' not found.", group);
  726. return -1;
  727. }
  728. if (setgid(gr->gr_gid) != 0) {
  729. log_warn(LD_GENERAL,"Error setting to configured GID: %s",
  730. strerror(errno));
  731. return -1;
  732. }
  733. } else if (user) {
  734. if (setgid(pw->pw_gid) != 0) {
  735. log_warn(LD_GENERAL,"Error setting to user GID: %s", strerror(errno));
  736. return -1;
  737. }
  738. }
  739. /* now that the group is switched, we can switch users and lose
  740. privileges */
  741. if (user) {
  742. if (setuid(pw->pw_uid) != 0) {
  743. log_warn(LD_GENERAL,"Error setting UID: %s", strerror(errno));
  744. return -1;
  745. }
  746. }
  747. return 0;
  748. #else
  749. (void)user;
  750. (void)group;
  751. #endif
  752. log_warn(LD_CONFIG,
  753. "User or group specified, but switching users is not supported.");
  754. return -1;
  755. }
  756. #ifdef HAVE_PWD_H
  757. /** Allocate and return a string containing the home directory for the
  758. * user <b>username</b>. Only works on posix-like systems. */
  759. char *
  760. get_user_homedir(const char *username)
  761. {
  762. struct passwd *pw;
  763. tor_assert(username);
  764. if (!(pw = getpwnam(username))) {
  765. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  766. return NULL;
  767. }
  768. return tor_strdup(pw->pw_dir);
  769. }
  770. #endif
  771. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  772. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  773. * but works on Windows and Solaris.)
  774. */
  775. int
  776. tor_inet_aton(const char *c, struct in_addr* addr)
  777. {
  778. #ifdef HAVE_INET_ATON
  779. return inet_aton(c, addr);
  780. #else
  781. uint32_t r;
  782. tor_assert(c);
  783. tor_assert(addr);
  784. if (strcmp(c, "255.255.255.255") == 0) {
  785. addr->s_addr = 0xFFFFFFFFu;
  786. return 1;
  787. }
  788. r = inet_addr(c);
  789. if (r == INADDR_NONE)
  790. return 0;
  791. addr->s_addr = r;
  792. return 1;
  793. #endif
  794. }
  795. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  796. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  797. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  798. * <b>dst</b> on success, NULL on failure.
  799. *
  800. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  801. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  802. * support.) */
  803. const char *
  804. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  805. {
  806. if (af == AF_INET) {
  807. if (tor_inet_ntoa(src, dst, len) < 0)
  808. return NULL;
  809. else
  810. return dst;
  811. } else if (af == AF_INET6) {
  812. const struct in6_addr *addr = src;
  813. char buf[64], *cp;
  814. int longestGapLen = 0, longestGapPos = -1, i,
  815. curGapPos = -1, curGapLen = 0;
  816. uint16_t words[8];
  817. for (i = 0; i < 8; ++i) {
  818. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  819. }
  820. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  821. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  822. (words[5] == 0xffff))) {
  823. /* This is an IPv4 address. */
  824. if (words[5] == 0) {
  825. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  826. addr->s6_addr[12], addr->s6_addr[13],
  827. addr->s6_addr[14], addr->s6_addr[15]);
  828. } else {
  829. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  830. addr->s6_addr[12], addr->s6_addr[13],
  831. addr->s6_addr[14], addr->s6_addr[15]);
  832. }
  833. if (strlen(buf) > len)
  834. return NULL;
  835. strlcpy(dst, buf, len);
  836. return dst;
  837. }
  838. i = 0;
  839. while (i < 8) {
  840. if (words[i] == 0) {
  841. curGapPos = i++;
  842. curGapLen = 1;
  843. while (i<8 && words[i] == 0) {
  844. ++i; ++curGapLen;
  845. }
  846. if (curGapLen > longestGapLen) {
  847. longestGapPos = curGapPos;
  848. longestGapLen = curGapLen;
  849. }
  850. } else {
  851. ++i;
  852. }
  853. }
  854. if (longestGapLen<=1)
  855. longestGapPos = -1;
  856. cp = buf;
  857. for (i = 0; i < 8; ++i) {
  858. if (words[i] == 0 && longestGapPos == i) {
  859. if (i == 0)
  860. *cp++ = ':';
  861. *cp++ = ':';
  862. while (i < 8 && words[i] == 0)
  863. ++i;
  864. --i; /* to compensate for loop increment. */
  865. } else {
  866. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  867. cp += strlen(cp);
  868. if (i != 7)
  869. *cp++ = ':';
  870. }
  871. }
  872. *cp = '\0';
  873. if (strlen(buf) > len)
  874. return NULL;
  875. strlcpy(dst, buf, len);
  876. return dst;
  877. } else {
  878. return NULL;
  879. }
  880. }
  881. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  882. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  883. * address and store the result in <b>dst</b> (which must have space for a
  884. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  885. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  886. *
  887. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  888. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  889. * support.) */
  890. int
  891. tor_inet_pton(int af, const char *src, void *dst)
  892. {
  893. if (af == AF_INET) {
  894. return tor_inet_aton(src, dst);
  895. } else if (af == AF_INET6) {
  896. struct in6_addr *out = dst;
  897. uint16_t words[8];
  898. int gapPos = -1, i, setWords=0;
  899. const char *dot = strchr(src, '.');
  900. const char *eow; /* end of words. */
  901. if (dot == src)
  902. return 0;
  903. else if (!dot)
  904. eow = src+strlen(src);
  905. else {
  906. int byte1,byte2,byte3,byte4;
  907. char more;
  908. for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
  909. ;
  910. ++eow;
  911. /* We use "scanf" because some platform inet_aton()s are too lax
  912. * about IPv4 addresses of the form "1.2.3" */
  913. if (sscanf(eow, "%d.%d.%d.%d%c", &byte1,&byte2,&byte3,&byte4,&more) != 4)
  914. return 0;
  915. if (byte1 > 255 || byte1 < 0 ||
  916. byte2 > 255 || byte2 < 0 ||
  917. byte3 > 255 || byte3 < 0 ||
  918. byte4 > 255 || byte4 < 0)
  919. return 0;
  920. words[6] = (byte1<<8) | byte2;
  921. words[7] = (byte3<<8) | byte4;
  922. setWords += 2;
  923. }
  924. i = 0;
  925. while (src < eow) {
  926. if (i > 7)
  927. return 0;
  928. if (TOR_ISXDIGIT(*src)) {
  929. char *next;
  930. int r = strtol(src, &next, 16);
  931. if (next > 4+src)
  932. return 0;
  933. if (next == src)
  934. return 0;
  935. if (r<0 || r>65536)
  936. return 0;
  937. words[i++] = (uint16_t)r;
  938. setWords++;
  939. src = next;
  940. if (*src != ':' && src != eow)
  941. return 0;
  942. ++src;
  943. } else if (*src == ':' && i > 0 && gapPos==-1) {
  944. gapPos = i;
  945. ++src;
  946. } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
  947. gapPos = i;
  948. src += 2;
  949. } else {
  950. return 0;
  951. }
  952. }
  953. if (setWords > 8 ||
  954. (setWords == 8 && gapPos != -1) ||
  955. (setWords < 8 && gapPos == -1))
  956. return 0;
  957. if (gapPos >= 0) {
  958. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  959. int gapLen = 8 - setWords;
  960. tor_assert(nToMove >= 0);
  961. memmove(&words[gapPos+gapLen], &words[gapPos],
  962. sizeof(uint16_t)*nToMove);
  963. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  964. }
  965. for (i = 0; i < 8; ++i) {
  966. out->s6_addr[2*i ] = words[i] >> 8;
  967. out->s6_addr[2*i+1] = words[i] & 0xff;
  968. }
  969. return 1;
  970. } else {
  971. return -1;
  972. }
  973. }
  974. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  975. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  976. * on success, -1 on failure; 1 on transient failure.
  977. *
  978. * (This function exists because standard windows gethostbyname
  979. * doesn't treat raw IP addresses properly.)
  980. */
  981. int
  982. tor_lookup_hostname(const char *name, uint32_t *addr)
  983. {
  984. tor_addr_t myaddr;
  985. int ret;
  986. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  987. return ret;
  988. if (IN_FAMILY(&myaddr) == AF_INET) {
  989. *addr = IPV4IPh(&myaddr);
  990. return ret;
  991. }
  992. return -1;
  993. }
  994. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  995. * *<b>addr</b> to the proper IP address and family. The <b>family</b>
  996. * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
  997. * <i>preferred</i> family, though another one may be returned if only one
  998. * family is implemented for this address.
  999. *
  1000. * Return 0 on success, -1 on failure; 1 on transient failure.
  1001. */
  1002. int
  1003. tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
  1004. {
  1005. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  1006. * something.
  1007. */
  1008. struct in_addr iaddr;
  1009. struct in6_addr iaddr6;
  1010. tor_assert(name);
  1011. tor_assert(addr);
  1012. tor_assert(family == AF_INET || family == AF_UNSPEC);
  1013. memset(addr, 0, sizeof(addr)); /* Clear the extraneous fields. */
  1014. if (!*name) {
  1015. /* Empty address is an error. */
  1016. return -1;
  1017. } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
  1018. /* It's an IPv4 IP. */
  1019. addr->sa.sin_family = AF_INET;
  1020. memcpy(&addr->sa.sin_addr, &iaddr, sizeof(struct in_addr));
  1021. return 0;
  1022. } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
  1023. addr->sa6.sin6_family = AF_INET6;
  1024. memcpy(&addr->sa6.sin6_addr, &iaddr6, sizeof(struct in6_addr));
  1025. return 0;
  1026. } else {
  1027. #ifdef HAVE_GETADDRINFO
  1028. int err;
  1029. struct addrinfo *res=NULL, *res_p;
  1030. struct addrinfo *best=NULL;
  1031. struct addrinfo hints;
  1032. int result = -1;
  1033. memset(&hints, 0, sizeof(hints));
  1034. hints.ai_family = family;
  1035. hints.ai_socktype = SOCK_STREAM;
  1036. err = getaddrinfo(name, NULL, &hints, &res);
  1037. if (!err) {
  1038. best = NULL;
  1039. for (res_p = res; res_p; res_p = res_p->ai_next) {
  1040. if (family == AF_UNSPEC) {
  1041. if (res_p->ai_family == AF_INET) {
  1042. best = res_p;
  1043. break;
  1044. } else if (res_p->ai_family == AF_INET6 && !best) {
  1045. best = res_p;
  1046. }
  1047. } else if (family == res_p->ai_family) {
  1048. best = res_p;
  1049. break;
  1050. }
  1051. }
  1052. if (!best)
  1053. best = res;
  1054. if (best->ai_family == AF_INET) {
  1055. addr->sa.sin_family = AF_INET;
  1056. memcpy(&addr->sa.sin_addr,
  1057. &((struct sockaddr_in*)best->ai_addr)->sin_addr,
  1058. sizeof(struct in_addr));
  1059. result = 0;
  1060. } else if (best->ai_family == AF_INET6) {
  1061. addr->sa6.sin6_family = AF_INET6;
  1062. memcpy(&addr->sa6.sin6_addr,
  1063. &((struct sockaddr_in6*)best->ai_addr)->sin6_addr,
  1064. sizeof(struct in6_addr));
  1065. result = 0;
  1066. }
  1067. freeaddrinfo(res);
  1068. return result;
  1069. }
  1070. return (err == EAI_AGAIN) ? 1 : -1;
  1071. #else
  1072. struct hostent *ent;
  1073. int err;
  1074. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  1075. char buf[2048];
  1076. struct hostent hostent;
  1077. int r;
  1078. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  1079. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1080. char buf[2048];
  1081. struct hostent hostent;
  1082. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  1083. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  1084. struct hostent_data data;
  1085. struct hostent hent;
  1086. memset(&data, 0, sizeof(data));
  1087. err = gethostbyname_r(name, &hent, &data);
  1088. ent = err ? NULL : &hent;
  1089. #else
  1090. ent = gethostbyname(name);
  1091. #ifdef MS_WINDOWS
  1092. err = WSAGetLastError();
  1093. #else
  1094. err = h_errno;
  1095. #endif
  1096. #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
  1097. if (ent) {
  1098. addr->sa.sin_family = ent->h_addrtype;
  1099. if (ent->h_addrtype == AF_INET) {
  1100. memcpy(&addr->sa.sin_addr, ent->h_addr, sizeof(struct in_addr));
  1101. } else if (ent->h_addrtype == AF_INET6) {
  1102. memcpy(&addr->sa6.sin6_addr, ent->h_addr, sizeof(struct in6_addr));
  1103. } else {
  1104. tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
  1105. }
  1106. return 0;
  1107. }
  1108. memset(addr, 0, sizeof(tor_addr_t)); /* XXXX020 is this redundant? */
  1109. #ifdef MS_WINDOWS
  1110. return (err == WSATRY_AGAIN) ? 1 : -1;
  1111. #else
  1112. return (err == TRY_AGAIN) ? 1 : -1;
  1113. #endif
  1114. #endif
  1115. }
  1116. }
  1117. /** Hold the result of our call to <b>uname</b>. */
  1118. static char uname_result[256];
  1119. /** True iff uname_result is set. */
  1120. static int uname_result_is_set = 0;
  1121. /** Return a pointer to a description of our platform.
  1122. */
  1123. const char *
  1124. get_uname(void)
  1125. {
  1126. #ifdef HAVE_UNAME
  1127. struct utsname u;
  1128. #endif
  1129. if (!uname_result_is_set) {
  1130. #ifdef HAVE_UNAME
  1131. if (uname(&u) != -1) {
  1132. /* (linux says 0 is success, solaris says 1 is success) */
  1133. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1134. u.sysname, u.machine);
  1135. } else
  1136. #endif
  1137. {
  1138. #ifdef MS_WINDOWS
  1139. OSVERSIONINFOEX info;
  1140. int i;
  1141. unsigned int leftover_mask;
  1142. const char *plat = NULL;
  1143. const char *extra = NULL;
  1144. static struct {
  1145. unsigned major; unsigned minor; const char *version;
  1146. } win_version_table[] = {
  1147. { 6, 0, "Windows \"Longhorn\"" },
  1148. { 5, 2, "Windows Server 2003" },
  1149. { 5, 1, "Windows XP" },
  1150. { 5, 0, "Windows 2000" },
  1151. /* { 4, 0, "Windows NT 4.0" }, */
  1152. { 4, 90, "Windows Me" },
  1153. { 4, 10, "Windows 98" },
  1154. /* { 4, 0, "Windows 95" } */
  1155. { 3, 51, "Windows NT 3.51" },
  1156. { 0, 0, NULL }
  1157. };
  1158. #ifdef VER_SUITE_BACKOFFICE
  1159. static struct {
  1160. unsigned int mask; const char *str;
  1161. } win_mask_table[] = {
  1162. { VER_SUITE_BACKOFFICE, " {backoffice}" },
  1163. { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
  1164. { VER_SUITE_DATACENTER, " {datacenter}" },
  1165. { VER_SUITE_ENTERPRISE, " {enterprise}" },
  1166. { VER_SUITE_EMBEDDEDNT, " {embedded}" },
  1167. { VER_SUITE_PERSONAL, " {personal}" },
  1168. { VER_SUITE_SINGLEUSERTS,
  1169. " {terminal services, single user}" },
  1170. { VER_SUITE_SMALLBUSINESS, " {small business}" },
  1171. { VER_SUITE_SMALLBUSINESS_RESTRICTED,
  1172. " {small business, restricted}" },
  1173. { VER_SUITE_TERMINAL, " {terminal services}" },
  1174. { 0, NULL },
  1175. };
  1176. #endif
  1177. memset(&info, 0, sizeof(info));
  1178. info.dwOSVersionInfoSize = sizeof(info);
  1179. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  1180. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  1181. " doesn't work.", sizeof(uname_result));
  1182. uname_result_is_set = 1;
  1183. return uname_result;
  1184. }
  1185. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  1186. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  1187. plat = "Windows NT 4.0";
  1188. else
  1189. plat = "Windows 95";
  1190. if (info.szCSDVersion[1] == 'B')
  1191. extra = "OSR2 (B)";
  1192. else if (info.szCSDVersion[1] == 'C')
  1193. extra = "OSR2 (C)";
  1194. } else {
  1195. for (i=0; win_version_table[i].major>0; ++i) {
  1196. if (win_version_table[i].major == info.dwMajorVersion &&
  1197. win_version_table[i].minor == info.dwMinorVersion) {
  1198. plat = win_version_table[i].version;
  1199. break;
  1200. }
  1201. }
  1202. }
  1203. if (plat && !strcmp(plat, "Windows 98")) {
  1204. if (info.szCSDVersion[1] == 'A')
  1205. extra = "SE (A)";
  1206. else if (info.szCSDVersion[1] == 'B')
  1207. extra = "SE (B)";
  1208. }
  1209. if (plat) {
  1210. if (!extra)
  1211. extra = info.szCSDVersion;
  1212. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1213. plat, extra);
  1214. } else {
  1215. if (info.dwMajorVersion > 6 ||
  1216. (info.dwMajorVersion==6 && info.dwMinorVersion>0))
  1217. tor_snprintf(uname_result, sizeof(uname_result),
  1218. "Very recent version of Windows [major=%d,minor=%d] %s",
  1219. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1220. info.szCSDVersion);
  1221. else
  1222. tor_snprintf(uname_result, sizeof(uname_result),
  1223. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  1224. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1225. info.szCSDVersion);
  1226. }
  1227. #ifdef VER_SUITE_BACKOFFICE
  1228. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  1229. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  1230. } else if (info.wProductType == VER_NT_SERVER) {
  1231. strlcat(uname_result, " [server]", sizeof(uname_result));
  1232. } else if (info.wProductType == VER_NT_WORKSTATION) {
  1233. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  1234. }
  1235. leftover_mask = info.wSuiteMask;
  1236. for (i = 0; win_mask_table[i].mask; ++i) {
  1237. if (info.wSuiteMask & win_mask_table[i].mask) {
  1238. strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
  1239. leftover_mask &= ~win_mask_table[i].mask;
  1240. }
  1241. }
  1242. if (leftover_mask) {
  1243. size_t len = strlen(uname_result);
  1244. tor_snprintf(uname_result+len, sizeof(uname_result)-len,
  1245. " {0x%x}", info.wSuiteMask);
  1246. }
  1247. #endif
  1248. #else
  1249. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  1250. #endif
  1251. }
  1252. uname_result_is_set = 1;
  1253. }
  1254. return uname_result;
  1255. }
  1256. /*
  1257. * Process control
  1258. */
  1259. #if defined(USE_PTHREADS)
  1260. /** Wraps a void (*)(void*) function and its argument so we can
  1261. * invoke them in a way pthreads would expect.
  1262. */
  1263. typedef struct tor_pthread_data_t {
  1264. void (*func)(void *);
  1265. void *data;
  1266. } tor_pthread_data_t;
  1267. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  1268. * and free _data. Used to make sure we can call functions the way pthread
  1269. * expects. */
  1270. static void *
  1271. tor_pthread_helper_fn(void *_data)
  1272. {
  1273. tor_pthread_data_t *data = _data;
  1274. void (*func)(void*);
  1275. void *arg;
  1276. /* mask signals to worker threads to avoid SIGPIPE, etc */
  1277. sigset_t sigs;
  1278. /* We're in a subthread; don't handle any signals here. */
  1279. sigfillset(&sigs);
  1280. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  1281. func = data->func;
  1282. arg = data->data;
  1283. tor_free(_data);
  1284. func(arg);
  1285. return NULL;
  1286. }
  1287. #endif
  1288. /** Minimalist interface to run a void function in the background. On
  1289. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  1290. * func should not return, but rather should call spawn_exit.
  1291. *
  1292. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  1293. * since in a multithreaded environment, there is no way to be sure that
  1294. * the caller's stack will still be around when the called function is
  1295. * running.
  1296. */
  1297. int
  1298. spawn_func(void (*func)(void *), void *data)
  1299. {
  1300. #if defined(USE_WIN32_THREADS)
  1301. int rv;
  1302. rv = (int)_beginthread(func, 0, data);
  1303. if (rv == (int)-1)
  1304. return -1;
  1305. return 0;
  1306. #elif defined(USE_PTHREADS)
  1307. pthread_t thread;
  1308. tor_pthread_data_t *d;
  1309. d = tor_malloc(sizeof(tor_pthread_data_t));
  1310. d->data = data;
  1311. d->func = func;
  1312. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  1313. return -1;
  1314. if (pthread_detach(thread))
  1315. return -1;
  1316. return 0;
  1317. #else
  1318. pid_t pid;
  1319. pid = fork();
  1320. if (pid<0)
  1321. return -1;
  1322. if (pid==0) {
  1323. /* Child */
  1324. func(data);
  1325. tor_assert(0); /* Should never reach here. */
  1326. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  1327. } else {
  1328. /* Parent */
  1329. return 0;
  1330. }
  1331. #endif
  1332. }
  1333. /** End the current thread/process.
  1334. */
  1335. void
  1336. spawn_exit(void)
  1337. {
  1338. #if defined(USE_WIN32_THREADS)
  1339. _endthread();
  1340. //we should never get here. my compiler thinks that _endthread returns, this
  1341. //is an attempt to fool it.
  1342. tor_assert(0);
  1343. _exit(0);
  1344. #elif defined(USE_PTHREADS)
  1345. pthread_exit(NULL);
  1346. #else
  1347. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  1348. * call _exit, not exit, from child processes. */
  1349. _exit(0);
  1350. #endif
  1351. }
  1352. /** Set *timeval to the current time of day. On error, log and terminate.
  1353. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  1354. */
  1355. void
  1356. tor_gettimeofday(struct timeval *timeval)
  1357. {
  1358. #ifdef MS_WINDOWS
  1359. /* Epoch bias copied from perl: number of units between windows epoch and
  1360. * unix epoch. */
  1361. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  1362. #define UNITS_PER_SEC U64_LITERAL(10000000)
  1363. #define USEC_PER_SEC U64_LITERAL(1000000)
  1364. #define UNITS_PER_USEC U64_LITERAL(10)
  1365. union {
  1366. uint64_t ft_64;
  1367. FILETIME ft_ft;
  1368. } ft;
  1369. /* number of 100-nsec units since Jan 1, 1601 */
  1370. GetSystemTimeAsFileTime(&ft.ft_ft);
  1371. if (ft.ft_64 < EPOCH_BIAS) {
  1372. log_err(LD_GENERAL,"System time is before 1970; failing.");
  1373. exit(1);
  1374. }
  1375. ft.ft_64 -= EPOCH_BIAS;
  1376. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  1377. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  1378. #elif defined(HAVE_GETTIMEOFDAY)
  1379. if (gettimeofday(timeval, NULL)) {
  1380. log_err(LD_GENERAL,"gettimeofday failed.");
  1381. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  1382. or segfaulted.*/
  1383. exit(1);
  1384. }
  1385. #elif defined(HAVE_FTIME)
  1386. struct timeb tb;
  1387. ftime(&tb);
  1388. timeval->tv_sec = tb.time;
  1389. timeval->tv_usec = tb.millitm * 1000;
  1390. #else
  1391. #error "No way to get time."
  1392. #endif
  1393. return;
  1394. }
  1395. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  1396. /** Defined iff we need to add locks when defining fake versions of reentrant
  1397. * versions of time-related functions. */
  1398. #define TIME_FNS_NEED_LOCKS
  1399. #endif
  1400. #ifndef HAVE_LOCALTIME_R
  1401. #ifdef TIME_FNS_NEED_LOCKS
  1402. struct tm *
  1403. tor_localtime_r(const time_t *timep, struct tm *result)
  1404. {
  1405. struct tm *r;
  1406. static tor_mutex_t *m=NULL;
  1407. if (!m) { m=tor_mutex_new(); }
  1408. tor_assert(result);
  1409. tor_mutex_acquire(m);
  1410. r = localtime(timep);
  1411. memcpy(result, r, sizeof(struct tm));
  1412. tor_mutex_release(m);
  1413. return result;
  1414. }
  1415. #else
  1416. struct tm *
  1417. tor_localtime_r(const time_t *timep, struct tm *result)
  1418. {
  1419. struct tm *r;
  1420. tor_assert(result);
  1421. r = localtime(timep);
  1422. memcpy(result, r, sizeof(struct tm));
  1423. return result;
  1424. }
  1425. #endif
  1426. #endif
  1427. #ifndef HAVE_GMTIME_R
  1428. #ifdef TIME_FNS_NEED_LOCKS
  1429. struct tm *
  1430. tor_gmtime_r(const time_t *timep, struct tm *result)
  1431. {
  1432. struct tm *r;
  1433. static tor_mutex_t *m=NULL;
  1434. if (!m) { m=tor_mutex_new(); }
  1435. tor_assert(result);
  1436. tor_mutex_acquire(m);
  1437. r = gmtime(timep);
  1438. memcpy(result, r, sizeof(struct tm));
  1439. tor_mutex_release(m);
  1440. return result;
  1441. }
  1442. #else
  1443. struct tm *
  1444. tor_gmtime_r(const time_t *timep, struct tm *result)
  1445. {
  1446. struct tm *r;
  1447. tor_assert(result);
  1448. r = gmtime(timep);
  1449. memcpy(result, r, sizeof(struct tm));
  1450. return result;
  1451. }
  1452. #endif
  1453. #endif
  1454. #if defined(USE_WIN32_THREADS) && 0
  1455. /** A generic lock structure for multithreaded builds. */
  1456. struct tor_mutex_t {
  1457. HANDLE handle;
  1458. };
  1459. tor_mutex_t *
  1460. tor_mutex_new(void)
  1461. {
  1462. tor_mutex_t *m;
  1463. m = tor_malloc_zero(sizeof(tor_mutex_t));
  1464. m->handle = CreateMutex(NULL, FALSE, NULL);
  1465. tor_assert(m->handle != NULL);
  1466. return m;
  1467. }
  1468. void
  1469. tor_mutex_free(tor_mutex_t *m)
  1470. {
  1471. CloseHandle(m->handle);
  1472. tor_free(m);
  1473. }
  1474. void
  1475. tor_mutex_acquire(tor_mutex_t *m)
  1476. {
  1477. DWORD r;
  1478. r = WaitForSingleObject(m->handle, INFINITE);
  1479. switch (r) {
  1480. case WAIT_ABANDONED: /* holding thread exited. */
  1481. case WAIT_OBJECT_0: /* we got the mutex normally. */
  1482. break;
  1483. case WAIT_TIMEOUT: /* Should never happen. */
  1484. tor_assert(0);
  1485. break;
  1486. case WAIT_FAILED:
  1487. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  1488. }
  1489. }
  1490. void
  1491. tor_mutex_release(tor_mutex_t *m)
  1492. {
  1493. BOOL r;
  1494. r = ReleaseMutex(m->handle);
  1495. if (!r) {
  1496. log_warn(LD_GENERAL, "Failed to release mutex: %d", (int) GetLastError());
  1497. }
  1498. }
  1499. unsigned long
  1500. tor_get_thread_id(void)
  1501. {
  1502. return (unsigned long)GetCurrentThreadId();
  1503. }
  1504. #elif defined(USE_WIN32_THREADS)
  1505. /** A generic lock structure for multithreaded builds. */
  1506. struct tor_mutex_t {
  1507. CRITICAL_SECTION mutex;
  1508. };
  1509. tor_mutex_t *
  1510. tor_mutex_new(void)
  1511. {
  1512. tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
  1513. InitializeCriticalSection(&m->mutex);
  1514. return m;
  1515. }
  1516. void
  1517. tor_mutex_free(tor_mutex_t *m)
  1518. {
  1519. DeleteCriticalSection(&m->mutex);
  1520. tor_free(m);
  1521. }
  1522. void
  1523. tor_mutex_acquire(tor_mutex_t *m)
  1524. {
  1525. tor_assert(m);
  1526. EnterCriticalSection(&m->mutex);
  1527. }
  1528. void
  1529. tor_mutex_release(tor_mutex_t *m)
  1530. {
  1531. LeaveCriticalSection(&m->mutex);
  1532. }
  1533. unsigned long
  1534. tor_get_thread_id(void)
  1535. {
  1536. return (unsigned long)GetCurrentThreadId();
  1537. }
  1538. #elif defined(USE_PTHREADS)
  1539. /** A generic lock structure for multithreaded builds. */
  1540. struct tor_mutex_t {
  1541. pthread_mutex_t mutex;
  1542. };
  1543. /** Allocate and return new lock. */
  1544. tor_mutex_t *
  1545. tor_mutex_new(void)
  1546. {
  1547. int err;
  1548. tor_mutex_t *mutex = tor_malloc_zero(sizeof(tor_mutex_t));
  1549. err = pthread_mutex_init(&mutex->mutex, NULL);
  1550. if (PREDICT_UNLIKELY(err)) {
  1551. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  1552. tor_fragile_assert();
  1553. }
  1554. return mutex;
  1555. }
  1556. /** Wait until <b>m</b> is free, then acquire it. */
  1557. void
  1558. tor_mutex_acquire(tor_mutex_t *m)
  1559. {
  1560. int err;
  1561. tor_assert(m);
  1562. err = pthread_mutex_lock(&m->mutex);
  1563. if (PREDICT_UNLIKELY(err)) {
  1564. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  1565. tor_fragile_assert();
  1566. }
  1567. }
  1568. /** Release the lock <b>m</b> so another thread can have it. */
  1569. void
  1570. tor_mutex_release(tor_mutex_t *m)
  1571. {
  1572. int err;
  1573. tor_assert(m);
  1574. err = pthread_mutex_unlock(&m->mutex);
  1575. if (PREDICT_UNLIKELY(err)) {
  1576. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  1577. tor_fragile_assert();
  1578. }
  1579. }
  1580. /** Free all storage held by the lock <b>m</b>. */
  1581. void
  1582. tor_mutex_free(tor_mutex_t *m)
  1583. {
  1584. int err;
  1585. tor_assert(m);
  1586. err = pthread_mutex_destroy(&m->mutex);
  1587. if (PREDICT_UNLIKELY(err)) {
  1588. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  1589. tor_fragile_assert();
  1590. }
  1591. tor_free(m);
  1592. }
  1593. /** Return an integer representing this thread. */
  1594. unsigned long
  1595. tor_get_thread_id(void)
  1596. {
  1597. union {
  1598. pthread_t thr;
  1599. unsigned long id;
  1600. } r;
  1601. r.thr = pthread_self();
  1602. return r.id;
  1603. }
  1604. #else
  1605. /** A generic lock structure for multithreaded builds. */
  1606. struct tor_mutex_t {
  1607. int _unused;
  1608. };
  1609. #endif
  1610. /* Conditions. */
  1611. #ifdef USE_PTHREADS
  1612. /** Cross-platform condtion implementation. */
  1613. struct tor_cond_t {
  1614. pthread_cond_t cond;
  1615. };
  1616. /** Return a newly allocated condition, with nobody waiting on it. */
  1617. tor_cond_t *
  1618. tor_cond_new(void)
  1619. {
  1620. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  1621. if (pthread_cond_init(&cond->cond, NULL)) {
  1622. tor_free(cond);
  1623. return NULL;
  1624. }
  1625. return cond;
  1626. }
  1627. /** Release all resources held by <b>cond</b>. */
  1628. void
  1629. tor_cond_free(tor_cond_t *cond)
  1630. {
  1631. tor_assert(cond);
  1632. if (pthread_cond_destroy(&cond->cond)) {
  1633. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  1634. return;
  1635. }
  1636. tor_free(cond);
  1637. }
  1638. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  1639. * All waiters on the condition must wait holding the same <b>mutex</b>.
  1640. * Returns 0 on success, negative on failure. */
  1641. int
  1642. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  1643. {
  1644. return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
  1645. }
  1646. /** Wake up one of the waiters on <b>cond</b>. */
  1647. void
  1648. tor_cond_signal_one(tor_cond_t *cond)
  1649. {
  1650. pthread_cond_signal(&cond->cond);
  1651. }
  1652. /** Wake up all of the waiters on <b>cond</b>. */
  1653. void
  1654. tor_cond_signal_all(tor_cond_t *cond)
  1655. {
  1656. pthread_cond_broadcast(&cond->cond);
  1657. }
  1658. /** Set up common structures for use by threading. */
  1659. void
  1660. tor_threads_init(void)
  1661. {
  1662. }
  1663. #elif defined(USE_WIN32_THREADS)
  1664. static DWORD cond_event_tls_index;
  1665. struct tor_cond_t {
  1666. CRITICAL_SECTION mutex;
  1667. smartlist_t *events;
  1668. };
  1669. tor_cond_t *
  1670. tor_cond_new(void)
  1671. {
  1672. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  1673. InitializeCriticalSection(&cond->mutex);
  1674. cond->events = smartlist_create();
  1675. return cond;
  1676. }
  1677. void
  1678. tor_cond_free(tor_cond_t *cond)
  1679. {
  1680. tor_assert(cond);
  1681. DeleteCriticalSection(&cond->mutex);
  1682. /* XXXX020 notify? */
  1683. smartlist_free(cond->events);
  1684. tor_free(cond);
  1685. }
  1686. int
  1687. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  1688. {
  1689. HANDLE event;
  1690. int r;
  1691. tor_assert(cond);
  1692. tor_assert(mutex);
  1693. event = TlsGetValue(cond_event_tls_index);
  1694. if (!event) {
  1695. event = CreateEvent(0, FALSE, FALSE, NULL);
  1696. TlsSetValue(cond_event_tls_index, event);
  1697. }
  1698. EnterCriticalSection(&cond->mutex);
  1699. tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
  1700. tor_assert(!smartlist_isin(cond->events, event));
  1701. smartlist_add(cond->events, event);
  1702. LeaveCriticalSection(&cond->mutex);
  1703. tor_mutex_release(mutex);
  1704. r = WaitForSingleObject(event, INFINITE);
  1705. tor_mutex_acquire(mutex);
  1706. switch (r) {
  1707. case WAIT_OBJECT_0: /* we got the mutex normally. */
  1708. break;
  1709. case WAIT_ABANDONED: /* holding thread exited. */
  1710. case WAIT_TIMEOUT: /* Should never happen. */
  1711. tor_assert(0);
  1712. break;
  1713. case WAIT_FAILED:
  1714. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  1715. }
  1716. return 0;
  1717. }
  1718. void
  1719. tor_cond_signal_one(tor_cond_t *cond)
  1720. {
  1721. HANDLE event;
  1722. tor_assert(cond);
  1723. EnterCriticalSection(&cond->mutex);
  1724. if ((event = smartlist_pop_last(cond->events)))
  1725. SetEvent(event);
  1726. LeaveCriticalSection(&cond->mutex);
  1727. }
  1728. void
  1729. tor_cond_signal_all(tor_cond_t *cond)
  1730. {
  1731. tor_assert(cond);
  1732. EnterCriticalSection(&cond->mutex);
  1733. SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
  1734. smartlist_clear(cond->events);
  1735. LeaveCriticalSection(&cond->mutex);
  1736. }
  1737. void
  1738. tor_threads_init(void)
  1739. {
  1740. cond_event_tls_index = TlsAlloc();
  1741. }
  1742. #endif
  1743. /**
  1744. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1745. * you need to ask the socket for its actual errno. Also, you need to
  1746. * get your errors from WSAGetLastError, not errno. (If you supply a
  1747. * socket of -1, we check WSAGetLastError, but don't correct
  1748. * WSAEWOULDBLOCKs.)
  1749. *
  1750. * The upshot of all of this is that when a socket call fails, you
  1751. * should call tor_socket_errno <em>at most once</em> on the failing
  1752. * socket to get the error.
  1753. */
  1754. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1755. int
  1756. tor_socket_errno(int sock)
  1757. {
  1758. int optval, optvallen=sizeof(optval);
  1759. int err = WSAGetLastError();
  1760. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1761. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1762. return err;
  1763. if (optval)
  1764. return optval;
  1765. }
  1766. return err;
  1767. }
  1768. #endif
  1769. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1770. #define E(code, s) { code, (s " [" #code " ]") }
  1771. struct { int code; const char *msg; } windows_socket_errors[] = {
  1772. E(WSAEINTR, "Interrupted function call"),
  1773. E(WSAEACCES, "Permission denied"),
  1774. E(WSAEFAULT, "Bad address"),
  1775. E(WSAEINVAL, "Invalid argument"),
  1776. E(WSAEMFILE, "Too many open files"),
  1777. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1778. E(WSAEINPROGRESS, "Operation now in progress"),
  1779. E(WSAEALREADY, "Operation already in progress"),
  1780. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1781. E(WSAEDESTADDRREQ, "Destination address required"),
  1782. E(WSAEMSGSIZE, "Message too long"),
  1783. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1784. E(WSAENOPROTOOPT, "Bad protocol option"),
  1785. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1786. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1787. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1788. E(WSAEOPNOTSUPP, "Operation not supported"),
  1789. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1790. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1791. E(WSAEADDRINUSE, "Address already in use"),
  1792. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1793. E(WSAENETDOWN, "Network is down"),
  1794. E(WSAENETUNREACH, "Network is unreachable"),
  1795. E(WSAENETRESET, "Network dropped connection on reset"),
  1796. E(WSAECONNABORTED, "Software caused connection abort"),
  1797. E(WSAECONNRESET, "Connection reset by peer"),
  1798. E(WSAENOBUFS, "No buffer space available"),
  1799. E(WSAEISCONN, "Socket is already connected"),
  1800. E(WSAENOTCONN, "Socket is not connected"),
  1801. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1802. E(WSAETIMEDOUT, "Connection timed out"),
  1803. E(WSAECONNREFUSED, "Connection refused"),
  1804. E(WSAEHOSTDOWN, "Host is down"),
  1805. E(WSAEHOSTUNREACH, "No route to host"),
  1806. E(WSAEPROCLIM, "Too many processes"),
  1807. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1808. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1809. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1810. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1811. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1812. #ifdef WSATYPE_NOT_FOUND
  1813. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1814. #endif
  1815. E(WSAHOST_NOT_FOUND, "Host not found"),
  1816. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1817. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1818. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1819. /* There are some more error codes whose numeric values are marked
  1820. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1821. * reason that practitioners of some craft traditions deliberately
  1822. * introduce imperfections into their baskets and rugs "to allow the
  1823. * evil spirits to escape." If we catch them, then our binaries
  1824. * might not report consistent results across versions of Windows.
  1825. * Thus, I'm going to let them all fall through.
  1826. */
  1827. { -1, NULL },
  1828. };
  1829. /** There does not seem to be a strerror equivalent for winsock errors.
  1830. * Naturally, we have to roll our own.
  1831. */
  1832. const char *
  1833. tor_socket_strerror(int e)
  1834. {
  1835. int i;
  1836. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1837. if (e == windows_socket_errors[i].code)
  1838. return windows_socket_errors[i].msg;
  1839. }
  1840. return strerror(e);
  1841. }
  1842. #endif
  1843. /** Called before we make any calls to network-related functions.
  1844. * (Some operating systems require their network libraries to be
  1845. * initialized.) */
  1846. int
  1847. network_init(void)
  1848. {
  1849. #ifdef MS_WINDOWS
  1850. /* This silly exercise is necessary before windows will allow
  1851. * gethostbyname to work. */
  1852. WSADATA WSAData;
  1853. int r;
  1854. r = WSAStartup(0x101,&WSAData);
  1855. if (r) {
  1856. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1857. return -1;
  1858. }
  1859. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1860. * We might use it to complain if we're trying to be a server but have
  1861. * too few sockets available. */
  1862. #endif
  1863. return 0;
  1864. }
  1865. #ifdef MS_WINDOWS
  1866. /** Return a newly allocated string describing the windows system error code
  1867. * <b>err</b>. Note that error codes are different from errno. Error codes
  1868. * come from GetLastError() when a winapi call fails. errno is set only when
  1869. * ansi functions fail. Whee. */
  1870. char *
  1871. format_win32_error(DWORD err)
  1872. {
  1873. LPVOID str = NULL;
  1874. char *result;
  1875. /* Somebody once decided that this interface was better than strerror(). */
  1876. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1877. FORMAT_MESSAGE_FROM_SYSTEM |
  1878. FORMAT_MESSAGE_IGNORE_INSERTS,
  1879. NULL, err,
  1880. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1881. (LPTSTR) &str,
  1882. 0, NULL);
  1883. if (str) {
  1884. result = tor_strdup((char*)str);
  1885. LocalFree(str); /* LocalFree != free() */
  1886. } else {
  1887. result = tor_strdup("<unformattable error>");
  1888. }
  1889. return result;
  1890. }
  1891. #endif