compat.c 102 KB

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