compat.c 71 KB

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