compat.c 53 KB

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