compat.c 39 KB

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