compat.c 102 KB

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