compat.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  1. /* Copyright 2003-2004 Roger Dingledine
  2. * Copyright 2004-2007 Roger Dingledine, Nick Mathewson */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char compat_c_id[] =
  6. "$Id$";
  7. /**
  8. * \file compat.c
  9. * \brief Wrappers to make calls more portable. This code defines
  10. * functions such as tor_malloc, tor_snprintf, get/set various data types,
  11. * renaming, setting socket options, switching user IDs. It is basically
  12. * where the non-portable items are conditionally included depending on
  13. * the platform.
  14. **/
  15. /* This is required on rh7 to make strptime not complain.
  16. * We also need it to make memmem get defined (where available)
  17. */
  18. #define _GNU_SOURCE
  19. #include "orconfig.h"
  20. #include "compat.h"
  21. #ifdef MS_WINDOWS
  22. #include <process.h>
  23. #include <windows.h>
  24. #endif
  25. #ifdef HAVE_UNAME
  26. #include <sys/utsname.h>
  27. #endif
  28. #ifdef HAVE_SYS_TIME_H
  29. #include <sys/time.h>
  30. #endif
  31. #ifdef HAVE_UNISTD_H
  32. #include <unistd.h>
  33. #endif
  34. #ifdef HAVE_SYS_FCNTL_H
  35. #include <sys/fcntl.h>
  36. #endif
  37. #ifdef HAVE_PWD_H
  38. #include <pwd.h>
  39. #endif
  40. #ifdef HAVE_GRP_H
  41. #include <grp.h>
  42. #endif
  43. #ifdef HAVE_FCNTL_H
  44. #include <fcntl.h>
  45. #endif
  46. #ifdef HAVE_SYS_RESOURCE_H
  47. #include <sys/resource.h>
  48. #endif
  49. #ifdef HAVE_ERRNO_H
  50. #include <errno.h>
  51. #endif
  52. #ifdef HAVE_NETINET_IN_H
  53. #include <netinet/in.h>
  54. #endif
  55. #ifdef HAVE_ARPA_INET_H
  56. #include <arpa/inet.h>
  57. #endif
  58. #ifndef HAVE_GETTIMEOFDAY
  59. #ifdef HAVE_FTIME
  60. #include <sys/timeb.h>
  61. #endif
  62. #endif
  63. #ifdef HAVE_SYS_SOCKET_H
  64. #include <sys/socket.h>
  65. #endif
  66. #ifdef HAVE_NETDB_H
  67. #include <netdb.h>
  68. #endif
  69. #ifdef HAVE_SYS_PARAM_H
  70. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  71. #endif
  72. #include <stdarg.h>
  73. #include <stdio.h>
  74. #include <stdlib.h>
  75. #include <string.h>
  76. #include <assert.h>
  77. #ifdef HAVE_PTHREAD_H
  78. #include <pthread.h>
  79. #endif
  80. #ifdef HAVE_SIGNAL_H
  81. #include <signal.h>
  82. #endif
  83. #ifdef HAVE_UTIME_H
  84. #include <utime.h>
  85. #endif
  86. #ifdef HAVE_SYS_UTIME_H
  87. #include <sys/utime.h>
  88. #endif
  89. #ifdef HAVE_SYS_MMAN_H
  90. #include <sys/mman.h>
  91. #endif
  92. #ifdef USE_BSOCKETS
  93. #include <bsocket.h>
  94. #endif
  95. #include "log.h"
  96. #include "util.h"
  97. /* Inline the strl functions if the platform doesn't have them. */
  98. #ifndef HAVE_STRLCPY
  99. #include "strlcpy.c"
  100. #endif
  101. #ifndef HAVE_STRLCAT
  102. #include "strlcat.c"
  103. #endif
  104. #ifndef INADDR_NONE
  105. /* This is used by inet_addr, but apparently Solaris doesn't define it
  106. * anyplace. */
  107. #define INADDR_NONE ((unsigned long) -1)
  108. #endif
  109. #ifdef HAVE_SYS_MMAN_H
  110. /** Implementation for tor_mmap_t: holds the regular tor_mmap_t, along
  111. * with extra fields needed for mmap()-based memory mapping. */
  112. typedef struct tor_mmap_impl_t {
  113. tor_mmap_t base;
  114. size_t mapping_size; /**< Size of the actual mapping. (This is this file
  115. * size, rounded up to the nearest page.) */
  116. } tor_mmap_impl_t;
  117. /** Try to create a memory mapping for <b>filename</b> and return it. On
  118. * failure, return NULL. */
  119. tor_mmap_t *
  120. tor_mmap_file(const char *filename)
  121. {
  122. int fd; /* router file */
  123. char *string;
  124. int page_size;
  125. tor_mmap_impl_t *res;
  126. size_t size, filesize;
  127. tor_assert(filename);
  128. fd = open(filename, O_RDONLY, 0);
  129. if (fd<0) {
  130. int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
  131. log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
  132. strerror(errno));
  133. return NULL;
  134. }
  135. size = filesize = (size_t) lseek(fd, 0, SEEK_END);
  136. lseek(fd, 0, SEEK_SET);
  137. /* ensure page alignment */
  138. page_size = getpagesize();
  139. size += (size%page_size) ? page_size-(size%page_size) : 0;
  140. if (!size) {
  141. /* Zero-length file. If we call mmap on it, it will succeed but
  142. * return NULL, and bad things will happen. So just fail. */
  143. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  144. return NULL;
  145. }
  146. string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  147. if (string == MAP_FAILED) {
  148. close(fd);
  149. log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
  150. strerror(errno));
  151. return NULL;
  152. }
  153. close(fd);
  154. res = tor_malloc_zero(sizeof(tor_mmap_impl_t));
  155. res->base.data = string;
  156. res->base.size = filesize;
  157. res->mapping_size = size;
  158. return &(res->base);
  159. }
  160. /** Release storage held for a memory mapping. */
  161. void
  162. tor_munmap_file(tor_mmap_t *handle)
  163. {
  164. tor_mmap_impl_t *h = SUBTYPE_P(handle, tor_mmap_impl_t, base);
  165. munmap((char*)h->base.data, h->mapping_size);
  166. tor_free(h);
  167. }
  168. #elif defined(MS_WINDOWS)
  169. /** Implementation for tor_mmap_t: holds the regular tor_mmap_t, along
  170. * with extra fields needed for WIN32 memory mapping. */
  171. typedef struct win_mmap_t {
  172. tor_mmap_t base;
  173. HANDLE file_handle;
  174. HANDLE mmap_handle;
  175. } win_mmap_t;
  176. tor_mmap_t *
  177. tor_mmap_file(const char *filename)
  178. {
  179. win_mmap_t *res = tor_malloc_zero(sizeof(win_mmap_t));
  180. res->file_handle = INVALID_HANDLE_VALUE;
  181. res->mmap_handle = NULL;
  182. res->file_handle = CreateFile(filename,
  183. GENERIC_READ,
  184. 0, NULL,
  185. OPEN_EXISTING,
  186. FILE_ATTRIBUTE_NORMAL,
  187. 0);
  188. if (res->file_handle == INVALID_HANDLE_VALUE)
  189. goto win_err;
  190. res->base.size = GetFileSize(res->file_handle, NULL);
  191. if (res->base.size == 0) {
  192. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  193. goto err;
  194. }
  195. res->mmap_handle = CreateFileMapping(res->file_handle,
  196. NULL,
  197. PAGE_READONLY,
  198. #if SIZEOF_SIZE_T > 4
  199. (res->base.size >> 32),
  200. #else
  201. 0,
  202. #endif
  203. (res->base.size & 0xfffffffful),
  204. NULL);
  205. if (res->mmap_handle == NULL)
  206. goto win_err;
  207. res->base.data = (char*) MapViewOfFile(res->mmap_handle,
  208. FILE_MAP_READ,
  209. 0, 0, 0);
  210. if (!res->base.data)
  211. goto win_err;
  212. return &(res->base);
  213. win_err: {
  214. DWORD e = GetLastError();
  215. int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
  216. LOG_INFO : LOG_WARN;
  217. char *msg = format_win32_error(e);
  218. log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
  219. tor_free(msg);
  220. }
  221. err:
  222. tor_munmap_file(&res->base);
  223. return NULL;
  224. }
  225. void
  226. tor_munmap_file(tor_mmap_t *handle)
  227. {
  228. win_mmap_t *h = SUBTYPE_P(handle, win_mmap_t, base);
  229. if (handle->data)
  230. /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
  231. have to be redefined as non-const. */
  232. UnmapViewOfFile( (LPVOID) handle->data);
  233. if (h->mmap_handle != NULL)
  234. CloseHandle(h->mmap_handle);
  235. if (h->file_handle != INVALID_HANDLE_VALUE)
  236. CloseHandle(h->file_handle);
  237. tor_free(h);
  238. }
  239. #else
  240. tor_mmap_t *
  241. tor_mmap_file(const char *filename)
  242. {
  243. struct stat st;
  244. char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  245. tor_mmap_t *handle;
  246. if (! res)
  247. return NULL;
  248. handle = tor_malloc_zero(sizeof(tor_mmap_t));
  249. handle->data = res;
  250. handle->size = st.st_size;
  251. return handle;
  252. }
  253. void
  254. tor_munmap_file(tor_mmap_t *handle)
  255. {
  256. char *d = (char*)handle->data;
  257. tor_free(d);
  258. memset(handle, 0, sizeof(tor_mmap_t));
  259. tor_free(handle);
  260. }
  261. #endif
  262. /** Replacement for snprintf. Differs from platform snprintf in two
  263. * ways: First, always NUL-terminates its output. Second, always
  264. * returns -1 if the result is truncated. (Note that this return
  265. * behavior does <i>not</i> conform to C99; it just happens to be
  266. * easier to emulate "return -1" with conformant implementations than
  267. * it is to emulate "return number that would be written" with
  268. * non-conformant implementations.) */
  269. int
  270. tor_snprintf(char *str, size_t size, const char *format, ...)
  271. {
  272. va_list ap;
  273. int r;
  274. va_start(ap,format);
  275. r = tor_vsnprintf(str,size,format,ap);
  276. va_end(ap);
  277. return r;
  278. }
  279. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  280. * snprintf.
  281. */
  282. int
  283. tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  284. {
  285. int r;
  286. if (size == 0)
  287. return -1; /* no place for the NUL */
  288. if (size > SIZE_T_CEILING)
  289. return -1;
  290. #ifdef MS_WINDOWS
  291. r = _vsnprintf(str, size, format, args);
  292. #else
  293. r = vsnprintf(str, size, format, args);
  294. #endif
  295. str[size-1] = '\0';
  296. if (r < 0 || ((size_t)r) >= size)
  297. return -1;
  298. return r;
  299. }
  300. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  301. * <b>needle</b>, return a pointer to the first occurrence of the needle
  302. * within the haystack, or NULL if there is no such occurrence.
  303. *
  304. * Requires that nlen be greater than zero.
  305. */
  306. const void *
  307. tor_memmem(const void *_haystack, size_t hlen,
  308. const void *_needle, size_t nlen)
  309. {
  310. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  311. tor_assert(nlen);
  312. return memmem(_haystack, hlen, _needle, nlen);
  313. #else
  314. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  315. * be. */
  316. const char *p, *end;
  317. const char *haystack = (const char*)_haystack;
  318. const char *needle = (const char*)_needle;
  319. char first;
  320. tor_assert(nlen);
  321. p = haystack;
  322. end = haystack + hlen;
  323. first = *(const char*)needle;
  324. while ((p = memchr(p, first, end-p))) {
  325. if (p+nlen > end)
  326. return NULL;
  327. if (!memcmp(p, needle, nlen))
  328. return p;
  329. ++p;
  330. }
  331. return NULL;
  332. #endif
  333. }
  334. #ifdef MS_WINDOWS
  335. /** Take a filename and return a pointer to its final element. This
  336. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  337. * contains the full path to the file. This is bad, because it
  338. * confuses users to find the home directory of the person who
  339. * compiled the binary in their warrning messages.
  340. */
  341. const char *
  342. tor_fix_source_file(const char *fname)
  343. {
  344. const char *cp1, *cp2, *r;
  345. cp1 = strrchr(fname, '/');
  346. cp2 = strrchr(fname, '\\');
  347. if (cp1 && cp2) {
  348. r = (cp1<cp2)?(cp2+1):(cp1+1);
  349. } else if (cp1) {
  350. r = cp1+1;
  351. } else if (cp2) {
  352. r = cp2+1;
  353. } else {
  354. r = fname;
  355. }
  356. return r;
  357. }
  358. #endif
  359. /**
  360. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  361. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  362. * unaligned memory access.
  363. */
  364. uint16_t
  365. get_uint16(const char *cp)
  366. {
  367. uint16_t v;
  368. memcpy(&v,cp,2);
  369. return v;
  370. }
  371. /**
  372. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  373. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  374. * unaligned memory access.
  375. */
  376. uint32_t
  377. get_uint32(const char *cp)
  378. {
  379. uint32_t v;
  380. memcpy(&v,cp,4);
  381. return v;
  382. }
  383. /**
  384. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  385. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  386. * unaligned memory access. */
  387. void
  388. set_uint16(char *cp, uint16_t v)
  389. {
  390. memcpy(cp,&v,2);
  391. }
  392. /**
  393. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  394. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  395. * unaligned memory access. */
  396. void
  397. set_uint32(char *cp, uint32_t v)
  398. {
  399. memcpy(cp,&v,4);
  400. }
  401. /**
  402. * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
  403. * the same as rename(2). On windows, this removes <b>to</b> first if
  404. * it already exists.
  405. * Returns 0 on success. Returns -1 and sets errno on failure.
  406. */
  407. int
  408. replace_file(const char *from, const char *to)
  409. {
  410. #ifndef MS_WINDOWS
  411. return rename(from,to);
  412. #else
  413. switch (file_status(to))
  414. {
  415. case FN_NOENT:
  416. break;
  417. case FN_FILE:
  418. if (unlink(to)) return -1;
  419. break;
  420. case FN_ERROR:
  421. return -1;
  422. case FN_DIR:
  423. errno = EISDIR;
  424. return -1;
  425. }
  426. return rename(from,to);
  427. #endif
  428. }
  429. /** Change <b>fname</b>'s modification time to now. */
  430. int
  431. touch_file(const char *fname)
  432. {
  433. if (utime(fname, NULL)!=0)
  434. return -1;
  435. return 0;
  436. }
  437. /** Turn <b>socket</b> into a nonblocking socket.
  438. */
  439. void
  440. set_socket_nonblocking(int socket)
  441. {
  442. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  443. unsigned long nonblocking = 1;
  444. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  445. #else
  446. fcntl(socket, F_SETFL, O_NONBLOCK);
  447. #endif
  448. }
  449. /**
  450. * Allocate a pair of connected sockets. (Like socketpair(family,
  451. * type,protocol,fd), but works on systems that don't have
  452. * socketpair.)
  453. *
  454. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  455. *
  456. * Note that on systems without socketpair, this call will fail if
  457. * localhost is inaccessible (for example, if the networking
  458. * stack is down). And even if it succeeds, the socket pair will not
  459. * be able to read while localhost is down later (the socket pair may
  460. * even close, depending on OS-specific timeouts).
  461. *
  462. * Returns 0 on success and -errno on failure; do not rely on the value
  463. * of errno or WSAGetLastError().
  464. **/
  465. /* It would be nicer just to set errno, but that won't work for windows. */
  466. int
  467. tor_socketpair(int family, int type, int protocol, int fd[2])
  468. {
  469. //don't use win32 socketpairs (they are always bad)
  470. #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
  471. int r;
  472. r = socketpair(family, type, protocol, fd);
  473. return r < 0 ? -errno : r;
  474. #elif defined(USE_BSOCKETS)
  475. return bsocketpair(family, type, protocol, fd);
  476. #else
  477. /* This socketpair does not work when localhost is down. So
  478. * it's really not the same thing at all. But it's close enough
  479. * for now, and really, when localhost is down sometimes, we
  480. * have other problems too.
  481. */
  482. int listener = -1;
  483. int connector = -1;
  484. int acceptor = -1;
  485. struct sockaddr_in listen_addr;
  486. struct sockaddr_in connect_addr;
  487. int size;
  488. int saved_errno = -1;
  489. if (protocol
  490. #ifdef AF_UNIX
  491. || family != AF_UNIX
  492. #endif
  493. ) {
  494. #ifdef MS_WINDOWS
  495. return -WSAEAFNOSUPPORT;
  496. #else
  497. return -EAFNOSUPPORT;
  498. #endif
  499. }
  500. if (!fd) {
  501. return -EINVAL;
  502. }
  503. listener = socket(AF_INET, type, 0);
  504. if (listener < 0)
  505. return -tor_socket_errno(-1);
  506. memset(&listen_addr, 0, sizeof(listen_addr));
  507. listen_addr.sin_family = AF_INET;
  508. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  509. listen_addr.sin_port = 0; /* kernel chooses port. */
  510. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  511. == -1)
  512. goto tidy_up_and_fail;
  513. if (listen(listener, 1) == -1)
  514. goto tidy_up_and_fail;
  515. connector = socket(AF_INET, type, 0);
  516. if (connector < 0)
  517. goto tidy_up_and_fail;
  518. /* We want to find out the port number to connect to. */
  519. size = sizeof(connect_addr);
  520. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  521. goto tidy_up_and_fail;
  522. if (size != sizeof (connect_addr))
  523. goto abort_tidy_up_and_fail;
  524. if (connect(connector, (struct sockaddr *) &connect_addr,
  525. sizeof(connect_addr)) == -1)
  526. goto tidy_up_and_fail;
  527. size = sizeof(listen_addr);
  528. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  529. if (acceptor < 0)
  530. goto tidy_up_and_fail;
  531. if (size != sizeof(listen_addr))
  532. goto abort_tidy_up_and_fail;
  533. tor_close_socket(listener);
  534. /* Now check we are talking to ourself by matching port and host on the
  535. two sockets. */
  536. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  537. goto tidy_up_and_fail;
  538. if (size != sizeof (connect_addr)
  539. || listen_addr.sin_family != connect_addr.sin_family
  540. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  541. || listen_addr.sin_port != connect_addr.sin_port) {
  542. goto abort_tidy_up_and_fail;
  543. }
  544. fd[0] = connector;
  545. fd[1] = acceptor;
  546. return 0;
  547. abort_tidy_up_and_fail:
  548. #ifdef MS_WINDOWS
  549. saved_errno = WSAECONNABORTED;
  550. #else
  551. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  552. #endif
  553. tidy_up_and_fail:
  554. if (saved_errno < 0)
  555. saved_errno = errno;
  556. if (listener != -1)
  557. tor_close_socket(listener);
  558. if (connector != -1)
  559. tor_close_socket(connector);
  560. if (acceptor != -1)
  561. tor_close_socket(acceptor);
  562. return -saved_errno;
  563. #endif
  564. }
  565. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  566. /** Learn the maximum allowed number of file descriptors. (Some systems
  567. * have a low soft limit.
  568. *
  569. * We compute this by finding the largest number between <b>limit</b>
  570. * and <b>cap</b> that we can use. If we can't find a number greater
  571. * than or equal to <b>limit</b>, then we fail: return -1.
  572. *
  573. * Otherwise, return the number minus some buffer to allow for other
  574. * file descriptors we'll want available for ordinary use. */
  575. int
  576. set_max_file_descriptors(unsigned long limit, unsigned long cap)
  577. {
  578. #ifndef HAVE_GETRLIMIT
  579. log_fn(LOG_INFO, LD_NET,
  580. "This platform is missing getrlimit(). Proceeding.");
  581. if (limit < cap) {
  582. log_info(LD_CONFIG, "ConnLimit must be at most %d. Using that.", (int)cap);
  583. limit = cap;
  584. }
  585. #else
  586. struct rlimit rlim;
  587. unsigned long most;
  588. tor_assert(limit > 0);
  589. tor_assert(cap > 0);
  590. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  591. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  592. strerror(errno));
  593. return -1;
  594. }
  595. if (rlim.rlim_max < limit) {
  596. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  597. "limited to %lu. Please change your ulimit -n.",
  598. limit, (unsigned long)rlim.rlim_max);
  599. return -1;
  600. }
  601. most = (rlim.rlim_max > cap) ? cap : (unsigned) rlim.rlim_max;
  602. if (most > rlim.rlim_cur) {
  603. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  604. (unsigned long)rlim.rlim_cur, most);
  605. }
  606. rlim.rlim_cur = most;
  607. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  608. log_warn(LD_CONFIG, "Could not set maximum number of file descriptors: %s",
  609. strerror(errno));
  610. return -1;
  611. }
  612. /* leave some overhead for logs, etc, */
  613. limit = most;
  614. #endif
  615. if (limit < ULIMIT_BUFFER) {
  616. log_warn(LD_CONFIG,
  617. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  618. return -1;
  619. }
  620. return limit - ULIMIT_BUFFER;
  621. }
  622. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  623. * success. On failure, log and return -1.
  624. */
  625. int
  626. switch_id(const char *user, const char *group)
  627. {
  628. #ifndef MS_WINDOWS
  629. struct passwd *pw = NULL;
  630. struct group *gr = NULL;
  631. if (user) {
  632. pw = getpwnam(user);
  633. if (pw == NULL) {
  634. log_warn(LD_CONFIG,"User '%s' not found.", user);
  635. return -1;
  636. }
  637. }
  638. /* switch the group first, while we still have the privileges to do so */
  639. if (group) {
  640. gr = getgrnam(group);
  641. if (gr == NULL) {
  642. log_warn(LD_CONFIG,"Group '%s' not found.", group);
  643. return -1;
  644. }
  645. if (setgid(gr->gr_gid) != 0) {
  646. log_warn(LD_GENERAL,"Error setting to configured GID: %s",
  647. strerror(errno));
  648. return -1;
  649. }
  650. } else if (user) {
  651. if (setgid(pw->pw_gid) != 0) {
  652. log_warn(LD_GENERAL,"Error setting to user GID: %s", strerror(errno));
  653. return -1;
  654. }
  655. }
  656. /* now that the group is switched, we can switch users and lose
  657. privileges */
  658. if (user) {
  659. if (setuid(pw->pw_uid) != 0) {
  660. log_warn(LD_GENERAL,"Error setting UID: %s", strerror(errno));
  661. return -1;
  662. }
  663. }
  664. return 0;
  665. #else
  666. (void)user;
  667. (void)group;
  668. #endif
  669. log_warn(LD_CONFIG,
  670. "User or group specified, but switching users is not supported.");
  671. return -1;
  672. }
  673. #ifdef HAVE_PWD_H
  674. /** Allocate and return a string containing the home directory for the
  675. * user <b>username</b>. Only works on posix-like systems */
  676. char *
  677. get_user_homedir(const char *username)
  678. {
  679. struct passwd *pw;
  680. tor_assert(username);
  681. if (!(pw = getpwnam(username))) {
  682. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  683. return NULL;
  684. }
  685. return tor_strdup(pw->pw_dir);
  686. }
  687. #endif
  688. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  689. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  690. * but works on Windows and Solaris.)
  691. */
  692. int
  693. tor_inet_aton(const char *c, struct in_addr* addr)
  694. {
  695. #ifdef HAVE_INET_ATON
  696. return inet_aton(c, addr);
  697. #else
  698. uint32_t r;
  699. tor_assert(c);
  700. tor_assert(addr);
  701. if (strcmp(c, "255.255.255.255") == 0) {
  702. addr->s_addr = 0xFFFFFFFFu;
  703. return 1;
  704. }
  705. r = inet_addr(c);
  706. if (r == INADDR_NONE)
  707. return 0;
  708. addr->s_addr = r;
  709. return 1;
  710. #endif
  711. }
  712. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  713. * *addr to the proper IP address, in network byte order. Returns 0
  714. * on success, -1 on failure; 1 on transient failure.
  715. *
  716. * (This function exists because standard windows gethostbyname
  717. * doesn't treat raw IP addresses properly.)
  718. */
  719. int
  720. tor_lookup_hostname(const char *name, uint32_t *addr)
  721. {
  722. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  723. * something.
  724. */
  725. struct in_addr iaddr;
  726. tor_assert(name);
  727. tor_assert(addr);
  728. if (!*name) {
  729. /* Empty address is an error. */
  730. return -1;
  731. } else if (tor_inet_aton(name, &iaddr)) {
  732. /* It's an IP. */
  733. memcpy(addr, &iaddr.s_addr, 4);
  734. return 0;
  735. } else {
  736. #ifdef HAVE_GETADDRINFO
  737. int err;
  738. struct addrinfo *res=NULL, *res_p;
  739. struct addrinfo hints;
  740. int result = -1;
  741. memset(&hints, 0, sizeof(hints));
  742. hints.ai_family = PF_INET;
  743. hints.ai_socktype = SOCK_STREAM;
  744. err = getaddrinfo(name, NULL, &hints, &res);
  745. if (!err) {
  746. for (res_p = res; res_p; res_p = res_p->ai_next) {
  747. if (res_p->ai_family == AF_INET) {
  748. struct sockaddr_in *sin = (struct sockaddr_in *)res_p->ai_addr;
  749. memcpy(addr, &sin->sin_addr, 4);
  750. result = 0;
  751. break;
  752. }
  753. }
  754. freeaddrinfo(res);
  755. return result;
  756. }
  757. return (err == EAI_AGAIN) ? 1 : -1;
  758. #else
  759. struct hostent *ent;
  760. int err;
  761. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  762. char buf[2048];
  763. struct hostent hostent;
  764. int r;
  765. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  766. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  767. char buf[2048];
  768. struct hostent hostent;
  769. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  770. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  771. struct hostent_data data;
  772. struct hostent hent;
  773. memset(&data, 0, sizeof(data));
  774. err = gethostbyname_r(name, &hent, &data);
  775. ent = err ? NULL : &hent;
  776. #else
  777. ent = gethostbyname(name);
  778. #ifdef MS_WINDOWS
  779. err = WSAGetLastError();
  780. #else
  781. err = h_errno;
  782. #endif
  783. #endif
  784. if (ent) {
  785. /* break to remind us if we move away from IPv4 */
  786. tor_assert(ent->h_length == 4);
  787. memcpy(addr, ent->h_addr, 4);
  788. return 0;
  789. }
  790. memset(addr, 0, 4);
  791. #ifdef MS_WINDOWS
  792. return (err == WSATRY_AGAIN) ? 1 : -1;
  793. #else
  794. return (err == TRY_AGAIN) ? 1 : -1;
  795. #endif
  796. #endif
  797. }
  798. }
  799. /** Hold the result of our call to <b>uname</b>. */
  800. static char uname_result[256];
  801. /** True iff uname_result is set. */
  802. static int uname_result_is_set = 0;
  803. /** Return a pointer to a description of our platform.
  804. */
  805. const char *
  806. get_uname(void)
  807. {
  808. #ifdef HAVE_UNAME
  809. struct utsname u;
  810. #endif
  811. if (!uname_result_is_set) {
  812. #ifdef HAVE_UNAME
  813. if (uname(&u) != -1) {
  814. /* (linux says 0 is success, solaris says 1 is success) */
  815. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  816. u.sysname, u.machine);
  817. } else
  818. #endif
  819. {
  820. #ifdef MS_WINDOWS
  821. OSVERSIONINFOEX info;
  822. int i;
  823. unsigned int leftover_mask;
  824. const char *plat = NULL;
  825. static struct {
  826. unsigned major; unsigned minor; const char *version;
  827. } win_version_table[] = {
  828. { 6, 0, "Windows \"Longhorn\"" },
  829. { 5, 2, "Windows Server 2003" },
  830. { 5, 1, "Windows XP" },
  831. { 5, 0, "Windows 2000" },
  832. /* { 4, 0, "Windows NT 4.0" }, */
  833. { 4, 90, "Windows Me" },
  834. { 4, 10, "Windows 98" },
  835. /* { 4, 0, "Windows 95" } */
  836. { 3, 51, "Windows NT 3.51" },
  837. { 0, 0, NULL }
  838. };
  839. #ifdef VER_SUITE_BACKOFFICE
  840. static struct {
  841. unsigned int mask; const char *str;
  842. } win_mask_table[] = {
  843. { VER_SUITE_BACKOFFICE, " {backoffice}" },
  844. { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
  845. { VER_SUITE_DATACENTER, " {datacenter}" },
  846. { VER_SUITE_ENTERPRISE, " {enterprise}" },
  847. { VER_SUITE_EMBEDDEDNT, " {embedded}" },
  848. { VER_SUITE_PERSONAL, " {personal}" },
  849. { VER_SUITE_SINGLEUSERTS,
  850. " {terminal services, single user}" },
  851. { VER_SUITE_SMALLBUSINESS, " {small business}" },
  852. { VER_SUITE_SMALLBUSINESS_RESTRICTED,
  853. " {small business, restricted}" },
  854. { VER_SUITE_TERMINAL, " {terminal services}" },
  855. { 0, NULL },
  856. };
  857. #endif
  858. memset(&info, 0, sizeof(info));
  859. info.dwOSVersionInfoSize = sizeof(info);
  860. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  861. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  862. " doesn't work.", sizeof(uname_result));
  863. uname_result_is_set = 1;
  864. return uname_result;
  865. }
  866. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  867. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  868. plat = "Windows NT 4.0";
  869. else
  870. plat = "Windows 95";
  871. } else {
  872. for (i=0; win_version_table[i].major>0; ++i) {
  873. if (win_version_table[i].major == info.dwMajorVersion &&
  874. win_version_table[i].minor == info.dwMinorVersion) {
  875. plat = win_version_table[i].version;
  876. break;
  877. }
  878. }
  879. }
  880. if (plat) {
  881. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  882. plat, info.szCSDVersion);
  883. } else {
  884. if (info.dwMajorVersion > 6 ||
  885. (info.dwMajorVersion==6 && info.dwMinorVersion>0))
  886. tor_snprintf(uname_result, sizeof(uname_result),
  887. "Very recent version of Windows [major=%d,minor=%d] %s",
  888. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  889. info.szCSDVersion);
  890. else
  891. tor_snprintf(uname_result, sizeof(uname_result),
  892. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  893. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  894. info.szCSDVersion);
  895. }
  896. #ifdef VER_SUITE_BACKOFFICE
  897. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  898. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  899. } else if (info.wProductType == VER_NT_SERVER) {
  900. strlcat(uname_result, " [server]", sizeof(uname_result));
  901. } else if (info.wProductType == VER_NT_WORKSTATION) {
  902. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  903. }
  904. leftover_mask = info.wSuiteMask;
  905. for (i = 0; win_mask_table[i].mask; ++i) {
  906. if (info.wSuiteMask & win_mask_table[i].mask) {
  907. strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
  908. leftover_mask &= ~win_mask_table[i].mask;
  909. }
  910. }
  911. if (leftover_mask) {
  912. size_t len = strlen(uname_result);
  913. tor_snprintf(uname_result+len, sizeof(uname_result)-len,
  914. " {0x%x}", info.wSuiteMask);
  915. }
  916. #endif
  917. #else
  918. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  919. #endif
  920. }
  921. uname_result_is_set = 1;
  922. }
  923. return uname_result;
  924. }
  925. /*
  926. * Process control
  927. */
  928. #if defined(USE_PTHREADS)
  929. /** Wraps a void (*)(void*) function and its argument so we can
  930. * invoke them in a way pthreads would expect.
  931. */
  932. typedef struct tor_pthread_data_t {
  933. void (*func)(void *);
  934. void *data;
  935. } tor_pthread_data_t;
  936. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  937. * and free _data. Used to make sure we can call functions the way pthread
  938. * expects. */
  939. static void *
  940. tor_pthread_helper_fn(void *_data)
  941. {
  942. tor_pthread_data_t *data = _data;
  943. void (*func)(void*);
  944. void *arg;
  945. /* mask signals to worker threads to avoid SIGPIPE, etc */
  946. sigset_t sigs;
  947. /* We're in a subthread; don't handle any signals here. */
  948. sigfillset(&sigs);
  949. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  950. func = data->func;
  951. arg = data->data;
  952. tor_free(_data);
  953. func(arg);
  954. return NULL;
  955. }
  956. #endif
  957. /** Minimalist interface to run a void function in the background. On
  958. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  959. * func should not return, but rather should call spawn_exit.
  960. *
  961. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  962. * since in a multithreaded environment, there is no way to be sure that
  963. * the caller's stack will still be around when the called function is
  964. * running.
  965. */
  966. int
  967. spawn_func(void (*func)(void *), void *data)
  968. {
  969. #if defined(USE_WIN32_THREADS)
  970. int rv;
  971. rv = (int)_beginthread(func, 0, data);
  972. if (rv == (int)-1)
  973. return -1;
  974. return 0;
  975. #elif defined(USE_PTHREADS)
  976. pthread_t thread;
  977. tor_pthread_data_t *d;
  978. d = tor_malloc(sizeof(tor_pthread_data_t));
  979. d->data = data;
  980. d->func = func;
  981. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  982. return -1;
  983. if (pthread_detach(thread))
  984. return -1;
  985. return 0;
  986. #else
  987. pid_t pid;
  988. pid = fork();
  989. if (pid<0)
  990. return -1;
  991. if (pid==0) {
  992. /* Child */
  993. func(data);
  994. tor_assert(0); /* Should never reach here. */
  995. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  996. } else {
  997. /* Parent */
  998. return 0;
  999. }
  1000. #endif
  1001. }
  1002. /** End the current thread/process.
  1003. */
  1004. void
  1005. spawn_exit(void)
  1006. {
  1007. #if defined(USE_WIN32_THREADS)
  1008. _endthread();
  1009. //we should never get here. my compiler thinks that _endthread returns, this
  1010. //is an attempt to fool it.
  1011. tor_assert(0);
  1012. _exit(0);
  1013. #elif defined(USE_PTHREADS)
  1014. pthread_exit(NULL);
  1015. #else
  1016. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  1017. * call _exit, not exit, from child processes. */
  1018. _exit(0);
  1019. #endif
  1020. }
  1021. /** Set *timeval to the current time of day. On error, log and terminate.
  1022. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  1023. */
  1024. void
  1025. tor_gettimeofday(struct timeval *timeval)
  1026. {
  1027. #ifdef MS_WINDOWS
  1028. /* Epoch bias copied from perl: number of units between windows epoch and
  1029. * unix epoch. */
  1030. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  1031. #define UNITS_PER_SEC U64_LITERAL(10000000)
  1032. #define USEC_PER_SEC U64_LITERAL(1000000)
  1033. #define UNITS_PER_USEC U64_LITERAL(10)
  1034. union {
  1035. uint64_t ft_64;
  1036. FILETIME ft_ft;
  1037. } ft;
  1038. /* number of 100-nsec units since Jan 1, 1601 */
  1039. GetSystemTimeAsFileTime(&ft.ft_ft);
  1040. if (ft.ft_64 < EPOCH_BIAS) {
  1041. log_err(LD_GENERAL,"System time is before 1970; failing.");
  1042. exit(1);
  1043. }
  1044. ft.ft_64 -= EPOCH_BIAS;
  1045. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  1046. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  1047. #elif defined(HAVE_GETTIMEOFDAY)
  1048. if (gettimeofday(timeval, NULL)) {
  1049. log_err(LD_GENERAL,"gettimeofday failed.");
  1050. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  1051. or segfaulted.*/
  1052. exit(1);
  1053. }
  1054. #elif defined(HAVE_FTIME)
  1055. struct timeb tb;
  1056. ftime(&tb);
  1057. timeval->tv_sec = tb.time;
  1058. timeval->tv_usec = tb.millitm * 1000;
  1059. #else
  1060. #error "No way to get time."
  1061. #endif
  1062. return;
  1063. }
  1064. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  1065. /** Defined iff we need to add locks when defining fake versions of reentrant
  1066. * versions of time-related functions. */
  1067. #define TIME_FNS_NEED_LOCKS
  1068. #endif
  1069. #ifndef HAVE_LOCALTIME_R
  1070. #ifdef TIME_FNS_NEED_LOCKS
  1071. struct tm *
  1072. tor_localtime_r(const time_t *timep, struct tm *result)
  1073. {
  1074. struct tm *r;
  1075. static tor_mutex_t *m=NULL;
  1076. if (!m) { m=tor_mutex_new(); }
  1077. tor_assert(result);
  1078. tor_mutex_acquire(m);
  1079. r = localtime(timep);
  1080. memcpy(result, r, sizeof(struct tm));
  1081. tor_mutex_release(m);
  1082. return result;
  1083. }
  1084. #else
  1085. struct tm *
  1086. tor_localtime_r(const time_t *timep, struct tm *result)
  1087. {
  1088. struct tm *r;
  1089. tor_assert(result);
  1090. r = localtime(timep);
  1091. memcpy(result, r, sizeof(struct tm));
  1092. return result;
  1093. }
  1094. #endif
  1095. #endif
  1096. #ifndef HAVE_GMTIME_R
  1097. #ifdef TIME_FNS_NEED_LOCKS
  1098. struct tm *
  1099. tor_gmtime_r(const time_t *timep, struct tm *result)
  1100. {
  1101. struct tm *r;
  1102. static tor_mutex_t *m=NULL;
  1103. if (!m) { m=tor_mutex_new(); }
  1104. tor_assert(result);
  1105. tor_mutex_acquire(m);
  1106. r = gmtime(timep);
  1107. memcpy(result, r, sizeof(struct tm));
  1108. tor_mutex_release(m);
  1109. return result;
  1110. }
  1111. #else
  1112. struct tm *
  1113. tor_gmtime_r(const time_t *timep, struct tm *result)
  1114. {
  1115. struct tm *r;
  1116. tor_assert(result);
  1117. r = gmtime(timep);
  1118. memcpy(result, r, sizeof(struct tm));
  1119. return result;
  1120. }
  1121. #endif
  1122. #endif
  1123. #ifdef USE_WIN32_THREADS
  1124. /** A generic lock structure for multithreaded builds. */
  1125. struct tor_mutex_t {
  1126. HANDLE handle;
  1127. };
  1128. tor_mutex_t *
  1129. tor_mutex_new(void)
  1130. {
  1131. tor_mutex_t *m;
  1132. m = tor_malloc_zero(sizeof(tor_mutex_t));
  1133. m->handle = CreateMutex(NULL, FALSE, NULL);
  1134. tor_assert(m->handle != NULL);
  1135. return m;
  1136. }
  1137. void
  1138. tor_mutex_free(tor_mutex_t *m)
  1139. {
  1140. CloseHandle(m->handle);
  1141. tor_free(m);
  1142. }
  1143. void
  1144. tor_mutex_acquire(tor_mutex_t *m)
  1145. {
  1146. DWORD r;
  1147. r = WaitForSingleObject(m->handle, INFINITE);
  1148. switch (r) {
  1149. case WAIT_ABANDONED: /* holding thread exited. */
  1150. case WAIT_OBJECT_0: /* we got the mutex normally. */
  1151. break;
  1152. case WAIT_TIMEOUT: /* Should never happen. */
  1153. tor_assert(0);
  1154. break;
  1155. case WAIT_FAILED:
  1156. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  1157. }
  1158. }
  1159. void
  1160. tor_mutex_release(tor_mutex_t *m)
  1161. {
  1162. BOOL r;
  1163. r = ReleaseMutex(m->handle);
  1164. if (!r) {
  1165. log_warn(LD_GENERAL, "Failed to release mutex: %d", (int) GetLastError());
  1166. }
  1167. }
  1168. unsigned long
  1169. tor_get_thread_id(void)
  1170. {
  1171. return (unsigned long)GetCurrentThreadId();
  1172. }
  1173. #elif defined(USE_PTHREADS)
  1174. /** A generic lock structure for multithreaded builds. */
  1175. struct tor_mutex_t {
  1176. pthread_mutex_t mutex;
  1177. };
  1178. /** Allocate and return new lock. */
  1179. tor_mutex_t *
  1180. tor_mutex_new(void)
  1181. {
  1182. tor_mutex_t *mutex = tor_malloc_zero(sizeof(tor_mutex_t));
  1183. pthread_mutex_init(&mutex->mutex, NULL);
  1184. return mutex;
  1185. }
  1186. /** Wait until <b>m</b> is free, then acquire it. */
  1187. void
  1188. tor_mutex_acquire(tor_mutex_t *m)
  1189. {
  1190. tor_assert(m);
  1191. pthread_mutex_lock(&m->mutex);
  1192. }
  1193. /** Release the lock <b>m</b> so another thread can have it. */
  1194. void
  1195. tor_mutex_release(tor_mutex_t *m)
  1196. {
  1197. tor_assert(m);
  1198. pthread_mutex_unlock(&m->mutex);
  1199. }
  1200. /** Free all storage held by the lock <b>m</b>. */
  1201. void
  1202. tor_mutex_free(tor_mutex_t *m)
  1203. {
  1204. tor_assert(m);
  1205. pthread_mutex_destroy(&m->mutex);
  1206. tor_free(m);
  1207. }
  1208. /** Return an integer representing this thread. */
  1209. unsigned long
  1210. tor_get_thread_id(void)
  1211. {
  1212. union {
  1213. pthread_t thr;
  1214. unsigned long id;
  1215. } r;
  1216. r.thr = pthread_self();
  1217. return r.id;
  1218. }
  1219. #else
  1220. /** A generic lock structure for multithreaded builds. */
  1221. struct tor_mutex_t {
  1222. int _unused;
  1223. };
  1224. #endif
  1225. /**
  1226. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1227. * you need to ask the socket for its actual errno. Also, you need to
  1228. * get your errors from WSAGetLastError, not errno. (If you supply a
  1229. * socket of -1, we check WSAGetLastError, but don't correct
  1230. * WSAEWOULDBLOCKs.)
  1231. *
  1232. * The upshot of all of this is that when a socket call fails, you
  1233. * should call tor_socket_errno <em>at most once</em> on the failing
  1234. * socket to get the error.
  1235. */
  1236. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1237. int
  1238. tor_socket_errno(int sock)
  1239. {
  1240. int optval, optvallen=sizeof(optval);
  1241. int err = WSAGetLastError();
  1242. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1243. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1244. return err;
  1245. if (optval)
  1246. return optval;
  1247. }
  1248. return err;
  1249. }
  1250. #endif
  1251. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1252. #define E(code, s) { code, (s " [" #code " ]") }
  1253. struct { int code; const char *msg; } windows_socket_errors[] = {
  1254. E(WSAEINTR, "Interrupted function call"),
  1255. E(WSAEACCES, "Permission denied"),
  1256. E(WSAEFAULT, "Bad address"),
  1257. E(WSAEINVAL, "Invalid argument"),
  1258. E(WSAEMFILE, "Too many open files"),
  1259. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1260. E(WSAEINPROGRESS, "Operation now in progress"),
  1261. E(WSAEALREADY, "Operation already in progress"),
  1262. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1263. E(WSAEDESTADDRREQ, "Destination address required"),
  1264. E(WSAEMSGSIZE, "Message too long"),
  1265. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1266. E(WSAENOPROTOOPT, "Bad protocol option"),
  1267. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1268. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1269. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1270. E(WSAEOPNOTSUPP, "Operation not supported"),
  1271. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1272. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1273. E(WSAEADDRINUSE, "Address already in use"),
  1274. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1275. E(WSAENETDOWN, "Network is down"),
  1276. E(WSAENETUNREACH, "Network is unreachable"),
  1277. E(WSAENETRESET, "Network dropped connection on reset"),
  1278. E(WSAECONNABORTED, "Software caused connection abort"),
  1279. E(WSAECONNRESET, "Connection reset by peer"),
  1280. E(WSAENOBUFS, "No buffer space available"),
  1281. E(WSAEISCONN, "Socket is already connected"),
  1282. E(WSAENOTCONN, "Socket is not connected"),
  1283. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1284. E(WSAETIMEDOUT, "Connection timed out"),
  1285. E(WSAECONNREFUSED, "Connection refused"),
  1286. E(WSAEHOSTDOWN, "Host is down"),
  1287. E(WSAEHOSTUNREACH, "No route to host"),
  1288. E(WSAEPROCLIM, "Too many processes"),
  1289. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1290. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1291. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1292. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1293. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1294. #ifdef WSATYPE_NOT_FOUND
  1295. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1296. #endif
  1297. E(WSAHOST_NOT_FOUND, "Host not found"),
  1298. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1299. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1300. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1301. /* There are some more error codes whose numeric values are marked
  1302. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1303. * reason that practitioners of some craft traditions deliberately
  1304. * introduce imperfections into their baskets and rugs "to allow the
  1305. * evil spirits to escape." If we catch them, then our binaries
  1306. * might not report consistent results across versions of Windows.
  1307. * Thus, I'm going to let them all fall through.
  1308. */
  1309. { -1, NULL },
  1310. };
  1311. /** There does not seem to be a strerror equivalent for winsock errors.
  1312. * Naturally, we have to roll our own.
  1313. */
  1314. const char *
  1315. tor_socket_strerror(int e)
  1316. {
  1317. int i;
  1318. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1319. if (e == windows_socket_errors[i].code)
  1320. return windows_socket_errors[i].msg;
  1321. }
  1322. return strerror(e);
  1323. }
  1324. #endif
  1325. /** Called before we make any calls to network-related functions.
  1326. * (Some operating systems require their network libraries to be
  1327. * initialized.) */
  1328. int
  1329. network_init(void)
  1330. {
  1331. #ifdef MS_WINDOWS
  1332. /* This silly exercise is necessary before windows will allow
  1333. * gethostbyname to work. */
  1334. WSADATA WSAData;
  1335. int r;
  1336. r = WSAStartup(0x101,&WSAData);
  1337. if (r) {
  1338. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1339. return -1;
  1340. }
  1341. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1342. * We might use it to complain if we're trying to be a server but have
  1343. * too few sockets available. */
  1344. #endif
  1345. return 0;
  1346. }
  1347. #ifdef MS_WINDOWS
  1348. /** Return a newly allocated string describing the windows system error code
  1349. * <b>err</b>. Note that error codes are different from errno. Error codes
  1350. * come from GetLastError() when a winapi call fails. errno is set only when
  1351. * ansi functions fail. Whee. */
  1352. char *
  1353. format_win32_error(DWORD err)
  1354. {
  1355. LPVOID str = NULL;
  1356. char *result;
  1357. /* Somebody once decided that this interface was better than strerror(). */
  1358. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1359. FORMAT_MESSAGE_FROM_SYSTEM |
  1360. FORMAT_MESSAGE_IGNORE_INSERTS,
  1361. NULL, err,
  1362. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1363. (LPTSTR) &str,
  1364. 0, NULL);
  1365. if (str) {
  1366. result = tor_strdup((char*)str);
  1367. LocalFree(str); /* LocalFree != free() */
  1368. } else {
  1369. result = tor_strdup("<unformattable error>");
  1370. }
  1371. return result;
  1372. }
  1373. #endif