compat.c 66 KB

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