compat.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005
  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. /** 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. tor_assert(n_sockets_open > 0);
  478. --n_sockets_open;
  479. }
  480. /** As socket(), but counts the number of open sockets. */
  481. int
  482. tor_open_socket(int domain, int type, int protocol)
  483. {
  484. int s = socket(domain, type, protocol);
  485. if (s >= 0)
  486. ++n_sockets_open;
  487. return s;
  488. }
  489. /** Return the number of sockets we currently have opened. */
  490. int
  491. get_n_open_sockets(void)
  492. {
  493. return n_sockets_open;
  494. }
  495. /** Turn <b>socket</b> into a nonblocking socket.
  496. */
  497. void
  498. set_socket_nonblocking(int socket)
  499. {
  500. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  501. unsigned long nonblocking = 1;
  502. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  503. #else
  504. fcntl(socket, F_SETFL, O_NONBLOCK);
  505. #endif
  506. }
  507. /**
  508. * Allocate a pair of connected sockets. (Like socketpair(family,
  509. * type,protocol,fd), but works on systems that don't have
  510. * socketpair.)
  511. *
  512. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  513. *
  514. * Note that on systems without socketpair, this call will fail if
  515. * localhost is inaccessible (for example, if the networking
  516. * stack is down). And even if it succeeds, the socket pair will not
  517. * be able to read while localhost is down later (the socket pair may
  518. * even close, depending on OS-specific timeouts).
  519. *
  520. * Returns 0 on success and -errno on failure; do not rely on the value
  521. * of errno or WSAGetLastError().
  522. **/
  523. /* It would be nicer just to set errno, but that won't work for windows. */
  524. int
  525. tor_socketpair(int family, int type, int protocol, int fd[2])
  526. {
  527. //don't use win32 socketpairs (they are always bad)
  528. #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
  529. int r;
  530. r = socketpair(family, type, protocol, fd);
  531. return r < 0 ? -errno : r;
  532. #elif defined(USE_BSOCKETS)
  533. return bsocketpair(family, type, protocol, fd);
  534. #else
  535. /* This socketpair does not work when localhost is down. So
  536. * it's really not the same thing at all. But it's close enough
  537. * for now, and really, when localhost is down sometimes, we
  538. * have other problems too.
  539. */
  540. int listener = -1;
  541. int connector = -1;
  542. int acceptor = -1;
  543. struct sockaddr_in listen_addr;
  544. struct sockaddr_in connect_addr;
  545. int size;
  546. int saved_errno = -1;
  547. if (protocol
  548. #ifdef AF_UNIX
  549. || family != AF_UNIX
  550. #endif
  551. ) {
  552. #ifdef MS_WINDOWS
  553. return -WSAEAFNOSUPPORT;
  554. #else
  555. return -EAFNOSUPPORT;
  556. #endif
  557. }
  558. if (!fd) {
  559. return -EINVAL;
  560. }
  561. listener = tor_open_socket(AF_INET, type, 0);
  562. if (listener < 0)
  563. return -tor_socket_errno(-1);
  564. memset(&listen_addr, 0, sizeof(listen_addr));
  565. listen_addr.sin_family = AF_INET;
  566. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  567. listen_addr.sin_port = 0; /* kernel chooses port. */
  568. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  569. == -1)
  570. goto tidy_up_and_fail;
  571. if (listen(listener, 1) == -1)
  572. goto tidy_up_and_fail;
  573. connector = tor_open_socket(AF_INET, type, 0);
  574. if (connector < 0)
  575. goto tidy_up_and_fail;
  576. /* We want to find out the port number to connect to. */
  577. size = sizeof(connect_addr);
  578. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  579. goto tidy_up_and_fail;
  580. if (size != sizeof (connect_addr))
  581. goto abort_tidy_up_and_fail;
  582. if (connect(connector, (struct sockaddr *) &connect_addr,
  583. sizeof(connect_addr)) == -1)
  584. goto tidy_up_and_fail;
  585. size = sizeof(listen_addr);
  586. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  587. if (acceptor < 0)
  588. goto tidy_up_and_fail;
  589. if (size != sizeof(listen_addr))
  590. goto abort_tidy_up_and_fail;
  591. tor_close_socket(listener);
  592. /* Now check we are talking to ourself by matching port and host on the
  593. two sockets. */
  594. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  595. goto tidy_up_and_fail;
  596. if (size != sizeof (connect_addr)
  597. || listen_addr.sin_family != connect_addr.sin_family
  598. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  599. || listen_addr.sin_port != connect_addr.sin_port) {
  600. goto abort_tidy_up_and_fail;
  601. }
  602. fd[0] = connector;
  603. fd[1] = acceptor;
  604. return 0;
  605. abort_tidy_up_and_fail:
  606. #ifdef MS_WINDOWS
  607. saved_errno = WSAECONNABORTED;
  608. #else
  609. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  610. #endif
  611. tidy_up_and_fail:
  612. if (saved_errno < 0)
  613. saved_errno = errno;
  614. if (listener != -1)
  615. tor_close_socket(listener);
  616. if (connector != -1)
  617. tor_close_socket(connector);
  618. if (acceptor != -1)
  619. tor_close_socket(acceptor);
  620. return -saved_errno;
  621. #endif
  622. }
  623. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  624. #if defined(HAVE_GETRLIMIT) && !defined(HAVE_RLIM_T)
  625. typedef unsigned long rlim_t;
  626. #endif
  627. /** Learn the maximum allowed number of file descriptors. (Some systems
  628. * have a low soft limit.
  629. *
  630. * We compute this by finding the largest number between <b>limit</b>
  631. * and <b>cap</b> that we can use. If we can't find a number greater
  632. * than or equal to <b>limit</b>, then we fail: return -1.
  633. *
  634. * Otherwise, return the number minus some buffer to allow for other
  635. * file descriptors we'll want available for ordinary use. */
  636. int
  637. set_max_file_descriptors(unsigned long limit, unsigned long cap)
  638. {
  639. #ifndef HAVE_GETRLIMIT
  640. log_fn(LOG_INFO, LD_NET,
  641. "This platform is missing getrlimit(). Proceeding.");
  642. if (limit < cap) {
  643. log_info(LD_CONFIG, "ConnLimit must be at most %d. Using that.", (int)cap);
  644. limit = cap;
  645. }
  646. #else
  647. struct rlimit rlim;
  648. rlim_t most;
  649. tor_assert(limit > 0);
  650. tor_assert(cap > 0);
  651. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  652. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  653. strerror(errno));
  654. return -1;
  655. }
  656. //log_notice(LD_CONFIG, "%llu %llu", rlim.rlim_cur, rlim.rlim_max);
  657. if ((unsigned long)rlim.rlim_max < limit) {
  658. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  659. "limited to %lu. Please change your ulimit -n.",
  660. limit, (unsigned long)rlim.rlim_max);
  661. return -1;
  662. }
  663. most = rlim.rlim_max > (rlim_t)cap ? (rlim_t)cap : rlim.rlim_max;
  664. if ((rlim_t)most > rlim.rlim_cur) {
  665. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  666. (unsigned long)rlim.rlim_cur, (unsigned long)most);
  667. }
  668. rlim.rlim_cur = most;
  669. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  670. int bad = 1;
  671. #ifdef OPEN_MAX
  672. if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
  673. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  674. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  675. rlim.rlim_cur = OPEN_MAX;
  676. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  677. if (rlim.rlim_cur < (rlim_t)limit) {
  678. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  679. "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
  680. (unsigned long)OPEN_MAX, limit);
  681. } else {
  682. log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
  683. "Apparently, %lu was too high and rlimit lied to us.",
  684. (unsigned long)OPEN_MAX, (unsigned long)most);
  685. }
  686. most = rlim.rlim_cur;
  687. bad = 0;
  688. }
  689. }
  690. #endif
  691. if (bad) {
  692. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  693. strerror(errno));
  694. return -1;
  695. }
  696. }
  697. /* leave some overhead for logs, etc, */
  698. limit = most;
  699. #endif
  700. if (limit < ULIMIT_BUFFER) {
  701. log_warn(LD_CONFIG,
  702. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  703. return -1;
  704. }
  705. return limit - ULIMIT_BUFFER;
  706. }
  707. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  708. * success. On failure, log and return -1.
  709. */
  710. int
  711. switch_id(const char *user, const char *group)
  712. {
  713. #ifndef MS_WINDOWS
  714. struct passwd *pw = NULL;
  715. struct group *gr = NULL;
  716. if (user) {
  717. pw = getpwnam(user);
  718. if (pw == NULL) {
  719. log_warn(LD_CONFIG,"User '%s' not found.", user);
  720. return -1;
  721. }
  722. }
  723. /* switch the group first, while we still have the privileges to do so */
  724. if (group) {
  725. gr = getgrnam(group);
  726. if (gr == NULL) {
  727. log_warn(LD_CONFIG,"Group '%s' not found.", group);
  728. return -1;
  729. }
  730. if (setgid(gr->gr_gid) != 0) {
  731. log_warn(LD_GENERAL,"Error setting to configured GID: %s",
  732. strerror(errno));
  733. return -1;
  734. }
  735. } else if (user) {
  736. if (setgid(pw->pw_gid) != 0) {
  737. log_warn(LD_GENERAL,"Error setting to user GID: %s", strerror(errno));
  738. return -1;
  739. }
  740. }
  741. /* now that the group is switched, we can switch users and lose
  742. privileges */
  743. if (user) {
  744. if (setuid(pw->pw_uid) != 0) {
  745. log_warn(LD_GENERAL,"Error setting UID: %s", strerror(errno));
  746. return -1;
  747. }
  748. }
  749. return 0;
  750. #else
  751. (void)user;
  752. (void)group;
  753. #endif
  754. log_warn(LD_CONFIG,
  755. "User or group specified, but switching users is not supported.");
  756. return -1;
  757. }
  758. #ifdef HAVE_PWD_H
  759. /** Allocate and return a string containing the home directory for the
  760. * user <b>username</b>. Only works on posix-like systems. */
  761. char *
  762. get_user_homedir(const char *username)
  763. {
  764. struct passwd *pw;
  765. tor_assert(username);
  766. if (!(pw = getpwnam(username))) {
  767. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  768. return NULL;
  769. }
  770. return tor_strdup(pw->pw_dir);
  771. }
  772. #endif
  773. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  774. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  775. * but works on Windows and Solaris.)
  776. */
  777. int
  778. tor_inet_aton(const char *c, struct in_addr* addr)
  779. {
  780. #ifdef HAVE_INET_ATON
  781. return inet_aton(c, addr);
  782. #else
  783. uint32_t r;
  784. tor_assert(c);
  785. tor_assert(addr);
  786. if (strcmp(c, "255.255.255.255") == 0) {
  787. addr->s_addr = 0xFFFFFFFFu;
  788. return 1;
  789. }
  790. r = inet_addr(c);
  791. if (r == INADDR_NONE)
  792. return 0;
  793. addr->s_addr = r;
  794. return 1;
  795. #endif
  796. }
  797. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  798. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  799. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  800. * <b>dst</b> on success, NULL on failure.
  801. *
  802. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  803. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  804. * support.) */
  805. const char *
  806. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  807. {
  808. if (af == AF_INET) {
  809. if (tor_inet_ntoa(src, dst, len) < 0)
  810. return NULL;
  811. else
  812. return dst;
  813. } else if (af == AF_INET6) {
  814. const struct in6_addr *addr = src;
  815. char buf[64], *cp;
  816. int longestGapLen = 0, longestGapPos = -1, i,
  817. curGapPos = -1, curGapLen = 0;
  818. uint16_t words[8];
  819. for (i = 0; i < 8; ++i) {
  820. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  821. }
  822. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  823. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  824. (words[5] == 0xffff))) {
  825. /* This is an IPv4 address. */
  826. if (words[5] == 0) {
  827. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  828. addr->s6_addr[12], addr->s6_addr[13],
  829. addr->s6_addr[14], addr->s6_addr[15]);
  830. } else {
  831. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  832. addr->s6_addr[12], addr->s6_addr[13],
  833. addr->s6_addr[14], addr->s6_addr[15]);
  834. }
  835. if (strlen(buf) > len)
  836. return NULL;
  837. strlcpy(dst, buf, len);
  838. return dst;
  839. }
  840. i = 0;
  841. while (i < 8) {
  842. if (words[i] == 0) {
  843. curGapPos = i++;
  844. curGapLen = 1;
  845. while (i<8 && words[i] == 0) {
  846. ++i; ++curGapLen;
  847. }
  848. if (curGapLen > longestGapLen) {
  849. longestGapPos = curGapPos;
  850. longestGapLen = curGapLen;
  851. }
  852. } else {
  853. ++i;
  854. }
  855. }
  856. if (longestGapLen<=1)
  857. longestGapPos = -1;
  858. cp = buf;
  859. for (i = 0; i < 8; ++i) {
  860. if (words[i] == 0 && longestGapPos == i) {
  861. if (i == 0)
  862. *cp++ = ':';
  863. *cp++ = ':';
  864. while (i < 8 && words[i] == 0)
  865. ++i;
  866. --i; /* to compensate for loop increment. */
  867. } else {
  868. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  869. cp += strlen(cp);
  870. if (i != 7)
  871. *cp++ = ':';
  872. }
  873. }
  874. *cp = '\0';
  875. if (strlen(buf) > len)
  876. return NULL;
  877. strlcpy(dst, buf, len);
  878. return dst;
  879. } else {
  880. return NULL;
  881. }
  882. }
  883. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  884. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  885. * address and store the result in <b>dst</b> (which must have space for a
  886. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  887. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  888. *
  889. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  890. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  891. * support.) */
  892. int
  893. tor_inet_pton(int af, const char *src, void *dst)
  894. {
  895. if (af == AF_INET) {
  896. return tor_inet_aton(src, dst);
  897. } else if (af == AF_INET6) {
  898. struct in6_addr *out = dst;
  899. uint16_t words[8];
  900. int gapPos = -1, i, setWords=0;
  901. const char *dot = strchr(src, '.');
  902. const char *eow; /* end of words. */
  903. if (dot == src)
  904. return 0;
  905. else if (!dot)
  906. eow = src+strlen(src);
  907. else {
  908. int byte1,byte2,byte3,byte4;
  909. char more;
  910. for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
  911. ;
  912. ++eow;
  913. /* We use "scanf" because some platform inet_aton()s are too lax
  914. * about IPv4 addresses of the form "1.2.3" */
  915. if (sscanf(eow, "%d.%d.%d.%d%c", &byte1,&byte2,&byte3,&byte4,&more) != 4)
  916. return 0;
  917. if (byte1 > 255 || byte1 < 0 ||
  918. byte2 > 255 || byte2 < 0 ||
  919. byte3 > 255 || byte3 < 0 ||
  920. byte4 > 255 || byte4 < 0)
  921. return 0;
  922. words[6] = (byte1<<8) | byte2;
  923. words[7] = (byte3<<8) | byte4;
  924. setWords += 2;
  925. }
  926. i = 0;
  927. while (src < eow) {
  928. if (i > 7)
  929. return 0;
  930. if (TOR_ISXDIGIT(*src)) {
  931. char *next;
  932. int r = strtol(src, &next, 16);
  933. if (next > 4+src)
  934. return 0;
  935. if (next == src)
  936. return 0;
  937. if (r<0 || r>65536)
  938. return 0;
  939. words[i++] = (uint16_t)r;
  940. setWords++;
  941. src = next;
  942. if (*src != ':' && src != eow)
  943. return 0;
  944. ++src;
  945. } else if (*src == ':' && i > 0 && gapPos==-1) {
  946. gapPos = i;
  947. ++src;
  948. } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
  949. gapPos = i;
  950. src += 2;
  951. } else {
  952. return 0;
  953. }
  954. }
  955. if (setWords > 8 ||
  956. (setWords == 8 && gapPos != -1) ||
  957. (setWords < 8 && gapPos == -1))
  958. return 0;
  959. if (gapPos >= 0) {
  960. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  961. int gapLen = 8 - setWords;
  962. tor_assert(nToMove >= 0);
  963. memmove(&words[gapPos+gapLen], &words[gapPos],
  964. sizeof(uint16_t)*nToMove);
  965. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  966. }
  967. for (i = 0; i < 8; ++i) {
  968. out->s6_addr[2*i ] = words[i] >> 8;
  969. out->s6_addr[2*i+1] = words[i] & 0xff;
  970. }
  971. return 1;
  972. } else {
  973. return -1;
  974. }
  975. }
  976. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  977. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  978. * on success, -1 on failure; 1 on transient failure.
  979. *
  980. * (This function exists because standard windows gethostbyname
  981. * doesn't treat raw IP addresses properly.)
  982. */
  983. int
  984. tor_lookup_hostname(const char *name, uint32_t *addr)
  985. {
  986. tor_addr_t myaddr;
  987. int ret;
  988. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  989. return ret;
  990. if (IN_FAMILY(&myaddr) == AF_INET) {
  991. *addr = IPV4IPh(&myaddr);
  992. return ret;
  993. }
  994. return -1;
  995. }
  996. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  997. * *<b>addr</b> to the proper IP address and family. The <b>family</b>
  998. * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
  999. * <i>preferred</i> family, though another one may be returned if only one
  1000. * family is implemented for this address.
  1001. *
  1002. * Return 0 on success, -1 on failure; 1 on transient failure.
  1003. */
  1004. int
  1005. tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
  1006. {
  1007. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  1008. * something.
  1009. */
  1010. struct in_addr iaddr;
  1011. struct in6_addr iaddr6;
  1012. tor_assert(name);
  1013. tor_assert(addr);
  1014. tor_assert(family == AF_INET || family == AF_UNSPEC);
  1015. memset(addr, 0, sizeof(addr)); /* Clear the extraneous fields. */
  1016. if (!*name) {
  1017. /* Empty address is an error. */
  1018. return -1;
  1019. } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
  1020. /* It's an IPv4 IP. */
  1021. addr->family = AF_INET;
  1022. memcpy(&addr->addr.in_addr, &iaddr, sizeof(struct in_addr));
  1023. return 0;
  1024. } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
  1025. addr->family = AF_INET6;
  1026. memcpy(&addr->addr.in6_addr, &iaddr6, sizeof(struct in6_addr));
  1027. return 0;
  1028. } else {
  1029. #ifdef HAVE_GETADDRINFO
  1030. int err;
  1031. struct addrinfo *res=NULL, *res_p;
  1032. struct addrinfo *best=NULL;
  1033. struct addrinfo hints;
  1034. int result = -1;
  1035. memset(&hints, 0, sizeof(hints));
  1036. hints.ai_family = family;
  1037. hints.ai_socktype = SOCK_STREAM;
  1038. err = getaddrinfo(name, NULL, &hints, &res);
  1039. if (!err) {
  1040. best = NULL;
  1041. for (res_p = res; res_p; res_p = res_p->ai_next) {
  1042. if (family == AF_UNSPEC) {
  1043. if (res_p->ai_family == AF_INET) {
  1044. best = res_p;
  1045. break;
  1046. } else if (res_p->ai_family == AF_INET6 && !best) {
  1047. best = res_p;
  1048. }
  1049. } else if (family == res_p->ai_family) {
  1050. best = res_p;
  1051. break;
  1052. }
  1053. }
  1054. if (!best)
  1055. best = res;
  1056. if (best->ai_family == AF_INET) {
  1057. addr->family = AF_INET;
  1058. memcpy(&addr->addr.in_addr,
  1059. &((struct sockaddr_in*)best->ai_addr)->sin_addr,
  1060. sizeof(struct in_addr));
  1061. result = 0;
  1062. } else if (best->ai_family == AF_INET6) {
  1063. addr->family = AF_INET6;
  1064. memcpy(&addr->addr.in6_addr,
  1065. &((struct sockaddr_in6*)best->ai_addr)->sin6_addr,
  1066. sizeof(struct in6_addr));
  1067. result = 0;
  1068. }
  1069. freeaddrinfo(res);
  1070. return result;
  1071. }
  1072. return (err == EAI_AGAIN) ? 1 : -1;
  1073. #else
  1074. struct hostent *ent;
  1075. int err;
  1076. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  1077. char buf[2048];
  1078. struct hostent hostent;
  1079. int r;
  1080. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  1081. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1082. char buf[2048];
  1083. struct hostent hostent;
  1084. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  1085. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  1086. struct hostent_data data;
  1087. struct hostent hent;
  1088. memset(&data, 0, sizeof(data));
  1089. err = gethostbyname_r(name, &hent, &data);
  1090. ent = err ? NULL : &hent;
  1091. #else
  1092. ent = gethostbyname(name);
  1093. #ifdef MS_WINDOWS
  1094. err = WSAGetLastError();
  1095. #else
  1096. err = h_errno;
  1097. #endif
  1098. #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
  1099. if (ent) {
  1100. addr->family = ent->h_addrtype;
  1101. if (ent->h_addrtype == AF_INET) {
  1102. memcpy(&addr->addr.in_addr, ent->h_addr, sizeof(struct in_addr));
  1103. } else if (ent->h_addrtype == AF_INET6) {
  1104. memcpy(&addr->addr.in6_addr, ent->h_addr, sizeof(struct in6_addr));
  1105. } else {
  1106. tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
  1107. }
  1108. return 0;
  1109. }
  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. #if 0
  1614. /** Cross-platform condition implementation. */
  1615. struct tor_cond_t {
  1616. pthread_cond_t cond;
  1617. };
  1618. /** Return a newly allocated condition, with nobody waiting on it. */
  1619. tor_cond_t *
  1620. tor_cond_new(void)
  1621. {
  1622. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  1623. if (pthread_cond_init(&cond->cond, NULL)) {
  1624. tor_free(cond);
  1625. return NULL;
  1626. }
  1627. return cond;
  1628. }
  1629. /** Release all resources held by <b>cond</b>. */
  1630. void
  1631. tor_cond_free(tor_cond_t *cond)
  1632. {
  1633. tor_assert(cond);
  1634. if (pthread_cond_destroy(&cond->cond)) {
  1635. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  1636. return;
  1637. }
  1638. tor_free(cond);
  1639. }
  1640. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  1641. * All waiters on the condition must wait holding the same <b>mutex</b>.
  1642. * Returns 0 on success, negative on failure. */
  1643. int
  1644. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  1645. {
  1646. return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
  1647. }
  1648. /** Wake up one of the waiters on <b>cond</b>. */
  1649. void
  1650. tor_cond_signal_one(tor_cond_t *cond)
  1651. {
  1652. pthread_cond_signal(&cond->cond);
  1653. }
  1654. /** Wake up all of the waiters on <b>cond</b>. */
  1655. void
  1656. tor_cond_signal_all(tor_cond_t *cond)
  1657. {
  1658. pthread_cond_broadcast(&cond->cond);
  1659. }
  1660. #endif
  1661. /** Set up common structures for use by threading. */
  1662. void
  1663. tor_threads_init(void)
  1664. {
  1665. }
  1666. #elif defined(USE_WIN32_THREADS)
  1667. #if 0
  1668. static DWORD cond_event_tls_index;
  1669. struct tor_cond_t {
  1670. CRITICAL_SECTION mutex;
  1671. smartlist_t *events;
  1672. };
  1673. tor_cond_t *
  1674. tor_cond_new(void)
  1675. {
  1676. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  1677. InitializeCriticalSection(&cond->mutex);
  1678. cond->events = smartlist_create();
  1679. return cond;
  1680. }
  1681. void
  1682. tor_cond_free(tor_cond_t *cond)
  1683. {
  1684. tor_assert(cond);
  1685. DeleteCriticalSection(&cond->mutex);
  1686. /* XXXX notify? */
  1687. smartlist_free(cond->events);
  1688. tor_free(cond);
  1689. }
  1690. int
  1691. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  1692. {
  1693. HANDLE event;
  1694. int r;
  1695. tor_assert(cond);
  1696. tor_assert(mutex);
  1697. event = TlsGetValue(cond_event_tls_index);
  1698. if (!event) {
  1699. event = CreateEvent(0, FALSE, FALSE, NULL);
  1700. TlsSetValue(cond_event_tls_index, event);
  1701. }
  1702. EnterCriticalSection(&cond->mutex);
  1703. tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
  1704. tor_assert(!smartlist_isin(cond->events, event));
  1705. smartlist_add(cond->events, event);
  1706. LeaveCriticalSection(&cond->mutex);
  1707. tor_mutex_release(mutex);
  1708. r = WaitForSingleObject(event, INFINITE);
  1709. tor_mutex_acquire(mutex);
  1710. switch (r) {
  1711. case WAIT_OBJECT_0: /* we got the mutex normally. */
  1712. break;
  1713. case WAIT_ABANDONED: /* holding thread exited. */
  1714. case WAIT_TIMEOUT: /* Should never happen. */
  1715. tor_assert(0);
  1716. break;
  1717. case WAIT_FAILED:
  1718. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  1719. }
  1720. return 0;
  1721. }
  1722. void
  1723. tor_cond_signal_one(tor_cond_t *cond)
  1724. {
  1725. HANDLE event;
  1726. tor_assert(cond);
  1727. EnterCriticalSection(&cond->mutex);
  1728. if ((event = smartlist_pop_last(cond->events)))
  1729. SetEvent(event);
  1730. LeaveCriticalSection(&cond->mutex);
  1731. }
  1732. void
  1733. tor_cond_signal_all(tor_cond_t *cond)
  1734. {
  1735. tor_assert(cond);
  1736. EnterCriticalSection(&cond->mutex);
  1737. SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
  1738. smartlist_clear(cond->events);
  1739. LeaveCriticalSection(&cond->mutex);
  1740. }
  1741. #endif
  1742. void
  1743. tor_threads_init(void)
  1744. {
  1745. #if 0
  1746. cond_event_tls_index = TlsAlloc();
  1747. #endif
  1748. }
  1749. #endif
  1750. /**
  1751. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1752. * you need to ask the socket for its actual errno. Also, you need to
  1753. * get your errors from WSAGetLastError, not errno. (If you supply a
  1754. * socket of -1, we check WSAGetLastError, but don't correct
  1755. * WSAEWOULDBLOCKs.)
  1756. *
  1757. * The upshot of all of this is that when a socket call fails, you
  1758. * should call tor_socket_errno <em>at most once</em> on the failing
  1759. * socket to get the error.
  1760. */
  1761. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1762. int
  1763. tor_socket_errno(int sock)
  1764. {
  1765. int optval, optvallen=sizeof(optval);
  1766. int err = WSAGetLastError();
  1767. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1768. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1769. return err;
  1770. if (optval)
  1771. return optval;
  1772. }
  1773. return err;
  1774. }
  1775. #endif
  1776. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1777. #define E(code, s) { code, (s " [" #code " ]") }
  1778. struct { int code; const char *msg; } windows_socket_errors[] = {
  1779. E(WSAEINTR, "Interrupted function call"),
  1780. E(WSAEACCES, "Permission denied"),
  1781. E(WSAEFAULT, "Bad address"),
  1782. E(WSAEINVAL, "Invalid argument"),
  1783. E(WSAEMFILE, "Too many open files"),
  1784. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1785. E(WSAEINPROGRESS, "Operation now in progress"),
  1786. E(WSAEALREADY, "Operation already in progress"),
  1787. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1788. E(WSAEDESTADDRREQ, "Destination address required"),
  1789. E(WSAEMSGSIZE, "Message too long"),
  1790. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1791. E(WSAENOPROTOOPT, "Bad protocol option"),
  1792. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1793. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1794. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1795. E(WSAEOPNOTSUPP, "Operation not supported"),
  1796. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1797. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1798. E(WSAEADDRINUSE, "Address already in use"),
  1799. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1800. E(WSAENETDOWN, "Network is down"),
  1801. E(WSAENETUNREACH, "Network is unreachable"),
  1802. E(WSAENETRESET, "Network dropped connection on reset"),
  1803. E(WSAECONNABORTED, "Software caused connection abort"),
  1804. E(WSAECONNRESET, "Connection reset by peer"),
  1805. E(WSAENOBUFS, "No buffer space available"),
  1806. E(WSAEISCONN, "Socket is already connected"),
  1807. E(WSAENOTCONN, "Socket is not connected"),
  1808. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1809. E(WSAETIMEDOUT, "Connection timed out"),
  1810. E(WSAECONNREFUSED, "Connection refused"),
  1811. E(WSAEHOSTDOWN, "Host is down"),
  1812. E(WSAEHOSTUNREACH, "No route to host"),
  1813. E(WSAEPROCLIM, "Too many processes"),
  1814. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1815. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1816. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1817. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1818. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1819. #ifdef WSATYPE_NOT_FOUND
  1820. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1821. #endif
  1822. E(WSAHOST_NOT_FOUND, "Host not found"),
  1823. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1824. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1825. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1826. /* There are some more error codes whose numeric values are marked
  1827. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1828. * reason that practitioners of some craft traditions deliberately
  1829. * introduce imperfections into their baskets and rugs "to allow the
  1830. * evil spirits to escape." If we catch them, then our binaries
  1831. * might not report consistent results across versions of Windows.
  1832. * Thus, I'm going to let them all fall through.
  1833. */
  1834. { -1, NULL },
  1835. };
  1836. /** There does not seem to be a strerror equivalent for winsock errors.
  1837. * Naturally, we have to roll our own.
  1838. */
  1839. const char *
  1840. tor_socket_strerror(int e)
  1841. {
  1842. int i;
  1843. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1844. if (e == windows_socket_errors[i].code)
  1845. return windows_socket_errors[i].msg;
  1846. }
  1847. return strerror(e);
  1848. }
  1849. #endif
  1850. /** Called before we make any calls to network-related functions.
  1851. * (Some operating systems require their network libraries to be
  1852. * initialized.) */
  1853. int
  1854. network_init(void)
  1855. {
  1856. #ifdef MS_WINDOWS
  1857. /* This silly exercise is necessary before windows will allow
  1858. * gethostbyname to work. */
  1859. WSADATA WSAData;
  1860. int r;
  1861. r = WSAStartup(0x101,&WSAData);
  1862. if (r) {
  1863. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1864. return -1;
  1865. }
  1866. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1867. * We might use it to complain if we're trying to be a server but have
  1868. * too few sockets available. */
  1869. #endif
  1870. return 0;
  1871. }
  1872. #ifdef MS_WINDOWS
  1873. /** Return a newly allocated string describing the windows system error code
  1874. * <b>err</b>. Note that error codes are different from errno. Error codes
  1875. * come from GetLastError() when a winapi call fails. errno is set only when
  1876. * ansi functions fail. Whee. */
  1877. char *
  1878. format_win32_error(DWORD err)
  1879. {
  1880. LPVOID str = NULL;
  1881. char *result;
  1882. /* Somebody once decided that this interface was better than strerror(). */
  1883. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1884. FORMAT_MESSAGE_FROM_SYSTEM |
  1885. FORMAT_MESSAGE_IGNORE_INSERTS,
  1886. NULL, err,
  1887. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1888. (LPTSTR) &str,
  1889. 0, NULL);
  1890. if (str) {
  1891. result = tor_strdup((char*)str);
  1892. LocalFree(str); /* LocalFree != free() */
  1893. } else {
  1894. result = tor_strdup("<unformattable error>");
  1895. }
  1896. return result;
  1897. }
  1898. #endif