compat.c 98 KB

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