compat.c 78 KB

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