compat.c 58 KB

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