compat.c 54 KB

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