compat.c 55 KB

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