compat.c 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2014, 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. /* XXXX024 We should just use AC_USE_SYSTEM_EXTENSIONS in our autoconf,
  17. * and get this (and other important stuff!) automatically. Once we do that,
  18. * make sure to also change the extern char **environ detection in
  19. * configure.ac, because whether that is declared or not depends on whether
  20. * we have _GNU_SOURCE defined! Maybe that means that once we take this out,
  21. * we can also take out the configure check. */
  22. #define _GNU_SOURCE
  23. #define COMPAT_PRIVATE
  24. #include "compat.h"
  25. #ifdef _WIN32
  26. #include <process.h>
  27. #include <windows.h>
  28. #include <sys/locking.h>
  29. #endif
  30. #ifdef HAVE_UNAME
  31. #include <sys/utsname.h>
  32. #endif
  33. #ifdef HAVE_SYS_TYPES_H
  34. #include <sys/types.h>
  35. #endif
  36. #ifdef HAVE_SYS_SYSCTL_H
  37. #include <sys/sysctl.h>
  38. #endif
  39. #ifdef HAVE_SYS_STAT_H
  40. #include <sys/stat.h>
  41. #endif
  42. #ifdef HAVE_UNISTD_H
  43. #include <unistd.h>
  44. #endif
  45. #ifdef HAVE_SYS_FCNTL_H
  46. #include <sys/fcntl.h>
  47. #endif
  48. #ifdef HAVE_PWD_H
  49. #include <pwd.h>
  50. #endif
  51. #ifdef HAVE_GRP_H
  52. #include <grp.h>
  53. #endif
  54. #ifdef HAVE_FCNTL_H
  55. #include <fcntl.h>
  56. #endif
  57. #ifdef HAVE_ERRNO_H
  58. #include <errno.h>
  59. #endif
  60. #ifdef HAVE_ARPA_INET_H
  61. #include <arpa/inet.h>
  62. #endif
  63. #ifdef HAVE_CRT_EXTERNS_H
  64. #include <crt_externs.h>
  65. #endif
  66. #ifndef HAVE_GETTIMEOFDAY
  67. #ifdef HAVE_FTIME
  68. #include <sys/timeb.h>
  69. #endif
  70. #endif
  71. /* Includes for the process attaching prevention */
  72. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  73. /* Only use the linux prctl; the IRIX prctl is totally different */
  74. #include <sys/prctl.h>
  75. #elif defined(__APPLE__)
  76. #include <sys/types.h>
  77. #include <sys/ptrace.h>
  78. #endif
  79. #ifdef HAVE_NETDB_H
  80. #include <netdb.h>
  81. #endif
  82. #ifdef HAVE_SYS_PARAM_H
  83. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  84. #endif
  85. #include <stdio.h>
  86. #include <stdlib.h>
  87. #include <assert.h>
  88. #ifdef HAVE_SIGNAL_H
  89. #include <signal.h>
  90. #endif
  91. #ifdef HAVE_UTIME_H
  92. #include <utime.h>
  93. #endif
  94. #ifdef HAVE_SYS_UTIME_H
  95. #include <sys/utime.h>
  96. #endif
  97. #ifdef HAVE_SYS_MMAN_H
  98. #include <sys/mman.h>
  99. #endif
  100. #ifdef HAVE_SYS_SYSLIMITS_H
  101. #include <sys/syslimits.h>
  102. #endif
  103. #ifdef HAVE_SYS_FILE_H
  104. #include <sys/file.h>
  105. #endif
  106. #ifdef TOR_UNIT_TESTS
  107. #if !defined(HAVE_USLEEP) && defined(HAVE_SYS_SELECT_H)
  108. /* as fallback implementation for tor_sleep_msec */
  109. #include <sys/select.h>
  110. #endif
  111. #endif
  112. #include "torlog.h"
  113. #include "util.h"
  114. #include "container.h"
  115. #include "address.h"
  116. #include "sandbox.h"
  117. /* Inline the strl functions if the platform doesn't have them. */
  118. #ifndef HAVE_STRLCPY
  119. #include "strlcpy.c"
  120. #endif
  121. #ifndef HAVE_STRLCAT
  122. #include "strlcat.c"
  123. #endif
  124. /** As open(path, flags, mode), but return an fd with the close-on-exec mode
  125. * set. */
  126. int
  127. tor_open_cloexec(const char *path, int flags, unsigned mode)
  128. {
  129. int fd;
  130. #ifdef O_CLOEXEC
  131. path = sandbox_intern_string(path);
  132. fd = open(path, flags|O_CLOEXEC, mode);
  133. if (fd >= 0)
  134. return fd;
  135. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  136. * even though we were built on a system with O_CLOEXEC support, we
  137. * are running on one without. */
  138. if (errno != EINVAL)
  139. return -1;
  140. #endif
  141. log_debug(LD_FS, "Opening %s with flags %x", path, flags);
  142. fd = open(path, flags, mode);
  143. #ifdef FD_CLOEXEC
  144. if (fd >= 0) {
  145. if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
  146. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  147. close(fd);
  148. return -1;
  149. }
  150. }
  151. #endif
  152. return fd;
  153. }
  154. /** As fopen(path,mode), but ensures that the O_CLOEXEC bit is set on the
  155. * underlying file handle. */
  156. FILE *
  157. tor_fopen_cloexec(const char *path, const char *mode)
  158. {
  159. FILE *result = fopen(path, mode);
  160. #ifdef FD_CLOEXEC
  161. if (result != NULL) {
  162. if (fcntl(fileno(result), F_SETFD, FD_CLOEXEC) == -1) {
  163. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  164. fclose(result);
  165. return NULL;
  166. }
  167. }
  168. #endif
  169. return result;
  170. }
  171. /** As rename(), but work correctly with the sandbox. */
  172. int
  173. tor_rename(const char *path_old, const char *path_new)
  174. {
  175. log_debug(LD_FS, "Renaming %s to %s", path_old, path_new);
  176. return rename(sandbox_intern_string(path_old),
  177. sandbox_intern_string(path_new));
  178. }
  179. #if defined(HAVE_SYS_MMAN_H) || defined(RUNNING_DOXYGEN)
  180. /** Try to create a memory mapping for <b>filename</b> and return it. On
  181. * failure, return NULL. Sets errno properly, using ERANGE to mean
  182. * "empty file". */
  183. tor_mmap_t *
  184. tor_mmap_file(const char *filename)
  185. {
  186. int fd; /* router file */
  187. char *string;
  188. int page_size, result;
  189. tor_mmap_t *res;
  190. size_t size, filesize;
  191. struct stat st;
  192. tor_assert(filename);
  193. fd = tor_open_cloexec(filename, O_RDONLY, 0);
  194. if (fd<0) {
  195. int save_errno = errno;
  196. int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
  197. log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
  198. strerror(errno));
  199. errno = save_errno;
  200. return NULL;
  201. }
  202. /* Get the size of the file */
  203. result = fstat(fd, &st);
  204. if (result != 0) {
  205. int save_errno = errno;
  206. log_warn(LD_FS,
  207. "Couldn't fstat opened descriptor for \"%s\" during mmap: %s",
  208. filename, strerror(errno));
  209. close(fd);
  210. errno = save_errno;
  211. return NULL;
  212. }
  213. size = filesize = (size_t)(st.st_size);
  214. /*
  215. * Should we check for weird crap like mmapping a named pipe here,
  216. * or just wait for if (!size) below to fail?
  217. */
  218. /* ensure page alignment */
  219. page_size = getpagesize();
  220. size += (size%page_size) ? page_size-(size%page_size) : 0;
  221. if (!size) {
  222. /* Zero-length file. If we call mmap on it, it will succeed but
  223. * return NULL, and bad things will happen. So just fail. */
  224. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  225. errno = ERANGE;
  226. close(fd);
  227. return NULL;
  228. }
  229. string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  230. close(fd);
  231. if (string == MAP_FAILED) {
  232. int save_errno = errno;
  233. log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
  234. strerror(errno));
  235. errno = save_errno;
  236. return NULL;
  237. }
  238. res = tor_malloc_zero(sizeof(tor_mmap_t));
  239. res->data = string;
  240. res->size = filesize;
  241. res->mapping_size = size;
  242. return res;
  243. }
  244. /** Release storage held for a memory mapping; returns 0 on success,
  245. * or -1 on failure (and logs a warning). */
  246. int
  247. tor_munmap_file(tor_mmap_t *handle)
  248. {
  249. int res;
  250. if (handle == NULL)
  251. return 0;
  252. res = munmap((char*)handle->data, handle->mapping_size);
  253. if (res == 0) {
  254. /* munmap() succeeded */
  255. tor_free(handle);
  256. } else {
  257. log_warn(LD_FS, "Failed to munmap() in tor_munmap_file(): %s",
  258. strerror(errno));
  259. res = -1;
  260. }
  261. return res;
  262. }
  263. #elif defined(_WIN32)
  264. tor_mmap_t *
  265. tor_mmap_file(const char *filename)
  266. {
  267. TCHAR tfilename[MAX_PATH]= {0};
  268. tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
  269. int empty = 0;
  270. HANDLE file_handle = INVALID_HANDLE_VALUE;
  271. DWORD size_low, size_high;
  272. uint64_t real_size;
  273. res->mmap_handle = NULL;
  274. #ifdef UNICODE
  275. mbstowcs(tfilename,filename,MAX_PATH);
  276. #else
  277. strlcpy(tfilename,filename,MAX_PATH);
  278. #endif
  279. file_handle = CreateFile(tfilename,
  280. GENERIC_READ, FILE_SHARE_READ,
  281. NULL,
  282. OPEN_EXISTING,
  283. FILE_ATTRIBUTE_NORMAL,
  284. 0);
  285. if (file_handle == INVALID_HANDLE_VALUE)
  286. goto win_err;
  287. size_low = GetFileSize(file_handle, &size_high);
  288. if (size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
  289. log_warn(LD_FS,"Error getting size of \"%s\".",filename);
  290. goto win_err;
  291. }
  292. if (size_low == 0 && size_high == 0) {
  293. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  294. empty = 1;
  295. goto err;
  296. }
  297. real_size = (((uint64_t)size_high)<<32) | size_low;
  298. if (real_size > SIZE_MAX) {
  299. log_warn(LD_FS,"File \"%s\" is too big to map; not trying.",filename);
  300. goto err;
  301. }
  302. res->size = real_size;
  303. res->mmap_handle = CreateFileMapping(file_handle,
  304. NULL,
  305. PAGE_READONLY,
  306. size_high,
  307. size_low,
  308. NULL);
  309. if (res->mmap_handle == NULL)
  310. goto win_err;
  311. res->data = (char*) MapViewOfFile(res->mmap_handle,
  312. FILE_MAP_READ,
  313. 0, 0, 0);
  314. if (!res->data)
  315. goto win_err;
  316. CloseHandle(file_handle);
  317. return res;
  318. win_err: {
  319. DWORD e = GetLastError();
  320. int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
  321. LOG_INFO : LOG_WARN;
  322. char *msg = format_win32_error(e);
  323. log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
  324. tor_free(msg);
  325. if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
  326. errno = ENOENT;
  327. else
  328. errno = EINVAL;
  329. }
  330. err:
  331. if (empty)
  332. errno = ERANGE;
  333. if (file_handle != INVALID_HANDLE_VALUE)
  334. CloseHandle(file_handle);
  335. tor_munmap_file(res);
  336. return NULL;
  337. }
  338. /* Unmap the file, and return 0 for success or -1 for failure */
  339. int
  340. tor_munmap_file(tor_mmap_t *handle)
  341. {
  342. if (handle == NULL)
  343. return 0;
  344. if (handle->data) {
  345. /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
  346. have to be redefined as non-const. */
  347. BOOL ok = UnmapViewOfFile( (LPVOID) handle->data);
  348. if (!ok) {
  349. log_warn(LD_FS, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
  350. (int)GetLastError());
  351. }
  352. }
  353. if (handle->mmap_handle != NULL)
  354. CloseHandle(handle->mmap_handle);
  355. tor_free(handle);
  356. return 0;
  357. }
  358. #else
  359. tor_mmap_t *
  360. tor_mmap_file(const char *filename)
  361. {
  362. struct stat st;
  363. char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  364. tor_mmap_t *handle;
  365. if (! res)
  366. return NULL;
  367. handle = tor_malloc_zero(sizeof(tor_mmap_t));
  368. handle->data = res;
  369. handle->size = st.st_size;
  370. return handle;
  371. }
  372. /** Unmap the file mapped with tor_mmap_file(), and return 0 for success
  373. * or -1 for failure.
  374. */
  375. int
  376. tor_munmap_file(tor_mmap_t *handle)
  377. {
  378. char *d = NULL;
  379. if (handle == NULL)
  380. return 0;
  381. d = (char*)handle->data;
  382. tor_free(d);
  383. memwipe(handle, 0, sizeof(tor_mmap_t));
  384. tor_free(handle);
  385. /* Can't fail in this mmap()/munmap()-free case */
  386. return 0;
  387. }
  388. #endif
  389. /** Replacement for snprintf. Differs from platform snprintf in two
  390. * ways: First, always NUL-terminates its output. Second, always
  391. * returns -1 if the result is truncated. (Note that this return
  392. * behavior does <i>not</i> conform to C99; it just happens to be
  393. * easier to emulate "return -1" with conformant implementations than
  394. * it is to emulate "return number that would be written" with
  395. * non-conformant implementations.) */
  396. int
  397. tor_snprintf(char *str, size_t size, const char *format, ...)
  398. {
  399. va_list ap;
  400. int r;
  401. va_start(ap,format);
  402. r = tor_vsnprintf(str,size,format,ap);
  403. va_end(ap);
  404. return r;
  405. }
  406. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  407. * snprintf.
  408. */
  409. int
  410. tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  411. {
  412. int r;
  413. if (size == 0)
  414. return -1; /* no place for the NUL */
  415. if (size > SIZE_T_CEILING)
  416. return -1;
  417. #ifdef _WIN32
  418. r = _vsnprintf(str, size, format, args);
  419. #else
  420. r = vsnprintf(str, size, format, args);
  421. #endif
  422. str[size-1] = '\0';
  423. if (r < 0 || r >= (ssize_t)size)
  424. return -1;
  425. return r;
  426. }
  427. /**
  428. * Portable asprintf implementation. Does a printf() into a newly malloc'd
  429. * string. Sets *<b>strp</b> to this string, and returns its length (not
  430. * including the terminating NUL character).
  431. *
  432. * You can treat this function as if its implementation were something like
  433. <pre>
  434. char buf[_INFINITY_];
  435. tor_snprintf(buf, sizeof(buf), fmt, args);
  436. *strp = tor_strdup(buf);
  437. return strlen(*strp):
  438. </pre>
  439. * Where _INFINITY_ is an imaginary constant so big that any string can fit
  440. * into it.
  441. */
  442. int
  443. tor_asprintf(char **strp, const char *fmt, ...)
  444. {
  445. int r;
  446. va_list args;
  447. va_start(args, fmt);
  448. r = tor_vasprintf(strp, fmt, args);
  449. va_end(args);
  450. if (!*strp || r < 0) {
  451. log_err(LD_BUG, "Internal error in asprintf");
  452. tor_assert(0);
  453. }
  454. return r;
  455. }
  456. /**
  457. * Portable vasprintf implementation. Does a printf() into a newly malloc'd
  458. * string. Differs from regular vasprintf in the same ways that
  459. * tor_asprintf() differs from regular asprintf.
  460. */
  461. int
  462. tor_vasprintf(char **strp, const char *fmt, va_list args)
  463. {
  464. /* use a temporary variable in case *strp is in args. */
  465. char *strp_tmp=NULL;
  466. #ifdef HAVE_VASPRINTF
  467. /* If the platform gives us one, use it. */
  468. int r = vasprintf(&strp_tmp, fmt, args);
  469. if (r < 0)
  470. *strp = NULL;
  471. else
  472. *strp = strp_tmp;
  473. return r;
  474. #elif defined(HAVE__VSCPRINTF)
  475. /* On Windows, _vsnprintf won't tell us the length of the string if it
  476. * overflows, so we need to use _vcsprintf to tell how much to allocate */
  477. int len, r;
  478. len = _vscprintf(fmt, args);
  479. if (len < 0) {
  480. *strp = NULL;
  481. return -1;
  482. }
  483. strp_tmp = tor_malloc(len + 1);
  484. r = _vsnprintf(strp_tmp, len+1, fmt, args);
  485. if (r != len) {
  486. tor_free(strp_tmp);
  487. *strp = NULL;
  488. return -1;
  489. }
  490. *strp = strp_tmp;
  491. return len;
  492. #else
  493. /* Everywhere else, we have a decent vsnprintf that tells us how many
  494. * characters we need. We give it a try on a short buffer first, since
  495. * it might be nice to avoid the second vsnprintf call.
  496. */
  497. char buf[128];
  498. int len, r;
  499. va_list tmp_args;
  500. va_copy(tmp_args, args);
  501. len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
  502. va_end(tmp_args);
  503. if (len < (int)sizeof(buf)) {
  504. *strp = tor_strdup(buf);
  505. return len;
  506. }
  507. strp_tmp = tor_malloc(len+1);
  508. r = vsnprintf(strp_tmp, len+1, fmt, args);
  509. if (r != len) {
  510. tor_free(strp_tmp);
  511. *strp = NULL;
  512. return -1;
  513. }
  514. *strp = strp_tmp;
  515. return len;
  516. #endif
  517. }
  518. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  519. * <b>needle</b>, return a pointer to the first occurrence of the needle
  520. * within the haystack, or NULL if there is no such occurrence.
  521. *
  522. * This function is <em>not</em> timing-safe.
  523. *
  524. * Requires that <b>nlen</b> be greater than zero.
  525. */
  526. const void *
  527. tor_memmem(const void *_haystack, size_t hlen,
  528. const void *_needle, size_t nlen)
  529. {
  530. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  531. tor_assert(nlen);
  532. return memmem(_haystack, hlen, _needle, nlen);
  533. #else
  534. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  535. * be. */
  536. const char *p, *last_possible_start;
  537. const char *haystack = (const char*)_haystack;
  538. const char *needle = (const char*)_needle;
  539. char first;
  540. tor_assert(nlen);
  541. if (nlen > hlen)
  542. return NULL;
  543. p = haystack;
  544. /* Last position at which the needle could start. */
  545. last_possible_start = haystack + hlen - nlen;
  546. first = *(const char*)needle;
  547. while ((p = memchr(p, first, last_possible_start + 1 - p))) {
  548. if (fast_memeq(p, needle, nlen))
  549. return p;
  550. if (++p > last_possible_start) {
  551. /* This comparison shouldn't be necessary, since if p was previously
  552. * equal to last_possible_start, the next memchr call would be
  553. * "memchr(p, first, 0)", which will return NULL. But it clarifies the
  554. * logic. */
  555. return NULL;
  556. }
  557. }
  558. return NULL;
  559. #endif
  560. }
  561. /**
  562. * Tables to implement ctypes-replacement TOR_IS*() functions. Each table
  563. * has 256 bits to look up whether a character is in some set or not. This
  564. * fails on non-ASCII platforms, but it is hard to find a platform whose
  565. * character set is not a superset of ASCII nowadays. */
  566. /**@{*/
  567. const uint32_t TOR_ISALPHA_TABLE[8] =
  568. { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
  569. const uint32_t TOR_ISALNUM_TABLE[8] =
  570. { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
  571. const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
  572. const uint32_t TOR_ISXDIGIT_TABLE[8] =
  573. { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
  574. const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
  575. const uint32_t TOR_ISPRINT_TABLE[8] =
  576. { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
  577. const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
  578. const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
  579. /** Upper-casing and lowercasing tables to map characters to upper/lowercase
  580. * equivalents. Used by tor_toupper() and tor_tolower(). */
  581. /**@{*/
  582. const char TOR_TOUPPER_TABLE[256] = {
  583. 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  584. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  585. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  586. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  587. 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  588. 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
  589. 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  590. 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
  591. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  592. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  593. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  594. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  595. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  596. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  597. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  598. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  599. };
  600. const char TOR_TOLOWER_TABLE[256] = {
  601. 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  602. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  603. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  604. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  605. 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  606. 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
  607. 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  608. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
  609. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  610. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  611. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  612. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  613. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  614. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  615. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  616. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  617. };
  618. /**@}*/
  619. /** Helper for tor_strtok_r_impl: Advances cp past all characters in
  620. * <b>sep</b>, and returns its new value. */
  621. static char *
  622. strtok_helper(char *cp, const char *sep)
  623. {
  624. if (sep[1]) {
  625. while (*cp && strchr(sep, *cp))
  626. ++cp;
  627. } else {
  628. while (*cp && *cp == *sep)
  629. ++cp;
  630. }
  631. return cp;
  632. }
  633. /** Implementation of strtok_r for platforms whose coders haven't figured out
  634. * how to write one. Hey guys! You can use this code here for free! */
  635. char *
  636. tor_strtok_r_impl(char *str, const char *sep, char **lasts)
  637. {
  638. char *cp, *start;
  639. tor_assert(*sep);
  640. if (str) {
  641. str = strtok_helper(str, sep);
  642. if (!*str)
  643. return NULL;
  644. start = cp = *lasts = str;
  645. } else if (!*lasts || !**lasts) {
  646. return NULL;
  647. } else {
  648. start = cp = *lasts;
  649. }
  650. if (sep[1]) {
  651. while (*cp && !strchr(sep, *cp))
  652. ++cp;
  653. } else {
  654. cp = strchr(cp, *sep);
  655. }
  656. if (!cp || !*cp) {
  657. *lasts = NULL;
  658. } else {
  659. *cp++ = '\0';
  660. *lasts = strtok_helper(cp, sep);
  661. }
  662. return start;
  663. }
  664. #ifdef _WIN32
  665. /** Take a filename and return a pointer to its final element. This
  666. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  667. * contains the full path to the file. This is bad, because it
  668. * confuses users to find the home directory of the person who
  669. * compiled the binary in their warning messages.
  670. */
  671. const char *
  672. tor_fix_source_file(const char *fname)
  673. {
  674. const char *cp1, *cp2, *r;
  675. cp1 = strrchr(fname, '/');
  676. cp2 = strrchr(fname, '\\');
  677. if (cp1 && cp2) {
  678. r = (cp1<cp2)?(cp2+1):(cp1+1);
  679. } else if (cp1) {
  680. r = cp1+1;
  681. } else if (cp2) {
  682. r = cp2+1;
  683. } else {
  684. r = fname;
  685. }
  686. return r;
  687. }
  688. #endif
  689. /**
  690. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  691. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  692. * unaligned memory access.
  693. */
  694. uint16_t
  695. get_uint16(const void *cp)
  696. {
  697. uint16_t v;
  698. memcpy(&v,cp,2);
  699. return v;
  700. }
  701. /**
  702. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  703. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  704. * unaligned memory access.
  705. */
  706. uint32_t
  707. get_uint32(const void *cp)
  708. {
  709. uint32_t v;
  710. memcpy(&v,cp,4);
  711. return v;
  712. }
  713. /**
  714. * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
  715. * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
  716. * unaligned memory access.
  717. */
  718. uint64_t
  719. get_uint64(const void *cp)
  720. {
  721. uint64_t v;
  722. memcpy(&v,cp,8);
  723. return v;
  724. }
  725. /**
  726. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  727. * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  728. * unaligned memory access. */
  729. void
  730. set_uint16(void *cp, uint16_t v)
  731. {
  732. memcpy(cp,&v,2);
  733. }
  734. /**
  735. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  736. * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  737. * unaligned memory access. */
  738. void
  739. set_uint32(void *cp, uint32_t v)
  740. {
  741. memcpy(cp,&v,4);
  742. }
  743. /**
  744. * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  745. * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  746. * unaligned memory access. */
  747. void
  748. set_uint64(void *cp, uint64_t v)
  749. {
  750. memcpy(cp,&v,8);
  751. }
  752. /**
  753. * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
  754. * the same as rename(2). On windows, this removes <b>to</b> first if
  755. * it already exists.
  756. * Returns 0 on success. Returns -1 and sets errno on failure.
  757. */
  758. int
  759. replace_file(const char *from, const char *to)
  760. {
  761. #ifndef _WIN32
  762. return tor_rename(from, to);
  763. #else
  764. switch (file_status(to))
  765. {
  766. case FN_NOENT:
  767. break;
  768. case FN_FILE:
  769. if (unlink(to)) return -1;
  770. break;
  771. case FN_ERROR:
  772. return -1;
  773. case FN_DIR:
  774. errno = EISDIR;
  775. return -1;
  776. }
  777. return tor_rename(from,to);
  778. #endif
  779. }
  780. /** Change <b>fname</b>'s modification time to now. */
  781. int
  782. touch_file(const char *fname)
  783. {
  784. if (utime(fname, NULL)!=0)
  785. return -1;
  786. return 0;
  787. }
  788. /** Represents a lockfile on which we hold the lock. */
  789. struct tor_lockfile_t {
  790. /** Name of the file */
  791. char *filename;
  792. /** File descriptor used to hold the file open */
  793. int fd;
  794. };
  795. /** Try to get a lock on the lockfile <b>filename</b>, creating it as
  796. * necessary. If someone else has the lock and <b>blocking</b> is true,
  797. * wait until the lock is available. Otherwise return immediately whether
  798. * we succeeded or not.
  799. *
  800. * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
  801. * otherwise.
  802. *
  803. * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
  804. *
  805. * (Implementation note: because we need to fall back to fcntl on some
  806. * platforms, these locks are per-process, not per-thread. If you want
  807. * to do in-process locking, use tor_mutex_t like a normal person.
  808. * On Windows, when <b>blocking</b> is true, the maximum time that
  809. * is actually waited is 10 seconds, after which NULL is returned
  810. * and <b>locked_out</b> is set to 1.)
  811. */
  812. tor_lockfile_t *
  813. tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
  814. {
  815. tor_lockfile_t *result;
  816. int fd;
  817. *locked_out = 0;
  818. log_info(LD_FS, "Locking \"%s\"", filename);
  819. fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  820. if (fd < 0) {
  821. log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
  822. strerror(errno));
  823. return NULL;
  824. }
  825. #ifdef _WIN32
  826. _lseek(fd, 0, SEEK_SET);
  827. if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
  828. if (errno != EACCES && errno != EDEADLOCK)
  829. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  830. else
  831. *locked_out = 1;
  832. close(fd);
  833. return NULL;
  834. }
  835. #elif defined(HAVE_FLOCK)
  836. if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
  837. if (errno != EWOULDBLOCK)
  838. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  839. else
  840. *locked_out = 1;
  841. close(fd);
  842. return NULL;
  843. }
  844. #else
  845. {
  846. struct flock lock;
  847. memset(&lock, 0, sizeof(lock));
  848. lock.l_type = F_WRLCK;
  849. lock.l_whence = SEEK_SET;
  850. if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
  851. if (errno != EACCES && errno != EAGAIN)
  852. log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
  853. else
  854. *locked_out = 1;
  855. close(fd);
  856. return NULL;
  857. }
  858. }
  859. #endif
  860. result = tor_malloc(sizeof(tor_lockfile_t));
  861. result->filename = tor_strdup(filename);
  862. result->fd = fd;
  863. return result;
  864. }
  865. /** Release the lock held as <b>lockfile</b>. */
  866. void
  867. tor_lockfile_unlock(tor_lockfile_t *lockfile)
  868. {
  869. tor_assert(lockfile);
  870. log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
  871. #ifdef _WIN32
  872. _lseek(lockfile->fd, 0, SEEK_SET);
  873. if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
  874. log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
  875. strerror(errno));
  876. }
  877. #elif defined(HAVE_FLOCK)
  878. if (flock(lockfile->fd, LOCK_UN) < 0) {
  879. log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
  880. strerror(errno));
  881. }
  882. #else
  883. /* Closing the lockfile is sufficient. */
  884. #endif
  885. close(lockfile->fd);
  886. lockfile->fd = -1;
  887. tor_free(lockfile->filename);
  888. tor_free(lockfile);
  889. }
  890. /** @{ */
  891. /** Some old versions of Unix didn't define constants for these values,
  892. * and instead expect you to say 0, 1, or 2. */
  893. #ifndef SEEK_SET
  894. #define SEEK_SET 0
  895. #endif
  896. #ifndef SEEK_CUR
  897. #define SEEK_CUR 1
  898. #endif
  899. #ifndef SEEK_END
  900. #define SEEK_END 2
  901. #endif
  902. /** @} */
  903. /** Return the position of <b>fd</b> with respect to the start of the file. */
  904. off_t
  905. tor_fd_getpos(int fd)
  906. {
  907. #ifdef _WIN32
  908. return (off_t) _lseek(fd, 0, SEEK_CUR);
  909. #else
  910. return (off_t) lseek(fd, 0, SEEK_CUR);
  911. #endif
  912. }
  913. /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success.
  914. * If the file is a pipe, do nothing and succeed.
  915. **/
  916. int
  917. tor_fd_seekend(int fd)
  918. {
  919. #ifdef _WIN32
  920. return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  921. #else
  922. off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  923. #ifdef ESPIPE
  924. /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
  925. * no need to worry. */
  926. if (rc < 0 && errno == ESPIPE)
  927. rc = 0;
  928. #endif
  929. return (rc < 0) ? -1 : 0;
  930. #endif
  931. }
  932. /** Move <b>fd</b> to position <b>pos</b> in the file. Return -1 on error, 0
  933. * on success. */
  934. int
  935. tor_fd_setpos(int fd, off_t pos)
  936. {
  937. #ifdef _WIN32
  938. return _lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
  939. #else
  940. return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
  941. #endif
  942. }
  943. /** Replacement for ftruncate(fd, 0): move to the front of the file and remove
  944. * all the rest of the file. Return -1 on error, 0 on success. */
  945. int
  946. tor_ftruncate(int fd)
  947. {
  948. /* Rumor has it that some versions of ftruncate do not move the file pointer.
  949. */
  950. if (tor_fd_setpos(fd, 0) < 0)
  951. return -1;
  952. #ifdef _WIN32
  953. return _chsize(fd, 0);
  954. #else
  955. return ftruncate(fd, 0);
  956. #endif
  957. }
  958. #undef DEBUG_SOCKET_COUNTING
  959. #ifdef DEBUG_SOCKET_COUNTING
  960. /** A bitarray of all fds that should be passed to tor_socket_close(). Only
  961. * used if DEBUG_SOCKET_COUNTING is defined. */
  962. static bitarray_t *open_sockets = NULL;
  963. /** The size of <b>open_sockets</b>, in bits. */
  964. static int max_socket = -1;
  965. #endif
  966. /** Count of number of sockets currently open. (Undercounts sockets opened by
  967. * eventdns and libevent.) */
  968. static int n_sockets_open = 0;
  969. /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
  970. static tor_mutex_t *socket_accounting_mutex = NULL;
  971. /** Helper: acquire the socket accounting lock. */
  972. static INLINE void
  973. socket_accounting_lock(void)
  974. {
  975. if (PREDICT_UNLIKELY(!socket_accounting_mutex))
  976. socket_accounting_mutex = tor_mutex_new();
  977. tor_mutex_acquire(socket_accounting_mutex);
  978. }
  979. /** Helper: release the socket accounting lock. */
  980. static INLINE void
  981. socket_accounting_unlock(void)
  982. {
  983. tor_mutex_release(socket_accounting_mutex);
  984. }
  985. /** As close(), but guaranteed to work for sockets across platforms (including
  986. * Windows, where close()ing a socket doesn't work. Returns 0 on success and
  987. * the socket error code on failure. */
  988. int
  989. tor_close_socket_simple(tor_socket_t s)
  990. {
  991. int r = 0;
  992. /* On Windows, you have to call close() on fds returned by open(),
  993. * and closesocket() on fds returned by socket(). On Unix, everything
  994. * gets close()'d. We abstract this difference by always using
  995. * tor_close_socket to close sockets, and always using close() on
  996. * files.
  997. */
  998. #if defined(_WIN32)
  999. r = closesocket(s);
  1000. #else
  1001. r = close(s);
  1002. #endif
  1003. if (r != 0) {
  1004. int err = tor_socket_errno(-1);
  1005. log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
  1006. return err;
  1007. }
  1008. return r;
  1009. }
  1010. /** As tor_close_socket_simple(), but keeps track of the number
  1011. * of open sockets. Returns 0 on success, -1 on failure. */
  1012. int
  1013. tor_close_socket(tor_socket_t s)
  1014. {
  1015. int r = tor_close_socket_simple(s);
  1016. socket_accounting_lock();
  1017. #ifdef DEBUG_SOCKET_COUNTING
  1018. if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
  1019. log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
  1020. "socket(), or that was already closed or something.", s);
  1021. } else {
  1022. tor_assert(open_sockets && s <= max_socket);
  1023. bitarray_clear(open_sockets, s);
  1024. }
  1025. #endif
  1026. if (r == 0) {
  1027. --n_sockets_open;
  1028. } else {
  1029. #ifdef _WIN32
  1030. if (r != WSAENOTSOCK)
  1031. --n_sockets_open;
  1032. #else
  1033. if (r != EBADF)
  1034. --n_sockets_open;
  1035. #endif
  1036. r = -1;
  1037. }
  1038. if (n_sockets_open < 0)
  1039. log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
  1040. "bug report.", n_sockets_open);
  1041. socket_accounting_unlock();
  1042. return r;
  1043. }
  1044. /** @{ */
  1045. #ifdef DEBUG_SOCKET_COUNTING
  1046. /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
  1047. * now an open socket. */
  1048. static INLINE void
  1049. mark_socket_open(tor_socket_t s)
  1050. {
  1051. /* XXXX This bitarray business will NOT work on windows: sockets aren't
  1052. small ints there. */
  1053. if (s > max_socket) {
  1054. if (max_socket == -1) {
  1055. open_sockets = bitarray_init_zero(s+128);
  1056. max_socket = s+128;
  1057. } else {
  1058. open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
  1059. max_socket = s+128;
  1060. }
  1061. }
  1062. if (bitarray_is_set(open_sockets, s)) {
  1063. log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
  1064. "gave it to me!", s);
  1065. }
  1066. bitarray_set(open_sockets, s);
  1067. }
  1068. #else
  1069. #define mark_socket_open(s) STMT_NIL
  1070. #endif
  1071. /** @} */
  1072. /** As socket(), but counts the number of open sockets. */
  1073. tor_socket_t
  1074. tor_open_socket(int domain, int type, int protocol)
  1075. {
  1076. return tor_open_socket_with_extensions(domain, type, protocol, 1, 0);
  1077. }
  1078. /** As socket(), but creates a nonblocking socket and
  1079. * counts the number of open sockets. */
  1080. tor_socket_t
  1081. tor_open_socket_nonblocking(int domain, int type, int protocol)
  1082. {
  1083. return tor_open_socket_with_extensions(domain, type, protocol, 1, 1);
  1084. }
  1085. /** As socket(), but counts the number of open sockets and handles
  1086. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  1087. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  1088. * if the corresponding extension should be used.*/
  1089. tor_socket_t
  1090. tor_open_socket_with_extensions(int domain, int type, int protocol,
  1091. int cloexec, int nonblock)
  1092. {
  1093. tor_socket_t s;
  1094. #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
  1095. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  1096. (nonblock ? SOCK_NONBLOCK : 0);
  1097. s = socket(domain, type|ext_flags, protocol);
  1098. if (SOCKET_OK(s))
  1099. goto socket_ok;
  1100. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  1101. * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
  1102. * support, we are running on one without. */
  1103. if (errno != EINVAL)
  1104. return s;
  1105. #endif /* SOCK_CLOEXEC && SOCK_NONBLOCK */
  1106. s = socket(domain, type, protocol);
  1107. if (! SOCKET_OK(s))
  1108. return s;
  1109. #if defined(FD_CLOEXEC)
  1110. if (cloexec) {
  1111. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  1112. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  1113. tor_close_socket_simple(s);
  1114. return TOR_INVALID_SOCKET;
  1115. }
  1116. }
  1117. #else
  1118. (void)cloexec;
  1119. #endif
  1120. if (nonblock) {
  1121. if (set_socket_nonblocking(s) == -1) {
  1122. tor_close_socket_simple(s);
  1123. return TOR_INVALID_SOCKET;
  1124. }
  1125. }
  1126. goto socket_ok; /* So that socket_ok will not be unused. */
  1127. socket_ok:
  1128. socket_accounting_lock();
  1129. ++n_sockets_open;
  1130. mark_socket_open(s);
  1131. socket_accounting_unlock();
  1132. return s;
  1133. }
  1134. /** As accept(), but counts the number of open sockets. */
  1135. tor_socket_t
  1136. tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
  1137. {
  1138. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0);
  1139. }
  1140. /** As accept(), but returns a nonblocking socket and
  1141. * counts the number of open sockets. */
  1142. tor_socket_t
  1143. tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr,
  1144. socklen_t *len)
  1145. {
  1146. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1);
  1147. }
  1148. /** As accept(), but counts the number of open sockets and handles
  1149. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  1150. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  1151. * if the corresponding extension should be used.*/
  1152. tor_socket_t
  1153. tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr,
  1154. socklen_t *len, int cloexec, int nonblock)
  1155. {
  1156. tor_socket_t s;
  1157. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
  1158. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  1159. (nonblock ? SOCK_NONBLOCK : 0);
  1160. s = accept4(sockfd, addr, len, ext_flags);
  1161. if (SOCKET_OK(s))
  1162. goto socket_ok;
  1163. /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
  1164. * even though we were built on a system with accept4 support, we
  1165. * are running on one without. Also, check for EINVAL, which indicates that
  1166. * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
  1167. if (errno != EINVAL && errno != ENOSYS)
  1168. return s;
  1169. #endif
  1170. s = accept(sockfd, addr, len);
  1171. if (!SOCKET_OK(s))
  1172. return s;
  1173. #if defined(FD_CLOEXEC)
  1174. if (cloexec) {
  1175. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  1176. log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno));
  1177. tor_close_socket_simple(s);
  1178. return TOR_INVALID_SOCKET;
  1179. }
  1180. }
  1181. #else
  1182. (void)cloexec;
  1183. #endif
  1184. if (nonblock) {
  1185. if (set_socket_nonblocking(s) == -1) {
  1186. tor_close_socket_simple(s);
  1187. return TOR_INVALID_SOCKET;
  1188. }
  1189. }
  1190. goto socket_ok; /* So that socket_ok will not be unused. */
  1191. socket_ok:
  1192. socket_accounting_lock();
  1193. ++n_sockets_open;
  1194. mark_socket_open(s);
  1195. socket_accounting_unlock();
  1196. return s;
  1197. }
  1198. /** Return the number of sockets we currently have opened. */
  1199. int
  1200. get_n_open_sockets(void)
  1201. {
  1202. int n;
  1203. socket_accounting_lock();
  1204. n = n_sockets_open;
  1205. socket_accounting_unlock();
  1206. return n;
  1207. }
  1208. /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
  1209. * on failure.
  1210. */
  1211. int
  1212. set_socket_nonblocking(tor_socket_t socket)
  1213. {
  1214. #if defined(_WIN32)
  1215. unsigned long nonblocking = 1;
  1216. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  1217. #else
  1218. int flags;
  1219. flags = fcntl(socket, F_GETFL, 0);
  1220. if (flags == -1) {
  1221. log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno));
  1222. return -1;
  1223. }
  1224. flags |= O_NONBLOCK;
  1225. if (fcntl(socket, F_SETFL, flags) == -1) {
  1226. log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno));
  1227. return -1;
  1228. }
  1229. #endif
  1230. return 0;
  1231. }
  1232. /**
  1233. * Allocate a pair of connected sockets. (Like socketpair(family,
  1234. * type,protocol,fd), but works on systems that don't have
  1235. * socketpair.)
  1236. *
  1237. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  1238. *
  1239. * Note that on systems without socketpair, this call will fail if
  1240. * localhost is inaccessible (for example, if the networking
  1241. * stack is down). And even if it succeeds, the socket pair will not
  1242. * be able to read while localhost is down later (the socket pair may
  1243. * even close, depending on OS-specific timeouts).
  1244. *
  1245. * Returns 0 on success and -errno on failure; do not rely on the value
  1246. * of errno or WSAGetLastError().
  1247. **/
  1248. /* It would be nicer just to set errno, but that won't work for windows. */
  1249. int
  1250. tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  1251. {
  1252. //don't use win32 socketpairs (they are always bad)
  1253. #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  1254. int r;
  1255. #ifdef SOCK_CLOEXEC
  1256. r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd);
  1257. if (r == 0)
  1258. goto sockets_ok;
  1259. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  1260. * even though we were built on a system with SOCK_CLOEXEC support, we
  1261. * are running on one without. */
  1262. if (errno != EINVAL)
  1263. return -errno;
  1264. #endif
  1265. r = socketpair(family, type, protocol, fd);
  1266. if (r < 0)
  1267. return -errno;
  1268. #if defined(FD_CLOEXEC)
  1269. if (SOCKET_OK(fd[0])) {
  1270. r = fcntl(fd[0], F_SETFD, FD_CLOEXEC);
  1271. if (r == -1) {
  1272. close(fd[0]);
  1273. close(fd[1]);
  1274. return -errno;
  1275. }
  1276. }
  1277. if (SOCKET_OK(fd[1])) {
  1278. r = fcntl(fd[1], F_SETFD, FD_CLOEXEC);
  1279. if (r == -1) {
  1280. close(fd[0]);
  1281. close(fd[1]);
  1282. return -errno;
  1283. }
  1284. }
  1285. #endif
  1286. goto sockets_ok; /* So that sockets_ok will not be unused. */
  1287. sockets_ok:
  1288. socket_accounting_lock();
  1289. if (SOCKET_OK(fd[0])) {
  1290. ++n_sockets_open;
  1291. mark_socket_open(fd[0]);
  1292. }
  1293. if (SOCKET_OK(fd[1])) {
  1294. ++n_sockets_open;
  1295. mark_socket_open(fd[1]);
  1296. }
  1297. socket_accounting_unlock();
  1298. return 0;
  1299. #else
  1300. return tor_ersatz_socketpair(family, type, protocol, fd);
  1301. #endif
  1302. }
  1303. #ifdef NEED_ERSATZ_SOCKETPAIR
  1304. /**
  1305. * Helper used to implement socketpair on systems that lack it, by
  1306. * making a direct connection to localhost.
  1307. */
  1308. STATIC int
  1309. tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  1310. {
  1311. /* This socketpair does not work when localhost is down. So
  1312. * it's really not the same thing at all. But it's close enough
  1313. * for now, and really, when localhost is down sometimes, we
  1314. * have other problems too.
  1315. */
  1316. tor_socket_t listener = TOR_INVALID_SOCKET;
  1317. tor_socket_t connector = TOR_INVALID_SOCKET;
  1318. tor_socket_t acceptor = TOR_INVALID_SOCKET;
  1319. struct sockaddr_in listen_addr;
  1320. struct sockaddr_in connect_addr;
  1321. socklen_t size;
  1322. int saved_errno = -1;
  1323. memset(&connect_addr, 0, sizeof(connect_addr));
  1324. memset(&listen_addr, 0, sizeof(listen_addr));
  1325. if (protocol
  1326. #ifdef AF_UNIX
  1327. || family != AF_UNIX
  1328. #endif
  1329. ) {
  1330. #ifdef _WIN32
  1331. return -WSAEAFNOSUPPORT;
  1332. #else
  1333. return -EAFNOSUPPORT;
  1334. #endif
  1335. }
  1336. if (!fd) {
  1337. return -EINVAL;
  1338. }
  1339. listener = tor_open_socket(AF_INET, type, 0);
  1340. if (!SOCKET_OK(listener))
  1341. return -tor_socket_errno(-1);
  1342. memset(&listen_addr, 0, sizeof(listen_addr));
  1343. listen_addr.sin_family = AF_INET;
  1344. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1345. listen_addr.sin_port = 0; /* kernel chooses port. */
  1346. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  1347. == -1)
  1348. goto tidy_up_and_fail;
  1349. if (listen(listener, 1) == -1)
  1350. goto tidy_up_and_fail;
  1351. connector = tor_open_socket(AF_INET, type, 0);
  1352. if (!SOCKET_OK(connector))
  1353. goto tidy_up_and_fail;
  1354. /* We want to find out the port number to connect to. */
  1355. size = sizeof(connect_addr);
  1356. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  1357. goto tidy_up_and_fail;
  1358. if (size != sizeof (connect_addr))
  1359. goto abort_tidy_up_and_fail;
  1360. if (connect(connector, (struct sockaddr *) &connect_addr,
  1361. sizeof(connect_addr)) == -1)
  1362. goto tidy_up_and_fail;
  1363. size = sizeof(listen_addr);
  1364. acceptor = tor_accept_socket(listener,
  1365. (struct sockaddr *) &listen_addr, &size);
  1366. if (!SOCKET_OK(acceptor))
  1367. goto tidy_up_and_fail;
  1368. if (size != sizeof(listen_addr))
  1369. goto abort_tidy_up_and_fail;
  1370. /* Now check we are talking to ourself by matching port and host on the
  1371. two sockets. */
  1372. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  1373. goto tidy_up_and_fail;
  1374. if (size != sizeof (connect_addr)
  1375. || listen_addr.sin_family != connect_addr.sin_family
  1376. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  1377. || listen_addr.sin_port != connect_addr.sin_port) {
  1378. goto abort_tidy_up_and_fail;
  1379. }
  1380. tor_close_socket(listener);
  1381. fd[0] = connector;
  1382. fd[1] = acceptor;
  1383. return 0;
  1384. abort_tidy_up_and_fail:
  1385. #ifdef _WIN32
  1386. saved_errno = WSAECONNABORTED;
  1387. #else
  1388. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  1389. #endif
  1390. tidy_up_and_fail:
  1391. if (saved_errno < 0)
  1392. saved_errno = errno;
  1393. if (SOCKET_OK(listener))
  1394. tor_close_socket(listener);
  1395. if (SOCKET_OK(connector))
  1396. tor_close_socket(connector);
  1397. if (SOCKET_OK(acceptor))
  1398. tor_close_socket(acceptor);
  1399. return -saved_errno;
  1400. }
  1401. #endif
  1402. /** Number of extra file descriptors to keep in reserve beyond those that we
  1403. * tell Tor it's allowed to use. */
  1404. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
  1405. /** Learn the maximum allowed number of file descriptors, and tell the system
  1406. * we want to use up to that number. (Some systems have a low soft limit, and
  1407. * let us set it higher.)
  1408. *
  1409. * We compute this by finding the largest number that we can use.
  1410. * If we can't find a number greater than or equal to <b>limit</b>,
  1411. * then we fail: return -1.
  1412. *
  1413. * If <b>limit</b> is 0, then do not adjust the current maximum.
  1414. *
  1415. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
  1416. int
  1417. set_max_file_descriptors(rlim_t limit, int *max_out)
  1418. {
  1419. /* Define some maximum connections values for systems where we cannot
  1420. * automatically determine a limit. Re Cygwin, see
  1421. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  1422. * For an iPhone, 9999 should work. For Windows and all other unknown
  1423. * systems we use 15000 as the default. */
  1424. #ifndef HAVE_GETRLIMIT
  1425. #if defined(CYGWIN) || defined(__CYGWIN__)
  1426. const char *platform = "Cygwin";
  1427. const unsigned long MAX_CONNECTIONS = 3200;
  1428. #elif defined(_WIN32)
  1429. const char *platform = "Windows";
  1430. const unsigned long MAX_CONNECTIONS = 15000;
  1431. #else
  1432. const char *platform = "unknown platforms with no getrlimit()";
  1433. const unsigned long MAX_CONNECTIONS = 15000;
  1434. #endif
  1435. log_fn(LOG_INFO, LD_NET,
  1436. "This platform is missing getrlimit(). Proceeding.");
  1437. if (limit > MAX_CONNECTIONS) {
  1438. log_warn(LD_CONFIG,
  1439. "We do not support more than %lu file descriptors "
  1440. "on %s. Tried to raise to %lu.",
  1441. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  1442. return -1;
  1443. }
  1444. limit = MAX_CONNECTIONS;
  1445. #else /* HAVE_GETRLIMIT */
  1446. struct rlimit rlim;
  1447. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1448. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  1449. strerror(errno));
  1450. return -1;
  1451. }
  1452. if (limit == 0) {
  1453. /* If limit == 0, return the maximum value without setting it. */
  1454. limit = rlim.rlim_max;
  1455. if (limit > INT_MAX)
  1456. limit = INT_MAX;
  1457. *max_out = (int)limit - ULIMIT_BUFFER;
  1458. return 0;
  1459. }
  1460. if (rlim.rlim_max < limit) {
  1461. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  1462. "limited to %lu. Please change your ulimit -n.",
  1463. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  1464. return -1;
  1465. }
  1466. if (rlim.rlim_max > rlim.rlim_cur) {
  1467. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  1468. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  1469. }
  1470. rlim.rlim_cur = rlim.rlim_max;
  1471. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1472. int bad = 1;
  1473. #ifdef OPEN_MAX
  1474. if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
  1475. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  1476. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  1477. rlim.rlim_cur = OPEN_MAX;
  1478. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  1479. if (rlim.rlim_cur < (rlim_t)limit) {
  1480. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  1481. "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
  1482. (unsigned long)OPEN_MAX, (unsigned long)limit);
  1483. } else {
  1484. log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
  1485. "Apparently, %lu was too high and rlimit lied to us.",
  1486. (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
  1487. }
  1488. bad = 0;
  1489. }
  1490. }
  1491. #endif /* OPEN_MAX */
  1492. if (bad) {
  1493. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  1494. strerror(errno));
  1495. return -1;
  1496. }
  1497. }
  1498. /* leave some overhead for logs, etc, */
  1499. limit = rlim.rlim_cur;
  1500. #endif /* HAVE_GETRLIMIT */
  1501. if (limit < ULIMIT_BUFFER) {
  1502. log_warn(LD_CONFIG,
  1503. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  1504. return -1;
  1505. }
  1506. if (limit > INT_MAX)
  1507. limit = INT_MAX;
  1508. tor_assert(max_out);
  1509. *max_out = (int)limit - ULIMIT_BUFFER;
  1510. return 0;
  1511. }
  1512. #ifndef _WIN32
  1513. /** Log details of current user and group credentials. Return 0 on
  1514. * success. Logs and return -1 on failure.
  1515. */
  1516. static int
  1517. log_credential_status(void)
  1518. {
  1519. /** Log level to use when describing non-error UID/GID status. */
  1520. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  1521. /* Real, effective and saved UIDs */
  1522. uid_t ruid, euid, suid;
  1523. /* Read, effective and saved GIDs */
  1524. gid_t rgid, egid, sgid;
  1525. /* Supplementary groups */
  1526. gid_t *sup_gids = NULL;
  1527. int sup_gids_size;
  1528. /* Number of supplementary groups */
  1529. int ngids;
  1530. /* log UIDs */
  1531. #ifdef HAVE_GETRESUID
  1532. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  1533. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  1534. return -1;
  1535. } else {
  1536. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1537. "UID is %u (real), %u (effective), %u (saved)",
  1538. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  1539. }
  1540. #else
  1541. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  1542. ruid = getuid();
  1543. euid = geteuid();
  1544. (void)suid;
  1545. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1546. "UID is %u (real), %u (effective), unknown (saved)",
  1547. (unsigned)ruid, (unsigned)euid);
  1548. #endif
  1549. /* log GIDs */
  1550. #ifdef HAVE_GETRESGID
  1551. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  1552. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  1553. return -1;
  1554. } else {
  1555. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1556. "GID is %u (real), %u (effective), %u (saved)",
  1557. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  1558. }
  1559. #else
  1560. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  1561. rgid = getgid();
  1562. egid = getegid();
  1563. (void)sgid;
  1564. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1565. "GID is %u (real), %u (effective), unknown (saved)",
  1566. (unsigned)rgid, (unsigned)egid);
  1567. #endif
  1568. /* log supplementary groups */
  1569. sup_gids_size = 64;
  1570. sup_gids = tor_calloc(sizeof(gid_t), 64);
  1571. while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
  1572. errno == EINVAL &&
  1573. sup_gids_size < NGROUPS_MAX) {
  1574. sup_gids_size *= 2;
  1575. sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
  1576. }
  1577. if (ngids < 0) {
  1578. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  1579. strerror(errno));
  1580. tor_free(sup_gids);
  1581. return -1;
  1582. } else {
  1583. int i, retval = 0;
  1584. char *s = NULL;
  1585. smartlist_t *elts = smartlist_new();
  1586. for (i = 0; i<ngids; i++) {
  1587. smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
  1588. }
  1589. s = smartlist_join_strings(elts, " ", 0, NULL);
  1590. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  1591. tor_free(s);
  1592. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1593. smartlist_free(elts);
  1594. tor_free(sup_gids);
  1595. return retval;
  1596. }
  1597. return 0;
  1598. }
  1599. #endif
  1600. #ifndef _WIN32
  1601. /** Cached struct from the last getpwname() call we did successfully. */
  1602. static struct passwd *passwd_cached = NULL;
  1603. /** Helper: copy a struct passwd object.
  1604. *
  1605. * We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
  1606. * any others, and I don't want to run into incompatibilities.
  1607. */
  1608. static struct passwd *
  1609. tor_passwd_dup(const struct passwd *pw)
  1610. {
  1611. struct passwd *new_pw = tor_malloc_zero(sizeof(struct passwd));
  1612. if (pw->pw_name)
  1613. new_pw->pw_name = tor_strdup(pw->pw_name);
  1614. if (pw->pw_dir)
  1615. new_pw->pw_dir = tor_strdup(pw->pw_dir);
  1616. new_pw->pw_uid = pw->pw_uid;
  1617. new_pw->pw_gid = pw->pw_gid;
  1618. return new_pw;
  1619. }
  1620. /** Helper: free one of our cached 'struct passwd' values. */
  1621. static void
  1622. tor_passwd_free(struct passwd *pw)
  1623. {
  1624. if (!pw)
  1625. return;
  1626. tor_free(pw->pw_name);
  1627. tor_free(pw->pw_dir);
  1628. tor_free(pw);
  1629. }
  1630. /** Wrapper around getpwnam() that caches result. Used so that we don't need
  1631. * to give the sandbox access to /etc/passwd.
  1632. *
  1633. * The following fields alone will definitely be copied in the output: pw_uid,
  1634. * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
  1635. *
  1636. * When called with a NULL argument, this function clears storage associated
  1637. * with static variables it uses.
  1638. **/
  1639. const struct passwd *
  1640. tor_getpwnam(const char *username)
  1641. {
  1642. struct passwd *pw;
  1643. if (username == NULL) {
  1644. tor_passwd_free(passwd_cached);
  1645. passwd_cached = NULL;
  1646. return NULL;
  1647. }
  1648. if ((pw = getpwnam(username))) {
  1649. tor_passwd_free(passwd_cached);
  1650. passwd_cached = tor_passwd_dup(pw);
  1651. log_notice(LD_GENERAL, "Caching new entry %s for %s",
  1652. passwd_cached->pw_name, username);
  1653. return pw;
  1654. }
  1655. /* Lookup failed */
  1656. if (! passwd_cached || ! passwd_cached->pw_name)
  1657. return NULL;
  1658. if (! strcmp(username, passwd_cached->pw_name))
  1659. return passwd_cached;
  1660. return NULL;
  1661. }
  1662. /** Wrapper around getpwnam() that can use cached result from
  1663. * tor_getpwnam(). Used so that we don't need to give the sandbox access to
  1664. * /etc/passwd.
  1665. *
  1666. * The following fields alone will definitely be copied in the output: pw_uid,
  1667. * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
  1668. */
  1669. const struct passwd *
  1670. tor_getpwuid(uid_t uid)
  1671. {
  1672. struct passwd *pw;
  1673. if ((pw = getpwuid(uid))) {
  1674. return pw;
  1675. }
  1676. /* Lookup failed */
  1677. if (! passwd_cached)
  1678. return NULL;
  1679. if (uid == passwd_cached->pw_uid)
  1680. return passwd_cached;
  1681. return NULL;
  1682. }
  1683. #endif
  1684. /** Call setuid and setgid to run as <b>user</b> and switch to their
  1685. * primary group. Return 0 on success. On failure, log and return -1.
  1686. */
  1687. int
  1688. switch_id(const char *user)
  1689. {
  1690. #ifndef _WIN32
  1691. const struct passwd *pw = NULL;
  1692. uid_t old_uid;
  1693. gid_t old_gid;
  1694. static int have_already_switched_id = 0;
  1695. tor_assert(user);
  1696. if (have_already_switched_id)
  1697. return 0;
  1698. /* Log the initial credential state */
  1699. if (log_credential_status())
  1700. return -1;
  1701. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  1702. /* Get old UID/GID to check if we changed correctly */
  1703. old_uid = getuid();
  1704. old_gid = getgid();
  1705. /* Lookup the user and group information, if we have a problem, bail out. */
  1706. pw = tor_getpwnam(user);
  1707. if (pw == NULL) {
  1708. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  1709. return -1;
  1710. }
  1711. /* Properly switch egid,gid,euid,uid here or bail out */
  1712. if (setgroups(1, &pw->pw_gid)) {
  1713. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  1714. (int)pw->pw_gid, strerror(errno));
  1715. if (old_uid == pw->pw_uid) {
  1716. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  1717. "the \"User\" option if you are already running as the user "
  1718. "you want to be. (If you did not set the User option in your "
  1719. "torrc, check whether it was specified on the command line "
  1720. "by a startup script.)", user);
  1721. } else {
  1722. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  1723. " as root.");
  1724. }
  1725. return -1;
  1726. }
  1727. if (setegid(pw->pw_gid)) {
  1728. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  1729. (int)pw->pw_gid, strerror(errno));
  1730. return -1;
  1731. }
  1732. if (setgid(pw->pw_gid)) {
  1733. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  1734. (int)pw->pw_gid, strerror(errno));
  1735. return -1;
  1736. }
  1737. if (setuid(pw->pw_uid)) {
  1738. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  1739. user, (int)pw->pw_uid, strerror(errno));
  1740. return -1;
  1741. }
  1742. if (seteuid(pw->pw_uid)) {
  1743. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  1744. user, (int)pw->pw_uid, strerror(errno));
  1745. return -1;
  1746. }
  1747. /* This is how OpenBSD rolls:
  1748. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  1749. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  1750. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  1751. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  1752. strerror(errno));
  1753. return -1;
  1754. }
  1755. */
  1756. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  1757. * we're here. */
  1758. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  1759. /* If we tried to drop privilege to a group/user other than root, attempt to
  1760. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  1761. /* Only check for privilege dropping if we were asked to be non-root */
  1762. if (pw->pw_uid) {
  1763. /* Try changing GID/EGID */
  1764. if (pw->pw_gid != old_gid &&
  1765. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  1766. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  1767. "switching GID: this means that the setgid code didn't work.");
  1768. return -1;
  1769. }
  1770. /* Try changing UID/EUID */
  1771. if (pw->pw_uid != old_uid &&
  1772. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  1773. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  1774. "switching UID: this means that the setuid code didn't work.");
  1775. return -1;
  1776. }
  1777. }
  1778. #endif
  1779. /* Check what really happened */
  1780. if (log_credential_status()) {
  1781. return -1;
  1782. }
  1783. have_already_switched_id = 1; /* mark success so we never try again */
  1784. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
  1785. #ifdef PR_SET_DUMPABLE
  1786. if (pw->pw_uid) {
  1787. /* Re-enable core dumps if we're not running as root. */
  1788. log_info(LD_CONFIG, "Re-enabling coredumps");
  1789. if (prctl(PR_SET_DUMPABLE, 1)) {
  1790. log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
  1791. }
  1792. }
  1793. #endif
  1794. #endif
  1795. return 0;
  1796. #else
  1797. (void)user;
  1798. log_warn(LD_CONFIG,
  1799. "User specified but switching users is unsupported on your OS.");
  1800. return -1;
  1801. #endif
  1802. }
  1803. /* We only use the linux prctl for now. There is no Win32 support; this may
  1804. * also work on various BSD systems and Mac OS X - send testing feedback!
  1805. *
  1806. * On recent Gnu/Linux kernels it is possible to create a system-wide policy
  1807. * that will prevent non-root processes from attaching to other processes
  1808. * unless they are the parent process; thus gdb can attach to programs that
  1809. * they execute but they cannot attach to other processes running as the same
  1810. * user. The system wide policy may be set with the sysctl
  1811. * kernel.yama.ptrace_scope or by inspecting
  1812. * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
  1813. *
  1814. * This ptrace scope will be ignored on Gnu/Linux for users with
  1815. * CAP_SYS_PTRACE and so it is very likely that root will still be able to
  1816. * attach to the Tor process.
  1817. */
  1818. /** Attempt to disable debugger attachment: return 1 on success, -1 on
  1819. * failure, and 0 if we don't know how to try on this platform. */
  1820. int
  1821. tor_disable_debugger_attach(void)
  1822. {
  1823. int r, attempted;
  1824. r = -1;
  1825. attempted = 0;
  1826. log_debug(LD_CONFIG,
  1827. "Attemping to disable debugger attachment to Tor for "
  1828. "unprivileged users.");
  1829. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
  1830. #ifdef PR_SET_DUMPABLE
  1831. attempted = 1;
  1832. r = prctl(PR_SET_DUMPABLE, 0);
  1833. #endif
  1834. #endif
  1835. #if defined(__APPLE__) && defined(PT_DENY_ATTACH)
  1836. if (r < 0) {
  1837. attempted = 1;
  1838. r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
  1839. }
  1840. #endif
  1841. // XXX: TODO - Mac OS X has dtrace and this may be disabled.
  1842. // XXX: TODO - Windows probably has something similar
  1843. if (r == 0 && attempted) {
  1844. log_debug(LD_CONFIG,"Debugger attachment disabled for "
  1845. "unprivileged users.");
  1846. return 1;
  1847. } else if (attempted) {
  1848. log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
  1849. strerror(errno));
  1850. }
  1851. return r;
  1852. }
  1853. #ifdef HAVE_PWD_H
  1854. /** Allocate and return a string containing the home directory for the
  1855. * user <b>username</b>. Only works on posix-like systems. */
  1856. char *
  1857. get_user_homedir(const char *username)
  1858. {
  1859. const struct passwd *pw;
  1860. tor_assert(username);
  1861. if (!(pw = tor_getpwnam(username))) {
  1862. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  1863. return NULL;
  1864. }
  1865. return tor_strdup(pw->pw_dir);
  1866. }
  1867. #endif
  1868. /** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
  1869. * actually examine the filesystem; does a purely syntactic modification.
  1870. *
  1871. * The parent of the root director is considered to be iteself.
  1872. *
  1873. * Path separators are the forward slash (/) everywhere and additionally
  1874. * the backslash (\) on Win32.
  1875. *
  1876. * Cuts off any number of trailing path separators but otherwise ignores
  1877. * them for purposes of finding the parent directory.
  1878. *
  1879. * Returns 0 if a parent directory was successfully found, -1 otherwise (fname
  1880. * did not have any path separators or only had them at the end).
  1881. * */
  1882. int
  1883. get_parent_directory(char *fname)
  1884. {
  1885. char *cp;
  1886. int at_end = 1;
  1887. tor_assert(fname);
  1888. #ifdef _WIN32
  1889. /* If we start with, say, c:, then don't consider that the start of the path
  1890. */
  1891. if (fname[0] && fname[1] == ':') {
  1892. fname += 2;
  1893. }
  1894. #endif
  1895. /* Now we want to remove all path-separators at the end of the string,
  1896. * and to remove the end of the string starting with the path separator
  1897. * before the last non-path-separator. In perl, this would be
  1898. * s#[/]*$##; s#/[^/]*$##;
  1899. * on a unixy platform.
  1900. */
  1901. cp = fname + strlen(fname);
  1902. at_end = 1;
  1903. while (--cp >= fname) {
  1904. int is_sep = (*cp == '/'
  1905. #ifdef _WIN32
  1906. || *cp == '\\'
  1907. #endif
  1908. );
  1909. if (is_sep) {
  1910. if (cp == fname) {
  1911. /* This is the first separator in the file name; don't remove it! */
  1912. cp[1] = '\0';
  1913. return 0;
  1914. }
  1915. *cp = '\0';
  1916. if (! at_end)
  1917. return 0;
  1918. } else {
  1919. at_end = 0;
  1920. }
  1921. }
  1922. return -1;
  1923. }
  1924. #ifndef _WIN32
  1925. /** Return a newly allocated string containing the output of getcwd(). Return
  1926. * NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
  1927. * Hurd hasn't got a PATH_MAX.)
  1928. */
  1929. static char *
  1930. alloc_getcwd(void)
  1931. {
  1932. int saved_errno = errno;
  1933. /* We use this as a starting path length. Not too large seems sane. */
  1934. #define START_PATH_LENGTH 128
  1935. /* Nobody has a maxpath longer than this, as far as I know. And if they
  1936. * do, they shouldn't. */
  1937. #define MAX_SANE_PATH_LENGTH 4096
  1938. size_t path_length = START_PATH_LENGTH;
  1939. char *path = tor_malloc(path_length);
  1940. errno = 0;
  1941. while (getcwd(path, path_length) == NULL) {
  1942. if (errno == ERANGE && path_length < MAX_SANE_PATH_LENGTH) {
  1943. path_length*=2;
  1944. path = tor_realloc(path, path_length);
  1945. } else {
  1946. tor_free(path);
  1947. path = NULL;
  1948. break;
  1949. }
  1950. }
  1951. errno = saved_errno;
  1952. return path;
  1953. }
  1954. #endif
  1955. /** Expand possibly relative path <b>fname</b> to an absolute path.
  1956. * Return a newly allocated string, possibly equal to <b>fname</b>. */
  1957. char *
  1958. make_path_absolute(char *fname)
  1959. {
  1960. #ifdef _WIN32
  1961. char *absfname_malloced = _fullpath(NULL, fname, 1);
  1962. /* We don't want to assume that tor_free can free a string allocated
  1963. * with malloc. On failure, return fname (it's better than nothing). */
  1964. char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
  1965. if (absfname_malloced) free(absfname_malloced);
  1966. return absfname;
  1967. #else
  1968. char *absfname = NULL, *path = NULL;
  1969. tor_assert(fname);
  1970. if (fname[0] == '/') {
  1971. absfname = tor_strdup(fname);
  1972. } else {
  1973. path = alloc_getcwd();
  1974. if (path) {
  1975. tor_asprintf(&absfname, "%s/%s", path, fname);
  1976. tor_free(path);
  1977. } else {
  1978. /* If getcwd failed, the best we can do here is keep using the
  1979. * relative path. (Perhaps / isn't readable by this UID/GID.) */
  1980. log_warn(LD_GENERAL, "Unable to find current working directory: %s",
  1981. strerror(errno));
  1982. absfname = tor_strdup(fname);
  1983. }
  1984. }
  1985. return absfname;
  1986. #endif
  1987. }
  1988. #ifndef HAVE__NSGETENVIRON
  1989. #ifndef HAVE_EXTERN_ENVIRON_DECLARED
  1990. /* Some platforms declare environ under some circumstances, others don't. */
  1991. #ifndef RUNNING_DOXYGEN
  1992. extern char **environ;
  1993. #endif
  1994. #endif
  1995. #endif
  1996. /** Return the current environment. This is a portable replacement for
  1997. * 'environ'. */
  1998. char **
  1999. get_environment(void)
  2000. {
  2001. #ifdef HAVE__NSGETENVIRON
  2002. /* This is for compatibility between OSX versions. Otherwise (for example)
  2003. * when we do a mostly-static build on OSX 10.7, the resulting binary won't
  2004. * work on OSX 10.6. */
  2005. return *_NSGetEnviron();
  2006. #else
  2007. return environ;
  2008. #endif
  2009. }
  2010. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  2011. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  2012. * but works on Windows and Solaris.)
  2013. */
  2014. int
  2015. tor_inet_aton(const char *str, struct in_addr* addr)
  2016. {
  2017. unsigned a,b,c,d;
  2018. char more;
  2019. if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
  2020. return 0;
  2021. if (a > 255) return 0;
  2022. if (b > 255) return 0;
  2023. if (c > 255) return 0;
  2024. if (d > 255) return 0;
  2025. addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
  2026. return 1;
  2027. }
  2028. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  2029. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  2030. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  2031. * <b>dst</b> on success, NULL on failure.
  2032. *
  2033. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  2034. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  2035. * support.) */
  2036. const char *
  2037. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  2038. {
  2039. if (af == AF_INET) {
  2040. if (tor_inet_ntoa(src, dst, len) < 0)
  2041. return NULL;
  2042. else
  2043. return dst;
  2044. } else if (af == AF_INET6) {
  2045. const struct in6_addr *addr = src;
  2046. char buf[64], *cp;
  2047. int longestGapLen = 0, longestGapPos = -1, i,
  2048. curGapPos = -1, curGapLen = 0;
  2049. uint16_t words[8];
  2050. for (i = 0; i < 8; ++i) {
  2051. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  2052. }
  2053. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  2054. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  2055. (words[5] == 0xffff))) {
  2056. /* This is an IPv4 address. */
  2057. if (words[5] == 0) {
  2058. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  2059. addr->s6_addr[12], addr->s6_addr[13],
  2060. addr->s6_addr[14], addr->s6_addr[15]);
  2061. } else {
  2062. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  2063. addr->s6_addr[12], addr->s6_addr[13],
  2064. addr->s6_addr[14], addr->s6_addr[15]);
  2065. }
  2066. if ((strlen(buf) + 1) > len) /* +1 for \0 */
  2067. return NULL;
  2068. strlcpy(dst, buf, len);
  2069. return dst;
  2070. }
  2071. i = 0;
  2072. while (i < 8) {
  2073. if (words[i] == 0) {
  2074. curGapPos = i++;
  2075. curGapLen = 1;
  2076. while (i<8 && words[i] == 0) {
  2077. ++i; ++curGapLen;
  2078. }
  2079. if (curGapLen > longestGapLen) {
  2080. longestGapPos = curGapPos;
  2081. longestGapLen = curGapLen;
  2082. }
  2083. } else {
  2084. ++i;
  2085. }
  2086. }
  2087. if (longestGapLen<=1)
  2088. longestGapPos = -1;
  2089. cp = buf;
  2090. for (i = 0; i < 8; ++i) {
  2091. if (words[i] == 0 && longestGapPos == i) {
  2092. if (i == 0)
  2093. *cp++ = ':';
  2094. *cp++ = ':';
  2095. while (i < 8 && words[i] == 0)
  2096. ++i;
  2097. --i; /* to compensate for loop increment. */
  2098. } else {
  2099. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  2100. cp += strlen(cp);
  2101. if (i != 7)
  2102. *cp++ = ':';
  2103. }
  2104. }
  2105. *cp = '\0';
  2106. if ((strlen(buf) + 1) > len) /* +1 for \0 */
  2107. return NULL;
  2108. strlcpy(dst, buf, len);
  2109. return dst;
  2110. } else {
  2111. return NULL;
  2112. }
  2113. }
  2114. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  2115. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  2116. * address and store the result in <b>dst</b> (which must have space for a
  2117. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  2118. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  2119. *
  2120. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  2121. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  2122. * support.) */
  2123. int
  2124. tor_inet_pton(int af, const char *src, void *dst)
  2125. {
  2126. if (af == AF_INET) {
  2127. return tor_inet_aton(src, dst);
  2128. } else if (af == AF_INET6) {
  2129. struct in6_addr *out = dst;
  2130. uint16_t words[8];
  2131. int gapPos = -1, i, setWords=0;
  2132. const char *dot = strchr(src, '.');
  2133. const char *eow; /* end of words. */
  2134. if (dot == src)
  2135. return 0;
  2136. else if (!dot)
  2137. eow = src+strlen(src);
  2138. else {
  2139. unsigned byte1,byte2,byte3,byte4;
  2140. char more;
  2141. for (eow = dot-1; eow > src && TOR_ISDIGIT(*eow); --eow)
  2142. ;
  2143. if (*eow != ':')
  2144. return 0;
  2145. ++eow;
  2146. /* We use "scanf" because some platform inet_aton()s are too lax
  2147. * about IPv4 addresses of the form "1.2.3" */
  2148. if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
  2149. &byte1,&byte2,&byte3,&byte4,&more) != 4)
  2150. return 0;
  2151. if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
  2152. return 0;
  2153. words[6] = (byte1<<8) | byte2;
  2154. words[7] = (byte3<<8) | byte4;
  2155. setWords += 2;
  2156. }
  2157. i = 0;
  2158. while (src < eow) {
  2159. if (i > 7)
  2160. return 0;
  2161. if (TOR_ISXDIGIT(*src)) {
  2162. char *next;
  2163. ssize_t len;
  2164. long r = strtol(src, &next, 16);
  2165. tor_assert(next != NULL);
  2166. tor_assert(next != src);
  2167. len = *next == '\0' ? eow - src : next - src;
  2168. if (len > 4)
  2169. return 0;
  2170. if (len > 1 && !TOR_ISXDIGIT(src[1]))
  2171. return 0; /* 0x is not valid */
  2172. tor_assert(r >= 0);
  2173. tor_assert(r < 65536);
  2174. words[i++] = (uint16_t)r;
  2175. setWords++;
  2176. src = next;
  2177. if (*src != ':' && src != eow)
  2178. return 0;
  2179. ++src;
  2180. } else if (*src == ':' && i > 0 && gapPos == -1) {
  2181. gapPos = i;
  2182. ++src;
  2183. } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' &&
  2184. gapPos == -1) {
  2185. gapPos = i;
  2186. src += 2;
  2187. } else {
  2188. return 0;
  2189. }
  2190. }
  2191. if (setWords > 8 ||
  2192. (setWords == 8 && gapPos != -1) ||
  2193. (setWords < 8 && gapPos == -1))
  2194. return 0;
  2195. if (gapPos >= 0) {
  2196. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  2197. int gapLen = 8 - setWords;
  2198. tor_assert(nToMove >= 0);
  2199. memmove(&words[gapPos+gapLen], &words[gapPos],
  2200. sizeof(uint16_t)*nToMove);
  2201. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  2202. }
  2203. for (i = 0; i < 8; ++i) {
  2204. out->s6_addr[2*i ] = words[i] >> 8;
  2205. out->s6_addr[2*i+1] = words[i] & 0xff;
  2206. }
  2207. return 1;
  2208. } else {
  2209. return -1;
  2210. }
  2211. }
  2212. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  2213. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  2214. * on success, -1 on failure; 1 on transient failure.
  2215. *
  2216. * (This function exists because standard windows gethostbyname
  2217. * doesn't treat raw IP addresses properly.)
  2218. */
  2219. int
  2220. tor_lookup_hostname(const char *name, uint32_t *addr)
  2221. {
  2222. tor_addr_t myaddr;
  2223. int ret;
  2224. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  2225. return ret;
  2226. if (tor_addr_family(&myaddr) == AF_INET) {
  2227. *addr = tor_addr_to_ipv4h(&myaddr);
  2228. return ret;
  2229. }
  2230. return -1;
  2231. }
  2232. /** Hold the result of our call to <b>uname</b>. */
  2233. static char uname_result[256];
  2234. /** True iff uname_result is set. */
  2235. static int uname_result_is_set = 0;
  2236. /** Return a pointer to a description of our platform.
  2237. */
  2238. const char *
  2239. get_uname(void)
  2240. {
  2241. #ifdef HAVE_UNAME
  2242. struct utsname u;
  2243. #endif
  2244. if (!uname_result_is_set) {
  2245. #ifdef HAVE_UNAME
  2246. if (uname(&u) != -1) {
  2247. /* (Linux says 0 is success, Solaris says 1 is success) */
  2248. strlcpy(uname_result, u.sysname, sizeof(uname_result));
  2249. } else
  2250. #endif
  2251. {
  2252. #ifdef _WIN32
  2253. OSVERSIONINFOEX info;
  2254. int i;
  2255. const char *plat = NULL;
  2256. static struct {
  2257. unsigned major; unsigned minor; const char *version;
  2258. } win_version_table[] = {
  2259. { 6, 2, "Windows 8" },
  2260. { 6, 1, "Windows 7" },
  2261. { 6, 0, "Windows Vista" },
  2262. { 5, 2, "Windows Server 2003" },
  2263. { 5, 1, "Windows XP" },
  2264. { 5, 0, "Windows 2000" },
  2265. /* { 4, 0, "Windows NT 4.0" }, */
  2266. { 4, 90, "Windows Me" },
  2267. { 4, 10, "Windows 98" },
  2268. /* { 4, 0, "Windows 95" } */
  2269. { 3, 51, "Windows NT 3.51" },
  2270. { 0, 0, NULL }
  2271. };
  2272. memset(&info, 0, sizeof(info));
  2273. info.dwOSVersionInfoSize = sizeof(info);
  2274. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  2275. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  2276. " doesn't work.", sizeof(uname_result));
  2277. uname_result_is_set = 1;
  2278. return uname_result;
  2279. }
  2280. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  2281. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  2282. plat = "Windows NT 4.0";
  2283. else
  2284. plat = "Windows 95";
  2285. } else {
  2286. for (i=0; win_version_table[i].major>0; ++i) {
  2287. if (win_version_table[i].major == info.dwMajorVersion &&
  2288. win_version_table[i].minor == info.dwMinorVersion) {
  2289. plat = win_version_table[i].version;
  2290. break;
  2291. }
  2292. }
  2293. }
  2294. if (plat) {
  2295. strlcpy(uname_result, plat, sizeof(uname_result));
  2296. } else {
  2297. if (info.dwMajorVersion > 6 ||
  2298. (info.dwMajorVersion==6 && info.dwMinorVersion>2))
  2299. tor_snprintf(uname_result, sizeof(uname_result),
  2300. "Very recent version of Windows [major=%d,minor=%d]",
  2301. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  2302. else
  2303. tor_snprintf(uname_result, sizeof(uname_result),
  2304. "Unrecognized version of Windows [major=%d,minor=%d]",
  2305. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  2306. }
  2307. #ifdef VER_NT_SERVER
  2308. if (info.wProductType == VER_NT_SERVER ||
  2309. info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  2310. strlcat(uname_result, " [server]", sizeof(uname_result));
  2311. }
  2312. #endif
  2313. #else
  2314. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  2315. #endif
  2316. }
  2317. uname_result_is_set = 1;
  2318. }
  2319. return uname_result;
  2320. }
  2321. /*
  2322. * Process control
  2323. */
  2324. #if defined(USE_PTHREADS)
  2325. /** Wraps a void (*)(void*) function and its argument so we can
  2326. * invoke them in a way pthreads would expect.
  2327. */
  2328. typedef struct tor_pthread_data_t {
  2329. void (*func)(void *);
  2330. void *data;
  2331. } tor_pthread_data_t;
  2332. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  2333. * and free _data. Used to make sure we can call functions the way pthread
  2334. * expects. */
  2335. static void *
  2336. tor_pthread_helper_fn(void *_data)
  2337. {
  2338. tor_pthread_data_t *data = _data;
  2339. void (*func)(void*);
  2340. void *arg;
  2341. /* mask signals to worker threads to avoid SIGPIPE, etc */
  2342. sigset_t sigs;
  2343. /* We're in a subthread; don't handle any signals here. */
  2344. sigfillset(&sigs);
  2345. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  2346. func = data->func;
  2347. arg = data->data;
  2348. tor_free(_data);
  2349. func(arg);
  2350. return NULL;
  2351. }
  2352. /**
  2353. * A pthread attribute to make threads start detached.
  2354. */
  2355. static pthread_attr_t attr_detached;
  2356. /** True iff we've called tor_threads_init() */
  2357. static int threads_initialized = 0;
  2358. #endif
  2359. /** Minimalist interface to run a void function in the background. On
  2360. * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  2361. * func should not return, but rather should call spawn_exit.
  2362. *
  2363. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  2364. * since in a multithreaded environment, there is no way to be sure that
  2365. * the caller's stack will still be around when the called function is
  2366. * running.
  2367. */
  2368. int
  2369. spawn_func(void (*func)(void *), void *data)
  2370. {
  2371. #if defined(USE_WIN32_THREADS)
  2372. int rv;
  2373. rv = (int)_beginthread(func, 0, data);
  2374. if (rv == (int)-1)
  2375. return -1;
  2376. return 0;
  2377. #elif defined(USE_PTHREADS)
  2378. pthread_t thread;
  2379. tor_pthread_data_t *d;
  2380. if (PREDICT_UNLIKELY(!threads_initialized))
  2381. tor_threads_init();
  2382. d = tor_malloc(sizeof(tor_pthread_data_t));
  2383. d->data = data;
  2384. d->func = func;
  2385. if (pthread_create(&thread,&attr_detached,tor_pthread_helper_fn,d))
  2386. return -1;
  2387. return 0;
  2388. #else
  2389. pid_t pid;
  2390. pid = fork();
  2391. if (pid<0)
  2392. return -1;
  2393. if (pid==0) {
  2394. /* Child */
  2395. func(data);
  2396. tor_assert(0); /* Should never reach here. */
  2397. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  2398. } else {
  2399. /* Parent */
  2400. return 0;
  2401. }
  2402. #endif
  2403. }
  2404. /** End the current thread/process.
  2405. */
  2406. void
  2407. spawn_exit(void)
  2408. {
  2409. #if defined(USE_WIN32_THREADS)
  2410. _endthread();
  2411. //we should never get here. my compiler thinks that _endthread returns, this
  2412. //is an attempt to fool it.
  2413. tor_assert(0);
  2414. _exit(0);
  2415. #elif defined(USE_PTHREADS)
  2416. pthread_exit(NULL);
  2417. #else
  2418. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  2419. * call _exit, not exit, from child processes. */
  2420. _exit(0);
  2421. #endif
  2422. }
  2423. /** Implementation logic for compute_num_cpus(). */
  2424. static int
  2425. compute_num_cpus_impl(void)
  2426. {
  2427. #ifdef _WIN32
  2428. SYSTEM_INFO info;
  2429. memset(&info, 0, sizeof(info));
  2430. GetSystemInfo(&info);
  2431. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  2432. return (int)info.dwNumberOfProcessors;
  2433. else
  2434. return -1;
  2435. #elif defined(HAVE_SYSCONF)
  2436. #ifdef _SC_NPROCESSORS_CONF
  2437. long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
  2438. #else
  2439. long cpus_conf = -1;
  2440. #endif
  2441. #ifdef _SC_NPROCESSORS_ONLN
  2442. long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
  2443. #else
  2444. long cpus_onln = -1;
  2445. #endif
  2446. long cpus = -1;
  2447. if (cpus_conf > 0 && cpus_onln < 0) {
  2448. cpus = cpus_conf;
  2449. } else if (cpus_onln > 0 && cpus_conf < 0) {
  2450. cpus = cpus_onln;
  2451. } else if (cpus_onln > 0 && cpus_conf > 0) {
  2452. if (cpus_onln < cpus_conf) {
  2453. log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
  2454. "are available. Telling Tor to only use %ld. You can over"
  2455. "ride this with the NumCPUs option",
  2456. cpus_conf, cpus_onln, cpus_onln);
  2457. }
  2458. cpus = cpus_onln;
  2459. }
  2460. if (cpus >= 1 && cpus < INT_MAX)
  2461. return (int)cpus;
  2462. else
  2463. return -1;
  2464. #else
  2465. return -1;
  2466. #endif
  2467. }
  2468. #define MAX_DETECTABLE_CPUS 16
  2469. /** Return how many CPUs we are running with. We assume that nobody is
  2470. * using hot-swappable CPUs, so we don't recompute this after the first
  2471. * time. Return -1 if we don't know how to tell the number of CPUs on this
  2472. * system.
  2473. */
  2474. int
  2475. compute_num_cpus(void)
  2476. {
  2477. static int num_cpus = -2;
  2478. if (num_cpus == -2) {
  2479. num_cpus = compute_num_cpus_impl();
  2480. tor_assert(num_cpus != -2);
  2481. if (num_cpus > MAX_DETECTABLE_CPUS)
  2482. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  2483. "will not autodetect any more than %d, though. If you "
  2484. "want to configure more, set NumCPUs in your torrc",
  2485. num_cpus, MAX_DETECTABLE_CPUS);
  2486. }
  2487. return num_cpus;
  2488. }
  2489. /** Set *timeval to the current time of day. On error, log and terminate.
  2490. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  2491. */
  2492. void
  2493. tor_gettimeofday(struct timeval *timeval)
  2494. {
  2495. #ifdef _WIN32
  2496. /* Epoch bias copied from perl: number of units between windows epoch and
  2497. * Unix epoch. */
  2498. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  2499. #define UNITS_PER_SEC U64_LITERAL(10000000)
  2500. #define USEC_PER_SEC U64_LITERAL(1000000)
  2501. #define UNITS_PER_USEC U64_LITERAL(10)
  2502. union {
  2503. uint64_t ft_64;
  2504. FILETIME ft_ft;
  2505. } ft;
  2506. /* number of 100-nsec units since Jan 1, 1601 */
  2507. GetSystemTimeAsFileTime(&ft.ft_ft);
  2508. if (ft.ft_64 < EPOCH_BIAS) {
  2509. log_err(LD_GENERAL,"System time is before 1970; failing.");
  2510. exit(1);
  2511. }
  2512. ft.ft_64 -= EPOCH_BIAS;
  2513. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  2514. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  2515. #elif defined(HAVE_GETTIMEOFDAY)
  2516. if (gettimeofday(timeval, NULL)) {
  2517. log_err(LD_GENERAL,"gettimeofday failed.");
  2518. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  2519. or segfaulted.*/
  2520. exit(1);
  2521. }
  2522. #elif defined(HAVE_FTIME)
  2523. struct timeb tb;
  2524. ftime(&tb);
  2525. timeval->tv_sec = tb.time;
  2526. timeval->tv_usec = tb.millitm * 1000;
  2527. #else
  2528. #error "No way to get time."
  2529. #endif
  2530. return;
  2531. }
  2532. #if !defined(_WIN32)
  2533. /** Defined iff we need to add locks when defining fake versions of reentrant
  2534. * versions of time-related functions. */
  2535. #define TIME_FNS_NEED_LOCKS
  2536. #endif
  2537. /** Helper: Deal with confused or out-of-bounds values from localtime_r and
  2538. * friends. (On some platforms, they can give out-of-bounds values or can
  2539. * return NULL.) If <b>islocal</b>, this is a localtime result; otherwise
  2540. * it's from gmtime. The function returned <b>r</b>, when given <b>timep</b>
  2541. * as its input. If we need to store new results, store them in
  2542. * <b>resultbuf</b>. */
  2543. static struct tm *
  2544. correct_tm(int islocal, const time_t *timep, struct tm *resultbuf,
  2545. struct tm *r)
  2546. {
  2547. const char *outcome;
  2548. if (PREDICT_LIKELY(r)) {
  2549. /* We can't strftime dates after 9999 CE, and we want to avoid dates
  2550. * before 1 CE (avoiding the year 0 issue and negative years). */
  2551. if (r->tm_year > 8099) {
  2552. r->tm_year = 8099;
  2553. r->tm_mon = 11;
  2554. r->tm_mday = 31;
  2555. r->tm_yday = 364;
  2556. r->tm_hour = 23;
  2557. r->tm_min = 59;
  2558. r->tm_sec = 59;
  2559. } else if (r->tm_year < (1-1900)) {
  2560. r->tm_year = (1-1900);
  2561. r->tm_mon = 0;
  2562. r->tm_mday = 1;
  2563. r->tm_yday = 0;
  2564. r->tm_hour = 0;
  2565. r->tm_min = 0;
  2566. r->tm_sec = 0;
  2567. }
  2568. return r;
  2569. }
  2570. /* If we get here, gmtime or localtime returned NULL. It might have done
  2571. * this because of overrun or underrun, or it might have done it because of
  2572. * some other weird issue. */
  2573. if (timep) {
  2574. if (*timep < 0) {
  2575. r = resultbuf;
  2576. r->tm_year = 70; /* 1970 CE */
  2577. r->tm_mon = 0;
  2578. r->tm_mday = 1;
  2579. r->tm_yday = 0;
  2580. r->tm_hour = 0;
  2581. r->tm_min = 0 ;
  2582. r->tm_sec = 0;
  2583. outcome = "Rounding up to 1970";
  2584. goto done;
  2585. } else if (*timep >= INT32_MAX) {
  2586. /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
  2587. * only do it if gmtime/localtime tells us NULL. */
  2588. r = resultbuf;
  2589. r->tm_year = 137; /* 2037 CE */
  2590. r->tm_mon = 11;
  2591. r->tm_mday = 31;
  2592. r->tm_yday = 364;
  2593. r->tm_hour = 23;
  2594. r->tm_min = 59;
  2595. r->tm_sec = 59;
  2596. outcome = "Rounding down to 2037";
  2597. goto done;
  2598. }
  2599. }
  2600. /* If we get here, then gmtime/localtime failed without getting an extreme
  2601. * value for *timep */
  2602. tor_fragile_assert();
  2603. r = resultbuf;
  2604. memset(resultbuf, 0, sizeof(struct tm));
  2605. outcome="can't recover";
  2606. done:
  2607. log_warn(LD_BUG, "%s("I64_FORMAT") failed with error %s: %s",
  2608. islocal?"localtime":"gmtime",
  2609. timep?I64_PRINTF_ARG(*timep):0,
  2610. strerror(errno),
  2611. outcome);
  2612. return r;
  2613. }
  2614. /** @{ */
  2615. /** As localtime_r, but defined for platforms that don't have it:
  2616. *
  2617. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  2618. * *<b>result</b>. Return the result on success, or NULL on failure.
  2619. */
  2620. #ifdef HAVE_LOCALTIME_R
  2621. struct tm *
  2622. tor_localtime_r(const time_t *timep, struct tm *result)
  2623. {
  2624. struct tm *r;
  2625. r = localtime_r(timep, result);
  2626. return correct_tm(1, timep, result, r);
  2627. }
  2628. #elif defined(TIME_FNS_NEED_LOCKS)
  2629. struct tm *
  2630. tor_localtime_r(const time_t *timep, struct tm *result)
  2631. {
  2632. struct tm *r;
  2633. static tor_mutex_t *m=NULL;
  2634. if (!m) { m=tor_mutex_new(); }
  2635. tor_assert(result);
  2636. tor_mutex_acquire(m);
  2637. r = localtime(timep);
  2638. if (r)
  2639. memcpy(result, r, sizeof(struct tm));
  2640. tor_mutex_release(m);
  2641. return correct_tm(1, timep, result, r);
  2642. }
  2643. #else
  2644. struct tm *
  2645. tor_localtime_r(const time_t *timep, struct tm *result)
  2646. {
  2647. struct tm *r;
  2648. tor_assert(result);
  2649. r = localtime(timep);
  2650. if (r)
  2651. memcpy(result, r, sizeof(struct tm));
  2652. return correct_tm(1, timep, result, r);
  2653. }
  2654. #endif
  2655. /** @} */
  2656. /** @{ */
  2657. /** As gmtime_r, but defined for platforms that don't have it:
  2658. *
  2659. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  2660. * *<b>result</b>. Return the result on success, or NULL on failure.
  2661. */
  2662. #ifdef HAVE_GMTIME_R
  2663. struct tm *
  2664. tor_gmtime_r(const time_t *timep, struct tm *result)
  2665. {
  2666. struct tm *r;
  2667. r = gmtime_r(timep, result);
  2668. return correct_tm(0, timep, result, r);
  2669. }
  2670. #elif defined(TIME_FNS_NEED_LOCKS)
  2671. struct tm *
  2672. tor_gmtime_r(const time_t *timep, struct tm *result)
  2673. {
  2674. struct tm *r;
  2675. static tor_mutex_t *m=NULL;
  2676. if (!m) { m=tor_mutex_new(); }
  2677. tor_assert(result);
  2678. tor_mutex_acquire(m);
  2679. r = gmtime(timep);
  2680. if (r)
  2681. memcpy(result, r, sizeof(struct tm));
  2682. tor_mutex_release(m);
  2683. return correct_tm(0, timep, result, r);
  2684. }
  2685. #else
  2686. struct tm *
  2687. tor_gmtime_r(const time_t *timep, struct tm *result)
  2688. {
  2689. struct tm *r;
  2690. tor_assert(result);
  2691. r = gmtime(timep);
  2692. if (r)
  2693. memcpy(result, r, sizeof(struct tm));
  2694. return correct_tm(0, timep, result, r);
  2695. }
  2696. #endif
  2697. #if defined(USE_WIN32_THREADS)
  2698. void
  2699. tor_mutex_init(tor_mutex_t *m)
  2700. {
  2701. InitializeCriticalSection(&m->mutex);
  2702. }
  2703. void
  2704. tor_mutex_uninit(tor_mutex_t *m)
  2705. {
  2706. DeleteCriticalSection(&m->mutex);
  2707. }
  2708. void
  2709. tor_mutex_acquire(tor_mutex_t *m)
  2710. {
  2711. tor_assert(m);
  2712. EnterCriticalSection(&m->mutex);
  2713. }
  2714. void
  2715. tor_mutex_release(tor_mutex_t *m)
  2716. {
  2717. LeaveCriticalSection(&m->mutex);
  2718. }
  2719. unsigned long
  2720. tor_get_thread_id(void)
  2721. {
  2722. return (unsigned long)GetCurrentThreadId();
  2723. }
  2724. #elif defined(USE_PTHREADS)
  2725. /** A mutex attribute that we're going to use to tell pthreads that we want
  2726. * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
  2727. * them.) */
  2728. static pthread_mutexattr_t attr_reentrant;
  2729. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  2730. * up with tor_mutex_init() or tor_mutex_new(); not both. */
  2731. void
  2732. tor_mutex_init(tor_mutex_t *mutex)
  2733. {
  2734. int err;
  2735. if (PREDICT_UNLIKELY(!threads_initialized))
  2736. tor_threads_init();
  2737. err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
  2738. if (PREDICT_UNLIKELY(err)) {
  2739. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  2740. tor_fragile_assert();
  2741. }
  2742. }
  2743. /** Wait until <b>m</b> is free, then acquire it. */
  2744. void
  2745. tor_mutex_acquire(tor_mutex_t *m)
  2746. {
  2747. int err;
  2748. tor_assert(m);
  2749. err = pthread_mutex_lock(&m->mutex);
  2750. if (PREDICT_UNLIKELY(err)) {
  2751. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  2752. tor_fragile_assert();
  2753. }
  2754. }
  2755. /** Release the lock <b>m</b> so another thread can have it. */
  2756. void
  2757. tor_mutex_release(tor_mutex_t *m)
  2758. {
  2759. int err;
  2760. tor_assert(m);
  2761. err = pthread_mutex_unlock(&m->mutex);
  2762. if (PREDICT_UNLIKELY(err)) {
  2763. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  2764. tor_fragile_assert();
  2765. }
  2766. }
  2767. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  2768. * resources. Does not free <b>m</b>. This function must only be called on
  2769. * mutexes from tor_mutex_init(). */
  2770. void
  2771. tor_mutex_uninit(tor_mutex_t *m)
  2772. {
  2773. int err;
  2774. tor_assert(m);
  2775. err = pthread_mutex_destroy(&m->mutex);
  2776. if (PREDICT_UNLIKELY(err)) {
  2777. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  2778. tor_fragile_assert();
  2779. }
  2780. }
  2781. /** Return an integer representing this thread. */
  2782. unsigned long
  2783. tor_get_thread_id(void)
  2784. {
  2785. union {
  2786. pthread_t thr;
  2787. unsigned long id;
  2788. } r;
  2789. r.thr = pthread_self();
  2790. return r.id;
  2791. }
  2792. #endif
  2793. /** Return a newly allocated, ready-for-use mutex. */
  2794. tor_mutex_t *
  2795. tor_mutex_new(void)
  2796. {
  2797. tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
  2798. tor_mutex_init(m);
  2799. return m;
  2800. }
  2801. /** Release all storage and system resources held by <b>m</b>. */
  2802. void
  2803. tor_mutex_free(tor_mutex_t *m)
  2804. {
  2805. if (!m)
  2806. return;
  2807. tor_mutex_uninit(m);
  2808. tor_free(m);
  2809. }
  2810. /* Conditions. */
  2811. #ifdef USE_PTHREADS
  2812. #if 0
  2813. /** Cross-platform condition implementation. */
  2814. struct tor_cond_t {
  2815. pthread_cond_t cond;
  2816. };
  2817. /** Return a newly allocated condition, with nobody waiting on it. */
  2818. tor_cond_t *
  2819. tor_cond_new(void)
  2820. {
  2821. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2822. if (pthread_cond_init(&cond->cond, NULL)) {
  2823. tor_free(cond);
  2824. return NULL;
  2825. }
  2826. return cond;
  2827. }
  2828. /** Release all resources held by <b>cond</b>. */
  2829. void
  2830. tor_cond_free(tor_cond_t *cond)
  2831. {
  2832. if (!cond)
  2833. return;
  2834. if (pthread_cond_destroy(&cond->cond)) {
  2835. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  2836. return;
  2837. }
  2838. tor_free(cond);
  2839. }
  2840. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  2841. * All waiters on the condition must wait holding the same <b>mutex</b>.
  2842. * Returns 0 on success, negative on failure. */
  2843. int
  2844. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2845. {
  2846. return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
  2847. }
  2848. /** Wake up one of the waiters on <b>cond</b>. */
  2849. void
  2850. tor_cond_signal_one(tor_cond_t *cond)
  2851. {
  2852. pthread_cond_signal(&cond->cond);
  2853. }
  2854. /** Wake up all of the waiters on <b>cond</b>. */
  2855. void
  2856. tor_cond_signal_all(tor_cond_t *cond)
  2857. {
  2858. pthread_cond_broadcast(&cond->cond);
  2859. }
  2860. #endif
  2861. /** Set up common structures for use by threading. */
  2862. void
  2863. tor_threads_init(void)
  2864. {
  2865. if (!threads_initialized) {
  2866. pthread_mutexattr_init(&attr_reentrant);
  2867. pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
  2868. tor_assert(0==pthread_attr_init(&attr_detached));
  2869. tor_assert(0==pthread_attr_setdetachstate(&attr_detached, 1));
  2870. threads_initialized = 1;
  2871. set_main_thread();
  2872. }
  2873. }
  2874. #elif defined(USE_WIN32_THREADS)
  2875. #if 0
  2876. static DWORD cond_event_tls_index;
  2877. struct tor_cond_t {
  2878. CRITICAL_SECTION mutex;
  2879. smartlist_t *events;
  2880. };
  2881. tor_cond_t *
  2882. tor_cond_new(void)
  2883. {
  2884. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2885. InitializeCriticalSection(&cond->mutex);
  2886. cond->events = smartlist_new();
  2887. return cond;
  2888. }
  2889. void
  2890. tor_cond_free(tor_cond_t *cond)
  2891. {
  2892. if (!cond)
  2893. return;
  2894. DeleteCriticalSection(&cond->mutex);
  2895. /* XXXX notify? */
  2896. smartlist_free(cond->events);
  2897. tor_free(cond);
  2898. }
  2899. int
  2900. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2901. {
  2902. HANDLE event;
  2903. int r;
  2904. tor_assert(cond);
  2905. tor_assert(mutex);
  2906. event = TlsGetValue(cond_event_tls_index);
  2907. if (!event) {
  2908. event = CreateEvent(0, FALSE, FALSE, NULL);
  2909. TlsSetValue(cond_event_tls_index, event);
  2910. }
  2911. EnterCriticalSection(&cond->mutex);
  2912. tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
  2913. tor_assert(!smartlist_contains(cond->events, event));
  2914. smartlist_add(cond->events, event);
  2915. LeaveCriticalSection(&cond->mutex);
  2916. tor_mutex_release(mutex);
  2917. r = WaitForSingleObject(event, INFINITE);
  2918. tor_mutex_acquire(mutex);
  2919. switch (r) {
  2920. case WAIT_OBJECT_0: /* we got the mutex normally. */
  2921. break;
  2922. case WAIT_ABANDONED: /* holding thread exited. */
  2923. case WAIT_TIMEOUT: /* Should never happen. */
  2924. tor_assert(0);
  2925. break;
  2926. case WAIT_FAILED:
  2927. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  2928. }
  2929. return 0;
  2930. }
  2931. void
  2932. tor_cond_signal_one(tor_cond_t *cond)
  2933. {
  2934. HANDLE event;
  2935. tor_assert(cond);
  2936. EnterCriticalSection(&cond->mutex);
  2937. if ((event = smartlist_pop_last(cond->events)))
  2938. SetEvent(event);
  2939. LeaveCriticalSection(&cond->mutex);
  2940. }
  2941. void
  2942. tor_cond_signal_all(tor_cond_t *cond)
  2943. {
  2944. tor_assert(cond);
  2945. EnterCriticalSection(&cond->mutex);
  2946. SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
  2947. smartlist_clear(cond->events);
  2948. LeaveCriticalSection(&cond->mutex);
  2949. }
  2950. #endif
  2951. void
  2952. tor_threads_init(void)
  2953. {
  2954. #if 0
  2955. cond_event_tls_index = TlsAlloc();
  2956. #endif
  2957. set_main_thread();
  2958. }
  2959. #endif
  2960. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  2961. /** Attempt to raise the current and max rlimit to infinity for our process.
  2962. * This only needs to be done once and can probably only be done when we have
  2963. * not already dropped privileges.
  2964. */
  2965. static int
  2966. tor_set_max_memlock(void)
  2967. {
  2968. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  2969. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  2970. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  2971. */
  2972. struct rlimit limit;
  2973. /* RLIM_INFINITY is -1 on some platforms. */
  2974. limit.rlim_cur = RLIM_INFINITY;
  2975. limit.rlim_max = RLIM_INFINITY;
  2976. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  2977. if (errno == EPERM) {
  2978. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  2979. "limits. Are you root?");
  2980. }
  2981. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  2982. strerror(errno));
  2983. return -1;
  2984. }
  2985. return 0;
  2986. }
  2987. #endif
  2988. /** Attempt to lock all current and all future memory pages.
  2989. * This should only be called once and while we're privileged.
  2990. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  2991. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  2992. */
  2993. int
  2994. tor_mlockall(void)
  2995. {
  2996. static int memory_lock_attempted = 0;
  2997. if (memory_lock_attempted) {
  2998. return 1;
  2999. }
  3000. memory_lock_attempted = 1;
  3001. /*
  3002. * Future consideration for Windows may be VirtualLock
  3003. * VirtualLock appears to implement mlock() but not mlockall()
  3004. *
  3005. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  3006. */
  3007. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  3008. if (tor_set_max_memlock() == 0) {
  3009. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  3010. }
  3011. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  3012. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  3013. return 0;
  3014. } else {
  3015. if (errno == ENOSYS) {
  3016. /* Apple - it's 2009! I'm looking at you. Grrr. */
  3017. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  3018. "your platform.");
  3019. } else if (errno == EPERM) {
  3020. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  3021. "lock memory. Are you root?");
  3022. }
  3023. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  3024. "pages: %s", strerror(errno));
  3025. return -1;
  3026. }
  3027. #else
  3028. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  3029. return -1;
  3030. #endif
  3031. }
  3032. /** Identity of the "main" thread */
  3033. static unsigned long main_thread_id = -1;
  3034. /** Start considering the current thread to be the 'main thread'. This has
  3035. * no effect on anything besides in_main_thread(). */
  3036. void
  3037. set_main_thread(void)
  3038. {
  3039. main_thread_id = tor_get_thread_id();
  3040. }
  3041. /** Return true iff called from the main thread. */
  3042. int
  3043. in_main_thread(void)
  3044. {
  3045. return main_thread_id == tor_get_thread_id();
  3046. }
  3047. /**
  3048. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  3049. * you need to ask the socket for its actual errno. Also, you need to
  3050. * get your errors from WSAGetLastError, not errno. (If you supply a
  3051. * socket of -1, we check WSAGetLastError, but don't correct
  3052. * WSAEWOULDBLOCKs.)
  3053. *
  3054. * The upshot of all of this is that when a socket call fails, you
  3055. * should call tor_socket_errno <em>at most once</em> on the failing
  3056. * socket to get the error.
  3057. */
  3058. #if defined(_WIN32)
  3059. int
  3060. tor_socket_errno(tor_socket_t sock)
  3061. {
  3062. int optval, optvallen=sizeof(optval);
  3063. int err = WSAGetLastError();
  3064. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  3065. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  3066. return err;
  3067. if (optval)
  3068. return optval;
  3069. }
  3070. return err;
  3071. }
  3072. #endif
  3073. #if defined(_WIN32)
  3074. #define E(code, s) { code, (s " [" #code " ]") }
  3075. struct { int code; const char *msg; } windows_socket_errors[] = {
  3076. E(WSAEINTR, "Interrupted function call"),
  3077. E(WSAEACCES, "Permission denied"),
  3078. E(WSAEFAULT, "Bad address"),
  3079. E(WSAEINVAL, "Invalid argument"),
  3080. E(WSAEMFILE, "Too many open files"),
  3081. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  3082. E(WSAEINPROGRESS, "Operation now in progress"),
  3083. E(WSAEALREADY, "Operation already in progress"),
  3084. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  3085. E(WSAEDESTADDRREQ, "Destination address required"),
  3086. E(WSAEMSGSIZE, "Message too long"),
  3087. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  3088. E(WSAENOPROTOOPT, "Bad protocol option"),
  3089. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  3090. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  3091. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  3092. E(WSAEOPNOTSUPP, "Operation not supported"),
  3093. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  3094. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  3095. E(WSAEADDRINUSE, "Address already in use"),
  3096. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  3097. E(WSAENETDOWN, "Network is down"),
  3098. E(WSAENETUNREACH, "Network is unreachable"),
  3099. E(WSAENETRESET, "Network dropped connection on reset"),
  3100. E(WSAECONNABORTED, "Software caused connection abort"),
  3101. E(WSAECONNRESET, "Connection reset by peer"),
  3102. E(WSAENOBUFS, "No buffer space available"),
  3103. E(WSAEISCONN, "Socket is already connected"),
  3104. E(WSAENOTCONN, "Socket is not connected"),
  3105. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  3106. E(WSAETIMEDOUT, "Connection timed out"),
  3107. E(WSAECONNREFUSED, "Connection refused"),
  3108. E(WSAEHOSTDOWN, "Host is down"),
  3109. E(WSAEHOSTUNREACH, "No route to host"),
  3110. E(WSAEPROCLIM, "Too many processes"),
  3111. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  3112. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  3113. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  3114. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  3115. E(WSAEDISCON, "Graceful shutdown now in progress"),
  3116. #ifdef WSATYPE_NOT_FOUND
  3117. E(WSATYPE_NOT_FOUND, "Class type not found"),
  3118. #endif
  3119. E(WSAHOST_NOT_FOUND, "Host not found"),
  3120. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  3121. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  3122. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  3123. /* There are some more error codes whose numeric values are marked
  3124. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  3125. * reason that practitioners of some craft traditions deliberately
  3126. * introduce imperfections into their baskets and rugs "to allow the
  3127. * evil spirits to escape." If we catch them, then our binaries
  3128. * might not report consistent results across versions of Windows.
  3129. * Thus, I'm going to let them all fall through.
  3130. */
  3131. { -1, NULL },
  3132. };
  3133. /** There does not seem to be a strerror equivalent for Winsock errors.
  3134. * Naturally, we have to roll our own.
  3135. */
  3136. const char *
  3137. tor_socket_strerror(int e)
  3138. {
  3139. int i;
  3140. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  3141. if (e == windows_socket_errors[i].code)
  3142. return windows_socket_errors[i].msg;
  3143. }
  3144. return strerror(e);
  3145. }
  3146. #endif
  3147. /** Called before we make any calls to network-related functions.
  3148. * (Some operating systems require their network libraries to be
  3149. * initialized.) */
  3150. int
  3151. network_init(void)
  3152. {
  3153. #ifdef _WIN32
  3154. /* This silly exercise is necessary before windows will allow
  3155. * gethostbyname to work. */
  3156. WSADATA WSAData;
  3157. int r;
  3158. r = WSAStartup(0x101,&WSAData);
  3159. if (r) {
  3160. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  3161. return -1;
  3162. }
  3163. if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
  3164. log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
  3165. "might not work. (Sizes are %d and %d respectively.)",
  3166. (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
  3167. }
  3168. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  3169. * We might use it to complain if we're trying to be a server but have
  3170. * too few sockets available. */
  3171. #endif
  3172. return 0;
  3173. }
  3174. #ifdef _WIN32
  3175. /** Return a newly allocated string describing the windows system error code
  3176. * <b>err</b>. Note that error codes are different from errno. Error codes
  3177. * come from GetLastError() when a winapi call fails. errno is set only when
  3178. * ANSI functions fail. Whee. */
  3179. char *
  3180. format_win32_error(DWORD err)
  3181. {
  3182. TCHAR *str = NULL;
  3183. char *result;
  3184. DWORD n;
  3185. /* Somebody once decided that this interface was better than strerror(). */
  3186. n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  3187. FORMAT_MESSAGE_FROM_SYSTEM |
  3188. FORMAT_MESSAGE_IGNORE_INSERTS,
  3189. NULL, err,
  3190. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  3191. (LPVOID)&str,
  3192. 0, NULL);
  3193. if (str && n) {
  3194. #ifdef UNICODE
  3195. size_t len;
  3196. if (n > 128*1024)
  3197. len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
  3198. * make sure. */
  3199. else
  3200. len = n * 2 + 1;
  3201. result = tor_malloc(len);
  3202. wcstombs(result,str,len);
  3203. result[len-1] = '\0';
  3204. #else
  3205. result = tor_strdup(str);
  3206. #endif
  3207. } else {
  3208. result = tor_strdup("<unformattable error>");
  3209. }
  3210. if (str) {
  3211. LocalFree(str); /* LocalFree != free() */
  3212. }
  3213. return result;
  3214. }
  3215. #endif
  3216. #if defined(HW_PHYSMEM64)
  3217. /* This appears to be an OpenBSD thing */
  3218. #define INT64_HW_MEM HW_PHYSMEM64
  3219. #elif defined(HW_MEMSIZE)
  3220. /* OSX defines this one */
  3221. #define INT64_HW_MEM HW_MEMSIZE
  3222. #endif
  3223. /**
  3224. * Helper: try to detect the total system memory, and return it. On failure,
  3225. * return 0.
  3226. */
  3227. static uint64_t
  3228. get_total_system_memory_impl(void)
  3229. {
  3230. #if defined(__linux__)
  3231. /* On linux, sysctl is deprecated. Because proc is so awesome that you
  3232. * shouldn't _want_ to write portable code, I guess? */
  3233. unsigned long long result=0;
  3234. int fd = -1;
  3235. char *s = NULL;
  3236. const char *cp;
  3237. size_t file_size=0;
  3238. if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
  3239. return 0;
  3240. s = read_file_to_str_until_eof(fd, 65536, &file_size);
  3241. if (!s)
  3242. goto err;
  3243. cp = strstr(s, "MemTotal:");
  3244. if (!cp)
  3245. goto err;
  3246. /* Use the system sscanf so that space will match a wider number of space */
  3247. if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
  3248. goto err;
  3249. close(fd);
  3250. tor_free(s);
  3251. return result * 1024;
  3252. err:
  3253. tor_free(s);
  3254. close(fd);
  3255. return 0;
  3256. #elif defined (_WIN32)
  3257. /* Windows has MEMORYSTATUSEX; pretty straightforward. */
  3258. MEMORYSTATUSEX ms;
  3259. memset(&ms, 0, sizeof(ms));
  3260. ms.dwLength = sizeof(ms);
  3261. if (! GlobalMemoryStatusEx(&ms))
  3262. return 0;
  3263. return ms.ullTotalPhys;
  3264. #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
  3265. /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
  3266. * variant if we know about it. */
  3267. uint64_t memsize = 0;
  3268. size_t len = sizeof(memsize);
  3269. int mib[2] = {CTL_HW, INT64_HW_MEM};
  3270. if (sysctl(mib,2,&memsize,&len,NULL,0))
  3271. return 0;
  3272. return memsize;
  3273. #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
  3274. /* On some systems (like FreeBSD I hope) you can use a size_t with
  3275. * HW_PHYSMEM. */
  3276. size_t memsize=0;
  3277. size_t len = sizeof(memsize);
  3278. int mib[2] = {CTL_HW, HW_USERMEM};
  3279. if (sysctl(mib,2,&memsize,&len,NULL,0))
  3280. return -1;
  3281. return memsize;
  3282. #else
  3283. /* I have no clue. */
  3284. return 0;
  3285. #endif
  3286. }
  3287. /**
  3288. * Try to find out how much physical memory the system has. On success,
  3289. * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
  3290. */
  3291. int
  3292. get_total_system_memory(size_t *mem_out)
  3293. {
  3294. static size_t mem_cached=0;
  3295. uint64_t m = get_total_system_memory_impl();
  3296. if (0 == m) {
  3297. /* We couldn't find our memory total */
  3298. if (0 == mem_cached) {
  3299. /* We have no cached value either */
  3300. *mem_out = 0;
  3301. return -1;
  3302. }
  3303. *mem_out = mem_cached;
  3304. return 0;
  3305. }
  3306. #if SIZE_MAX != UINT64_MAX
  3307. if (m > SIZE_MAX) {
  3308. /* I think this could happen if we're a 32-bit Tor running on a 64-bit
  3309. * system: we could have more system memory than would fit in a
  3310. * size_t. */
  3311. m = SIZE_MAX;
  3312. }
  3313. #endif
  3314. *mem_out = mem_cached = (size_t) m;
  3315. return 0;
  3316. }
  3317. #ifdef TOR_UNIT_TESTS
  3318. /** Delay for <b>msec</b> milliseconds. Only used in tests. */
  3319. void
  3320. tor_sleep_msec(int msec)
  3321. {
  3322. #ifdef _WIN32
  3323. Sleep(msec);
  3324. #elif defined(HAVE_USLEEP)
  3325. sleep(msec / 1000);
  3326. /* Some usleep()s hate sleeping more than 1 sec */
  3327. usleep((msec % 1000) * 1000);
  3328. #elif defined(HAVE_SYS_SELECT_H)
  3329. struct timeval tv = { msec / 1000, (msec % 1000) * 1000};
  3330. select(0, NULL, NULL, NULL, &tv);
  3331. #else
  3332. sleep(CEIL_DIV(msec, 1000));
  3333. #endif
  3334. }
  3335. #endif