compat.c 55 KB

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