util.c 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017
  1. /* Copyright (c) 2003, 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 util.c
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control.
  9. **/
  10. #include "orconfig.h"
  11. #ifdef HAVE_FCNTL_H
  12. #include <fcntl.h>
  13. #endif
  14. #define UTIL_PRIVATE
  15. #include "common/util.h"
  16. #include "lib/log/torlog.h"
  17. #include "lib/crypt_ops/crypto_digest.h"
  18. #include "lib/cc/torint.h"
  19. #include "lib/container/smartlist.h"
  20. #include "lib/fdio/fdio.h"
  21. #include "common/address.h"
  22. #include "common/sandbox.h"
  23. #include "lib/err/backtrace.h"
  24. #include "common/util_process.h"
  25. #include "common/util_format.h"
  26. #ifdef _WIN32
  27. #include <io.h>
  28. #include <direct.h>
  29. #include <process.h>
  30. #include <tchar.h>
  31. #include <winbase.h>
  32. #else /* !(defined(_WIN32)) */
  33. #include <dirent.h>
  34. #include <pwd.h>
  35. #include <grp.h>
  36. #endif /* defined(_WIN32) */
  37. /* math.h needs this on Linux */
  38. #ifndef _USE_ISOC99_
  39. #define _USE_ISOC99_ 1
  40. #endif
  41. #include <math.h>
  42. #include <stdlib.h>
  43. #include <stdio.h>
  44. #include <string.h>
  45. #include <signal.h>
  46. #ifdef HAVE_NETINET_IN_H
  47. #include <netinet/in.h>
  48. #endif
  49. #ifdef HAVE_ARPA_INET_H
  50. #include <arpa/inet.h>
  51. #endif
  52. #ifdef HAVE_ERRNO_H
  53. #include <errno.h>
  54. #endif
  55. #ifdef HAVE_SYS_SOCKET_H
  56. #include <sys/socket.h>
  57. #endif
  58. #ifdef HAVE_SYS_TIME_H
  59. #include <sys/time.h>
  60. #endif
  61. #ifdef HAVE_UNISTD_H
  62. #include <unistd.h>
  63. #endif
  64. #ifdef HAVE_SYS_STAT_H
  65. #include <sys/stat.h>
  66. #endif
  67. #ifdef HAVE_SYS_FCNTL_H
  68. #include <sys/fcntl.h>
  69. #endif
  70. #ifdef HAVE_TIME_H
  71. #include <time.h>
  72. #endif
  73. #ifdef HAVE_MALLOC_MALLOC_H
  74. #include <malloc/malloc.h>
  75. #endif
  76. #ifdef HAVE_MALLOC_H
  77. #if !defined(OpenBSD) && !defined(__FreeBSD__)
  78. /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
  79. * scold us for being so stupid as to autodetect its presence. To be fair,
  80. * they've done this since 1996, when autoconf was only 5 years old. */
  81. #include <malloc.h>
  82. #endif /* !defined(OpenBSD) && !defined(__FreeBSD__) */
  83. #endif /* defined(HAVE_MALLOC_H) */
  84. #ifdef HAVE_MALLOC_NP_H
  85. #include <malloc_np.h>
  86. #endif
  87. #ifdef HAVE_SYS_WAIT_H
  88. #include <sys/wait.h>
  89. #endif
  90. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  91. #include <sys/prctl.h>
  92. #endif
  93. /* =====
  94. * Memory management
  95. * ===== */
  96. DISABLE_GCC_WARNING(aggregate-return)
  97. /** Call the platform malloc info function, and dump the results to the log at
  98. * level <b>severity</b>. If no such function exists, do nothing. */
  99. void
  100. tor_log_mallinfo(int severity)
  101. {
  102. #ifdef HAVE_MALLINFO
  103. struct mallinfo mi;
  104. memset(&mi, 0, sizeof(mi));
  105. mi = mallinfo();
  106. tor_log(severity, LD_MM,
  107. "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
  108. "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
  109. "keepcost=%d",
  110. mi.arena, mi.ordblks, mi.smblks, mi.hblks,
  111. mi.hblkhd, mi.usmblks, mi.fsmblks, mi.uordblks, mi.fordblks,
  112. mi.keepcost);
  113. #else /* !(defined(HAVE_MALLINFO)) */
  114. (void)severity;
  115. #endif /* defined(HAVE_MALLINFO) */
  116. }
  117. ENABLE_GCC_WARNING(aggregate-return)
  118. /* =====
  119. * Math
  120. * ===== */
  121. /**
  122. * Returns the natural logarithm of d base e. We defined this wrapper here so
  123. * to avoid conflicts with old versions of tor_log(), which were named log().
  124. */
  125. double
  126. tor_mathlog(double d)
  127. {
  128. return log(d);
  129. }
  130. /** Return the long integer closest to <b>d</b>. We define this wrapper
  131. * here so that not all users of math.h need to use the right incantations
  132. * to get the c99 functions. */
  133. long
  134. tor_lround(double d)
  135. {
  136. #if defined(HAVE_LROUND)
  137. return lround(d);
  138. #elif defined(HAVE_RINT)
  139. return (long)rint(d);
  140. #else
  141. return (long)(d > 0 ? d + 0.5 : ceil(d - 0.5));
  142. #endif /* defined(HAVE_LROUND) || ... */
  143. }
  144. /** Return the 64-bit integer closest to d. We define this wrapper here so
  145. * that not all users of math.h need to use the right incantations to get the
  146. * c99 functions. */
  147. int64_t
  148. tor_llround(double d)
  149. {
  150. #if defined(HAVE_LLROUND)
  151. return (int64_t)llround(d);
  152. #elif defined(HAVE_RINT)
  153. return (int64_t)rint(d);
  154. #else
  155. return (int64_t)(d > 0 ? d + 0.5 : ceil(d - 0.5));
  156. #endif /* defined(HAVE_LLROUND) || ... */
  157. }
  158. /** Transform a random value <b>p</b> from the uniform distribution in
  159. * [0.0, 1.0[ into a Laplace distributed value with location parameter
  160. * <b>mu</b> and scale parameter <b>b</b>. Truncate the final result
  161. * to be an integer in [INT64_MIN, INT64_MAX]. */
  162. int64_t
  163. sample_laplace_distribution(double mu, double b, double p)
  164. {
  165. double result;
  166. tor_assert(p >= 0.0 && p < 1.0);
  167. /* This is the "inverse cumulative distribution function" from:
  168. * http://en.wikipedia.org/wiki/Laplace_distribution */
  169. if (p <= 0.0) {
  170. /* Avoid taking log(0.0) == -INFINITY, as some processors or compiler
  171. * options can cause the program to trap. */
  172. return INT64_MIN;
  173. }
  174. result = mu - b * (p > 0.5 ? 1.0 : -1.0)
  175. * tor_mathlog(1.0 - 2.0 * fabs(p - 0.5));
  176. return clamp_double_to_int64(result);
  177. }
  178. /** Add random noise between INT64_MIN and INT64_MAX coming from a Laplace
  179. * distribution with mu = 0 and b = <b>delta_f</b>/<b>epsilon</b> to
  180. * <b>signal</b> based on the provided <b>random</b> value in [0.0, 1.0[.
  181. * The epsilon value must be between ]0.0, 1.0]. delta_f must be greater
  182. * than 0. */
  183. int64_t
  184. add_laplace_noise(int64_t signal_, double random_, double delta_f,
  185. double epsilon)
  186. {
  187. int64_t noise;
  188. /* epsilon MUST be between ]0.0, 1.0] */
  189. tor_assert(epsilon > 0.0 && epsilon <= 1.0);
  190. /* delta_f MUST be greater than 0. */
  191. tor_assert(delta_f > 0.0);
  192. /* Just add noise, no further signal */
  193. noise = sample_laplace_distribution(0.0,
  194. delta_f / epsilon,
  195. random_);
  196. /* Clip (signal + noise) to [INT64_MIN, INT64_MAX] */
  197. if (noise > 0 && INT64_MAX - noise < signal_)
  198. return INT64_MAX;
  199. else if (noise < 0 && INT64_MIN - noise > signal_)
  200. return INT64_MIN;
  201. else
  202. return signal_ + noise;
  203. }
  204. /* =====
  205. * String manipulation
  206. * ===== */
  207. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  208. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  209. * result does not need to be deallocated, but repeated calls to
  210. * hex_str will trash old results.
  211. */
  212. const char *
  213. hex_str(const char *from, size_t fromlen)
  214. {
  215. static char buf[65];
  216. if (fromlen>(sizeof(buf)-1)/2)
  217. fromlen = (sizeof(buf)-1)/2;
  218. base16_encode(buf,sizeof(buf),from,fromlen);
  219. return buf;
  220. }
  221. /** Compare the value of the string <b>prefix</b> with the start of the
  222. * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
  223. *
  224. * [As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is
  225. * less than strlen(prefix).]
  226. */
  227. int
  228. fast_memcmpstart(const void *mem, size_t memlen,
  229. const char *prefix)
  230. {
  231. size_t plen = strlen(prefix);
  232. if (memlen < plen)
  233. return -1;
  234. return fast_memcmp(mem, prefix, plen);
  235. }
  236. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  237. int
  238. tor_mem_is_zero(const char *mem, size_t len)
  239. {
  240. static const char ZERO[] = {
  241. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  242. };
  243. while (len >= sizeof(ZERO)) {
  244. /* It's safe to use fast_memcmp here, since the very worst thing an
  245. * attacker could learn is how many initial bytes of a secret were zero */
  246. if (fast_memcmp(mem, ZERO, sizeof(ZERO)))
  247. return 0;
  248. len -= sizeof(ZERO);
  249. mem += sizeof(ZERO);
  250. }
  251. /* Deal with leftover bytes. */
  252. if (len)
  253. return fast_memeq(mem, ZERO, len);
  254. return 1;
  255. }
  256. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  257. int
  258. tor_digest_is_zero(const char *digest)
  259. {
  260. static const uint8_t ZERO_DIGEST[] = {
  261. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
  262. };
  263. return tor_memeq(digest, ZERO_DIGEST, DIGEST_LEN);
  264. }
  265. /** Return true if <b>string</b> is a valid 'key=[value]' string.
  266. * "value" is optional, to indicate the empty string. Log at logging
  267. * <b>severity</b> if something ugly happens. */
  268. int
  269. string_is_key_value(int severity, const char *string)
  270. {
  271. /* position of equal sign in string */
  272. const char *equal_sign_pos = NULL;
  273. tor_assert(string);
  274. if (strlen(string) < 2) { /* "x=" is shortest args string */
  275. tor_log(severity, LD_GENERAL, "'%s' is too short to be a k=v value.",
  276. escaped(string));
  277. return 0;
  278. }
  279. equal_sign_pos = strchr(string, '=');
  280. if (!equal_sign_pos) {
  281. tor_log(severity, LD_GENERAL, "'%s' is not a k=v value.", escaped(string));
  282. return 0;
  283. }
  284. /* validate that the '=' is not in the beginning of the string. */
  285. if (equal_sign_pos == string) {
  286. tor_log(severity, LD_GENERAL, "'%s' is not a valid k=v value.",
  287. escaped(string));
  288. return 0;
  289. }
  290. return 1;
  291. }
  292. /** Return true if <b>string</b> represents a valid IPv4 adddress in
  293. * 'a.b.c.d' form.
  294. */
  295. int
  296. string_is_valid_ipv4_address(const char *string)
  297. {
  298. struct in_addr addr;
  299. return (tor_inet_pton(AF_INET,string,&addr) == 1);
  300. }
  301. /** Return true if <b>string</b> represents a valid IPv6 address in
  302. * a form that inet_pton() can parse.
  303. */
  304. int
  305. string_is_valid_ipv6_address(const char *string)
  306. {
  307. struct in6_addr addr;
  308. return (tor_inet_pton(AF_INET6,string,&addr) == 1);
  309. }
  310. /** Return true iff <b>string</b> is a valid destination address,
  311. * i.e. either a DNS hostname or IPv4/IPv6 address string.
  312. */
  313. int
  314. string_is_valid_dest(const char *string)
  315. {
  316. char *tmp = NULL;
  317. int retval;
  318. size_t len;
  319. if (string == NULL)
  320. return 0;
  321. len = strlen(string);
  322. if (len == 0)
  323. return 0;
  324. if (string[0] == '[' && string[len - 1] == ']')
  325. string = tmp = tor_strndup(string + 1, len - 2);
  326. retval = string_is_valid_ipv4_address(string) ||
  327. string_is_valid_ipv6_address(string) ||
  328. string_is_valid_nonrfc_hostname(string);
  329. tor_free(tmp);
  330. return retval;
  331. }
  332. /** Return true iff <b>string</b> matches a pattern of DNS names
  333. * that we allow Tor clients to connect to.
  334. *
  335. * Note: This allows certain technically invalid characters ('_') to cope
  336. * with misconfigured zones that have been encountered in the wild.
  337. */
  338. int
  339. string_is_valid_nonrfc_hostname(const char *string)
  340. {
  341. int result = 1;
  342. int has_trailing_dot;
  343. char *last_label;
  344. smartlist_t *components;
  345. if (!string || strlen(string) == 0)
  346. return 0;
  347. if (string_is_valid_ipv4_address(string))
  348. return 0;
  349. components = smartlist_new();
  350. smartlist_split_string(components,string,".",0,0);
  351. if (BUG(smartlist_len(components) == 0))
  352. return 0; // LCOV_EXCL_LINE should be impossible given the earlier checks.
  353. /* Allow a single terminating '.' used rarely to indicate domains
  354. * are FQDNs rather than relative. */
  355. last_label = (char *)smartlist_get(components,
  356. smartlist_len(components) - 1);
  357. has_trailing_dot = (last_label[0] == '\0');
  358. if (has_trailing_dot) {
  359. smartlist_pop_last(components);
  360. tor_free(last_label);
  361. last_label = NULL;
  362. }
  363. SMARTLIST_FOREACH_BEGIN(components, char *, c) {
  364. if ((c[0] == '-') || (*c == '_')) {
  365. result = 0;
  366. break;
  367. }
  368. do {
  369. result = (TOR_ISALNUM(*c) || (*c == '-') || (*c == '_'));
  370. c++;
  371. } while (result && *c);
  372. if (result == 0) {
  373. break;
  374. }
  375. } SMARTLIST_FOREACH_END(c);
  376. SMARTLIST_FOREACH_BEGIN(components, char *, c) {
  377. tor_free(c);
  378. } SMARTLIST_FOREACH_END(c);
  379. smartlist_free(components);
  380. return result;
  381. }
  382. /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
  383. int
  384. tor_digest256_is_zero(const char *digest)
  385. {
  386. return tor_mem_is_zero(digest, DIGEST256_LEN);
  387. }
  388. /* Helper: common code to check whether the result of a strtol or strtoul or
  389. * strtoll is correct. */
  390. #define CHECK_STRTOX_RESULT() \
  391. /* Did an overflow occur? */ \
  392. if (errno == ERANGE) \
  393. goto err; \
  394. /* Was at least one character converted? */ \
  395. if (endptr == s) \
  396. goto err; \
  397. /* Were there unexpected unconverted characters? */ \
  398. if (!next && *endptr) \
  399. goto err; \
  400. /* Illogical (max, min) inputs? */ \
  401. if (BUG(max < min)) \
  402. goto err; \
  403. /* Is r within limits? */ \
  404. if (r < min || r > max) \
  405. goto err; \
  406. if (ok) *ok = 1; \
  407. if (next) *next = endptr; \
  408. return r; \
  409. err: \
  410. if (ok) *ok = 0; \
  411. if (next) *next = endptr; \
  412. return 0
  413. /** Extract a long from the start of <b>s</b>, in the given numeric
  414. * <b>base</b>. If <b>base</b> is 0, <b>s</b> is parsed as a decimal,
  415. * octal, or hex number in the syntax of a C integer literal. If
  416. * there is unconverted data and <b>next</b> is provided, set
  417. * *<b>next</b> to the first unconverted character. An error has
  418. * occurred if no characters are converted; or if there are
  419. * unconverted characters and <b>next</b> is NULL; or if the parsed
  420. * value is not between <b>min</b> and <b>max</b>. When no error
  421. * occurs, return the parsed value and set *<b>ok</b> (if provided) to
  422. * 1. When an error occurs, return 0 and set *<b>ok</b> (if provided)
  423. * to 0.
  424. */
  425. long
  426. tor_parse_long(const char *s, int base, long min, long max,
  427. int *ok, char **next)
  428. {
  429. char *endptr;
  430. long r;
  431. if (BUG(base < 0)) {
  432. if (ok)
  433. *ok = 0;
  434. return 0;
  435. }
  436. errno = 0;
  437. r = strtol(s, &endptr, base);
  438. CHECK_STRTOX_RESULT();
  439. }
  440. /** As tor_parse_long(), but return an unsigned long. */
  441. unsigned long
  442. tor_parse_ulong(const char *s, int base, unsigned long min,
  443. unsigned long max, int *ok, char **next)
  444. {
  445. char *endptr;
  446. unsigned long r;
  447. if (BUG(base < 0)) {
  448. if (ok)
  449. *ok = 0;
  450. return 0;
  451. }
  452. errno = 0;
  453. r = strtoul(s, &endptr, base);
  454. CHECK_STRTOX_RESULT();
  455. }
  456. /** As tor_parse_long(), but return a double. */
  457. double
  458. tor_parse_double(const char *s, double min, double max, int *ok, char **next)
  459. {
  460. char *endptr;
  461. double r;
  462. errno = 0;
  463. r = strtod(s, &endptr);
  464. CHECK_STRTOX_RESULT();
  465. }
  466. /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
  467. * work for now. */
  468. uint64_t
  469. tor_parse_uint64(const char *s, int base, uint64_t min,
  470. uint64_t max, int *ok, char **next)
  471. {
  472. char *endptr;
  473. uint64_t r;
  474. if (BUG(base < 0)) {
  475. if (ok)
  476. *ok = 0;
  477. return 0;
  478. }
  479. errno = 0;
  480. #ifdef HAVE_STRTOULL
  481. r = (uint64_t)strtoull(s, &endptr, base);
  482. #elif defined(_WIN32)
  483. r = (uint64_t)_strtoui64(s, &endptr, base);
  484. #elif SIZEOF_LONG == 8
  485. r = (uint64_t)strtoul(s, &endptr, base);
  486. #else
  487. #error "I don't know how to parse 64-bit numbers."
  488. #endif /* defined(HAVE_STRTOULL) || ... */
  489. CHECK_STRTOX_RESULT();
  490. }
  491. /** Return a newly allocated string equal to <b>string</b>, except that every
  492. * character in <b>chars_to_escape</b> is preceded by a backslash. */
  493. char *
  494. tor_escape_str_for_pt_args(const char *string, const char *chars_to_escape)
  495. {
  496. char *new_string = NULL;
  497. char *new_cp = NULL;
  498. size_t length, new_length;
  499. tor_assert(string);
  500. length = strlen(string);
  501. if (!length) /* If we were given the empty string, return the same. */
  502. return tor_strdup("");
  503. /* (new_length > SIZE_MAX) => ((length * 2) + 1 > SIZE_MAX) =>
  504. (length*2 > SIZE_MAX - 1) => (length > (SIZE_MAX - 1)/2) */
  505. if (length > (SIZE_MAX - 1)/2) /* check for overflow */
  506. return NULL;
  507. /* this should be enough even if all characters must be escaped */
  508. new_length = (length * 2) + 1;
  509. new_string = new_cp = tor_malloc(new_length);
  510. while (*string) {
  511. if (strchr(chars_to_escape, *string))
  512. *new_cp++ = '\\';
  513. *new_cp++ = *string++;
  514. }
  515. *new_cp = '\0'; /* NUL-terminate the new string */
  516. return new_string;
  517. }
  518. /* =====
  519. * Time
  520. * ===== */
  521. #define TOR_USEC_PER_SEC 1000000
  522. /** Return the difference between start->tv_sec and end->tv_sec.
  523. * Returns INT64_MAX on overflow and underflow.
  524. */
  525. static int64_t
  526. tv_secdiff_impl(const struct timeval *start, const struct timeval *end)
  527. {
  528. const int64_t s = (int64_t)start->tv_sec;
  529. const int64_t e = (int64_t)end->tv_sec;
  530. /* This may not be the most efficient way of implemeting this check,
  531. * but it's easy to see that it's correct and doesn't overflow */
  532. if (s > 0 && e < INT64_MIN + s) {
  533. /* s is positive: equivalent to e - s < INT64_MIN, but without any
  534. * overflow */
  535. return INT64_MAX;
  536. } else if (s < 0 && e > INT64_MAX + s) {
  537. /* s is negative: equivalent to e - s > INT64_MAX, but without any
  538. * overflow */
  539. return INT64_MAX;
  540. }
  541. return e - s;
  542. }
  543. /** Return the number of microseconds elapsed between *start and *end.
  544. * Returns LONG_MAX on overflow and underflow.
  545. */
  546. long
  547. tv_udiff(const struct timeval *start, const struct timeval *end)
  548. {
  549. /* Sanity check tv_usec */
  550. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  551. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  552. "start tv_usec: " I64_FORMAT " microseconds",
  553. I64_PRINTF_ARG(start->tv_usec));
  554. return LONG_MAX;
  555. }
  556. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  557. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  558. "end tv_usec: " I64_FORMAT " microseconds",
  559. I64_PRINTF_ARG(end->tv_usec));
  560. return LONG_MAX;
  561. }
  562. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  563. */
  564. int64_t udiff;
  565. const int64_t secdiff = tv_secdiff_impl(start, end);
  566. /* end->tv_usec - start->tv_usec can be up to 1 second either way */
  567. if (secdiff > (int64_t)(LONG_MAX/1000000 - 1) ||
  568. secdiff < (int64_t)(LONG_MIN/1000000 + 1)) {
  569. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  570. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  571. return LONG_MAX;
  572. }
  573. /* we'll never get an overflow here, because we check that both usecs are
  574. * between 0 and TV_USEC_PER_SEC. */
  575. udiff = secdiff*1000000 + ((int64_t)end->tv_usec - (int64_t)start->tv_usec);
  576. /* Some compilers are smart enough to work out this is a no-op on L64 */
  577. #if SIZEOF_LONG < 8
  578. if (udiff > (int64_t)LONG_MAX || udiff < (int64_t)LONG_MIN) {
  579. return LONG_MAX;
  580. }
  581. #endif
  582. return (long)udiff;
  583. }
  584. /** Return the number of milliseconds elapsed between *start and *end.
  585. * If the tv_usec difference is 500, rounds away from zero.
  586. * Returns LONG_MAX on overflow and underflow.
  587. */
  588. long
  589. tv_mdiff(const struct timeval *start, const struct timeval *end)
  590. {
  591. /* Sanity check tv_usec */
  592. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  593. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  594. "start tv_usec: " I64_FORMAT " microseconds",
  595. I64_PRINTF_ARG(start->tv_usec));
  596. return LONG_MAX;
  597. }
  598. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  599. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  600. "end tv_usec: " I64_FORMAT " microseconds",
  601. I64_PRINTF_ARG(end->tv_usec));
  602. return LONG_MAX;
  603. }
  604. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  605. */
  606. int64_t mdiff;
  607. const int64_t secdiff = tv_secdiff_impl(start, end);
  608. /* end->tv_usec - start->tv_usec can be up to 1 second either way, but the
  609. * mdiff calculation may add another temporary second for rounding.
  610. * Whether this actually causes overflow depends on the compiler's constant
  611. * folding and order of operations. */
  612. if (secdiff > (int64_t)(LONG_MAX/1000 - 2) ||
  613. secdiff < (int64_t)(LONG_MIN/1000 + 1)) {
  614. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  615. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  616. return LONG_MAX;
  617. }
  618. /* Subtract and round */
  619. mdiff = secdiff*1000 +
  620. /* We add a million usec here to ensure that the result is positive,
  621. * so that the round-towards-zero behavior of the division will give
  622. * the right result for rounding to the nearest msec. Later we subtract
  623. * 1000 in order to get the correct result.
  624. * We'll never get an overflow here, because we check that both usecs are
  625. * between 0 and TV_USEC_PER_SEC. */
  626. ((int64_t)end->tv_usec - (int64_t)start->tv_usec + 500 + 1000000) / 1000
  627. - 1000;
  628. /* Some compilers are smart enough to work out this is a no-op on L64 */
  629. #if SIZEOF_LONG < 8
  630. if (mdiff > (int64_t)LONG_MAX || mdiff < (int64_t)LONG_MIN) {
  631. return LONG_MAX;
  632. }
  633. #endif
  634. return (long)mdiff;
  635. }
  636. /**
  637. * Converts timeval to milliseconds.
  638. */
  639. int64_t
  640. tv_to_msec(const struct timeval *tv)
  641. {
  642. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  643. /* Round ghetto-style */
  644. conv += ((int64_t)tv->tv_usec+500)/1000L;
  645. return conv;
  646. }
  647. /** Yield true iff <b>y</b> is a leap-year. */
  648. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  649. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  650. static int
  651. n_leapdays(int year1, int year2)
  652. {
  653. --year1;
  654. --year2;
  655. return (year2/4 - year1/4) - (year2/100 - year1/100)
  656. + (year2/400 - year1/400);
  657. }
  658. /** Number of days per month in non-leap year; used by tor_timegm and
  659. * parse_rfc1123_time. */
  660. static const int days_per_month[] =
  661. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  662. /** Compute a time_t given a struct tm. The result is given in UTC, and
  663. * does not account for leap seconds. Return 0 on success, -1 on failure.
  664. */
  665. int
  666. tor_timegm(const struct tm *tm, time_t *time_out)
  667. {
  668. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  669. * It's way more brute-force than fiddling with tzset().
  670. *
  671. * We use int64_t rather than time_t to avoid overflow on multiplication on
  672. * platforms with 32-bit time_t. Since year is clipped to INT32_MAX, and
  673. * since 365 * 24 * 60 * 60 is approximately 31 million, it's not possible
  674. * for INT32_MAX years to overflow int64_t when converted to seconds. */
  675. int64_t year, days, hours, minutes, seconds;
  676. int i, invalid_year, dpm;
  677. /* Initialize time_out to 0 for now, to avoid bad usage in case this function
  678. fails and the caller ignores the return value. */
  679. tor_assert(time_out);
  680. *time_out = 0;
  681. /* avoid int overflow on addition */
  682. if (tm->tm_year < INT32_MAX-1900) {
  683. year = tm->tm_year + 1900;
  684. } else {
  685. /* clamp year */
  686. year = INT32_MAX;
  687. }
  688. invalid_year = (year < 1970 || tm->tm_year >= INT32_MAX-1900);
  689. if (tm->tm_mon >= 0 && tm->tm_mon <= 11) {
  690. dpm = days_per_month[tm->tm_mon];
  691. if (tm->tm_mon == 1 && !invalid_year && IS_LEAPYEAR(tm->tm_year)) {
  692. dpm = 29;
  693. }
  694. } else {
  695. /* invalid month - default to 0 days per month */
  696. dpm = 0;
  697. }
  698. if (invalid_year ||
  699. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  700. tm->tm_mday < 1 || tm->tm_mday > dpm ||
  701. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  702. tm->tm_min < 0 || tm->tm_min > 59 ||
  703. tm->tm_sec < 0 || tm->tm_sec > 60) {
  704. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  705. return -1;
  706. }
  707. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  708. for (i = 0; i < tm->tm_mon; ++i)
  709. days += days_per_month[i];
  710. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  711. ++days;
  712. days += tm->tm_mday - 1;
  713. hours = days*24 + tm->tm_hour;
  714. minutes = hours*60 + tm->tm_min;
  715. seconds = minutes*60 + tm->tm_sec;
  716. /* Check that "seconds" will fit in a time_t. On platforms where time_t is
  717. * 32-bit, this check will fail for dates in and after 2038.
  718. *
  719. * We already know that "seconds" can't be negative because "year" >= 1970 */
  720. #if SIZEOF_TIME_T < 8
  721. if (seconds < TIME_MIN || seconds > TIME_MAX) {
  722. log_warn(LD_BUG, "Result does not fit in tor_timegm");
  723. return -1;
  724. }
  725. #endif /* SIZEOF_TIME_T < 8 */
  726. *time_out = (time_t)seconds;
  727. return 0;
  728. }
  729. /* strftime is locale-specific, so we need to replace those parts */
  730. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  731. static const char *WEEKDAY_NAMES[] =
  732. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  733. /** A c-locale array of 3-letter names of months, starting with Jan. */
  734. static const char *MONTH_NAMES[] =
  735. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  736. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  737. /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
  738. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  739. *
  740. * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
  741. * rather than "UTC".)
  742. */
  743. void
  744. format_rfc1123_time(char *buf, time_t t)
  745. {
  746. struct tm tm;
  747. tor_gmtime_r(&t, &tm);
  748. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  749. tor_assert(tm.tm_wday >= 0);
  750. tor_assert(tm.tm_wday <= 6);
  751. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  752. tor_assert(tm.tm_mon >= 0);
  753. tor_assert(tm.tm_mon <= 11);
  754. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  755. }
  756. /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
  757. * <b>buf</b>, and store the result in *<b>t</b>.
  758. *
  759. * Note that we only accept the subset generated by format_rfc1123_time above,
  760. * not the full range of formats suggested by RFC 1123.
  761. *
  762. * Return 0 on success, -1 on failure.
  763. */
  764. int
  765. parse_rfc1123_time(const char *buf, time_t *t)
  766. {
  767. struct tm tm;
  768. char month[4];
  769. char weekday[4];
  770. int i, m, invalid_year;
  771. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  772. unsigned dpm;
  773. if (strlen(buf) != RFC1123_TIME_LEN)
  774. return -1;
  775. memset(&tm, 0, sizeof(tm));
  776. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  777. &tm_mday, month, &tm_year, &tm_hour,
  778. &tm_min, &tm_sec) < 7) {
  779. char *esc = esc_for_log(buf);
  780. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  781. tor_free(esc);
  782. return -1;
  783. }
  784. m = -1;
  785. for (i = 0; i < 12; ++i) {
  786. if (!strcmp(month, MONTH_NAMES[i])) {
  787. m = i;
  788. break;
  789. }
  790. }
  791. if (m<0) {
  792. char *esc = esc_for_log(buf);
  793. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  794. tor_free(esc);
  795. return -1;
  796. }
  797. tm.tm_mon = m;
  798. invalid_year = (tm_year >= INT32_MAX || tm_year < 1970);
  799. tor_assert(m >= 0 && m <= 11);
  800. dpm = days_per_month[m];
  801. if (m == 1 && !invalid_year && IS_LEAPYEAR(tm_year)) {
  802. dpm = 29;
  803. }
  804. if (invalid_year || tm_mday < 1 || tm_mday > dpm ||
  805. tm_hour > 23 || tm_min > 59 || tm_sec > 60) {
  806. char *esc = esc_for_log(buf);
  807. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  808. tor_free(esc);
  809. return -1;
  810. }
  811. tm.tm_mday = (int)tm_mday;
  812. tm.tm_year = (int)tm_year;
  813. tm.tm_hour = (int)tm_hour;
  814. tm.tm_min = (int)tm_min;
  815. tm.tm_sec = (int)tm_sec;
  816. if (tm.tm_year < 1970) {
  817. /* LCOV_EXCL_START
  818. * XXXX I think this is dead code; we already checked for
  819. * invalid_year above. */
  820. tor_assert_nonfatal_unreached();
  821. char *esc = esc_for_log(buf);
  822. log_warn(LD_GENERAL,
  823. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  824. tor_free(esc);
  825. return -1;
  826. /* LCOV_EXCL_STOP */
  827. }
  828. tm.tm_year -= 1900;
  829. return tor_timegm(&tm, t);
  830. }
  831. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  832. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  833. *
  834. * (ISO8601 format is 2006-10-29 10:57:20)
  835. */
  836. void
  837. format_local_iso_time(char *buf, time_t t)
  838. {
  839. struct tm tm;
  840. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  841. }
  842. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  843. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  844. */
  845. void
  846. format_iso_time(char *buf, time_t t)
  847. {
  848. struct tm tm;
  849. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  850. }
  851. /** As format_local_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  852. * embedding an internal space. */
  853. void
  854. format_local_iso_time_nospace(char *buf, time_t t)
  855. {
  856. format_local_iso_time(buf, t);
  857. buf[10] = 'T';
  858. }
  859. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  860. * embedding an internal space. */
  861. void
  862. format_iso_time_nospace(char *buf, time_t t)
  863. {
  864. format_iso_time(buf, t);
  865. buf[10] = 'T';
  866. }
  867. /** As format_iso_time_nospace, but include microseconds in decimal
  868. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  869. * bytes long. */
  870. void
  871. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  872. {
  873. tor_assert(tv);
  874. format_iso_time_nospace(buf, (time_t)tv->tv_sec);
  875. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  876. }
  877. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  878. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  879. * failure. Ignore extraneous stuff in <b>cp</b> after the end of the time
  880. * string, unless <b>strict</b> is set. If <b>nospace</b> is set,
  881. * expect the YYYY-MM-DDTHH:MM:SS format. */
  882. int
  883. parse_iso_time_(const char *cp, time_t *t, int strict, int nospace)
  884. {
  885. struct tm st_tm;
  886. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  887. int n_fields;
  888. char extra_char, separator_char;
  889. n_fields = tor_sscanf(cp, "%u-%2u-%2u%c%2u:%2u:%2u%c",
  890. &year, &month, &day,
  891. &separator_char,
  892. &hour, &minute, &second, &extra_char);
  893. if (strict ? (n_fields != 7) : (n_fields < 7)) {
  894. char *esc = esc_for_log(cp);
  895. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  896. tor_free(esc);
  897. return -1;
  898. }
  899. if (separator_char != (nospace ? 'T' : ' ')) {
  900. char *esc = esc_for_log(cp);
  901. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  902. tor_free(esc);
  903. return -1;
  904. }
  905. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  906. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  907. char *esc = esc_for_log(cp);
  908. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  909. tor_free(esc);
  910. return -1;
  911. }
  912. st_tm.tm_year = (int)year-1900;
  913. st_tm.tm_mon = month-1;
  914. st_tm.tm_mday = day;
  915. st_tm.tm_hour = hour;
  916. st_tm.tm_min = minute;
  917. st_tm.tm_sec = second;
  918. st_tm.tm_wday = 0; /* Should be ignored. */
  919. if (st_tm.tm_year < 70) {
  920. /* LCOV_EXCL_START
  921. * XXXX I think this is dead code; we already checked for
  922. * year < 1970 above. */
  923. tor_assert_nonfatal_unreached();
  924. char *esc = esc_for_log(cp);
  925. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  926. tor_free(esc);
  927. return -1;
  928. /* LCOV_EXCL_STOP */
  929. }
  930. return tor_timegm(&st_tm, t);
  931. }
  932. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  933. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  934. * failure. Reject the string if any characters are present after the time.
  935. */
  936. int
  937. parse_iso_time(const char *cp, time_t *t)
  938. {
  939. return parse_iso_time_(cp, t, 1, 0);
  940. }
  941. /**
  942. * As parse_iso_time, but parses a time encoded by format_iso_time_nospace().
  943. */
  944. int
  945. parse_iso_time_nospace(const char *cp, time_t *t)
  946. {
  947. return parse_iso_time_(cp, t, 1, 1);
  948. }
  949. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  950. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  951. int
  952. parse_http_time(const char *date, struct tm *tm)
  953. {
  954. const char *cp;
  955. char month[4];
  956. char wkday[4];
  957. int i;
  958. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  959. tor_assert(tm);
  960. memset(tm, 0, sizeof(*tm));
  961. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  962. if ((cp = strchr(date, ','))) {
  963. ++cp;
  964. if (*cp != ' ')
  965. return -1;
  966. ++cp;
  967. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  968. &tm_mday, month, &tm_year,
  969. &tm_hour, &tm_min, &tm_sec) == 6) {
  970. /* rfc1123-date */
  971. tm_year -= 1900;
  972. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  973. &tm_mday, month, &tm_year,
  974. &tm_hour, &tm_min, &tm_sec) == 6) {
  975. /* rfc850-date */
  976. } else {
  977. return -1;
  978. }
  979. } else {
  980. /* No comma; possibly asctime() format. */
  981. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  982. wkday, month, &tm_mday,
  983. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  984. tm_year -= 1900;
  985. } else {
  986. return -1;
  987. }
  988. }
  989. tm->tm_mday = (int)tm_mday;
  990. tm->tm_year = (int)tm_year;
  991. tm->tm_hour = (int)tm_hour;
  992. tm->tm_min = (int)tm_min;
  993. tm->tm_sec = (int)tm_sec;
  994. tm->tm_wday = 0; /* Leave this unset. */
  995. month[3] = '\0';
  996. /* Okay, now decode the month. */
  997. /* set tm->tm_mon to dummy value so the check below fails. */
  998. tm->tm_mon = -1;
  999. for (i = 0; i < 12; ++i) {
  1000. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1001. tm->tm_mon = i;
  1002. }
  1003. }
  1004. if (tm->tm_year < 0 ||
  1005. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1006. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  1007. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1008. tm->tm_min < 0 || tm->tm_min > 59 ||
  1009. tm->tm_sec < 0 || tm->tm_sec > 60)
  1010. return -1; /* Out of range, or bad month. */
  1011. return 0;
  1012. }
  1013. /** Given an <b>interval</b> in seconds, try to write it to the
  1014. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1015. * Returns a non-negative integer on success, -1 on failure.
  1016. */
  1017. int
  1018. format_time_interval(char *out, size_t out_len, long interval)
  1019. {
  1020. /* We only report seconds if there's no hours. */
  1021. long sec = 0, min = 0, hour = 0, day = 0;
  1022. /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */
  1023. if (interval < -LONG_MAX)
  1024. interval = LONG_MAX;
  1025. else if (interval < 0)
  1026. interval = -interval;
  1027. if (interval >= 86400) {
  1028. day = interval / 86400;
  1029. interval %= 86400;
  1030. }
  1031. if (interval >= 3600) {
  1032. hour = interval / 3600;
  1033. interval %= 3600;
  1034. }
  1035. if (interval >= 60) {
  1036. min = interval / 60;
  1037. interval %= 60;
  1038. }
  1039. sec = interval;
  1040. if (day) {
  1041. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1042. day, hour, min);
  1043. } else if (hour) {
  1044. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1045. } else if (min) {
  1046. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1047. } else {
  1048. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1049. }
  1050. }
  1051. /* =====
  1052. * File helpers
  1053. * ===== */
  1054. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1055. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1056. * was returned by open(). Return the number of bytes written, or -1
  1057. * on error. Only use if fd is a blocking fd. */
  1058. ssize_t
  1059. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1060. {
  1061. size_t written = 0;
  1062. ssize_t result;
  1063. raw_assert(count < SSIZE_MAX);
  1064. while (written != count) {
  1065. if (isSocket)
  1066. result = tor_socket_send(fd, buf+written, count-written, 0);
  1067. else
  1068. result = write((int)fd, buf+written, count-written);
  1069. if (result<0)
  1070. return -1;
  1071. written += result;
  1072. }
  1073. return (ssize_t)count;
  1074. }
  1075. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1076. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1077. * was returned by socket() or accept(), and 0 if fd was returned by
  1078. * open(). Return the number of bytes read, or -1 on error. Only use
  1079. * if fd is a blocking fd. */
  1080. ssize_t
  1081. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1082. {
  1083. size_t numread = 0;
  1084. ssize_t result;
  1085. if (count > SIZE_T_CEILING || count > SSIZE_MAX) {
  1086. errno = EINVAL;
  1087. return -1;
  1088. }
  1089. while (numread < count) {
  1090. if (isSocket)
  1091. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1092. else
  1093. result = read((int)fd, buf+numread, count-numread);
  1094. if (result<0)
  1095. return -1;
  1096. else if (result == 0)
  1097. break;
  1098. numread += result;
  1099. }
  1100. return (ssize_t)numread;
  1101. }
  1102. /*
  1103. * Filesystem operations.
  1104. */
  1105. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1106. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1107. * the root of a disk. */
  1108. static void
  1109. clean_name_for_stat(char *name)
  1110. {
  1111. #ifdef _WIN32
  1112. size_t len = strlen(name);
  1113. if (!len)
  1114. return;
  1115. if (name[len-1]=='\\' || name[len-1]=='/') {
  1116. if (len == 1 || (len==3 && name[1]==':'))
  1117. return;
  1118. name[len-1]='\0';
  1119. }
  1120. #else /* !(defined(_WIN32)) */
  1121. (void)name;
  1122. #endif /* defined(_WIN32) */
  1123. }
  1124. /** Wrapper for unlink() to make it mockable for the test suite; returns 0
  1125. * if unlinking the file succeeded, -1 and sets errno if unlinking fails.
  1126. */
  1127. MOCK_IMPL(int,
  1128. tor_unlink,(const char *pathname))
  1129. {
  1130. return unlink(pathname);
  1131. }
  1132. /** Return:
  1133. * FN_ERROR if filename can't be read, is NULL, or is zero-length,
  1134. * FN_NOENT if it doesn't exist,
  1135. * FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems,
  1136. * FN_EMPTY for zero-byte regular files,
  1137. * FN_DIR if it's a directory, and
  1138. * FN_ERROR for any other file type.
  1139. * On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR
  1140. * is returned due to an unhandled file type.) */
  1141. file_status_t
  1142. file_status(const char *fname)
  1143. {
  1144. struct stat st;
  1145. char *f;
  1146. int r;
  1147. if (!fname || strlen(fname) == 0) {
  1148. return FN_ERROR;
  1149. }
  1150. f = tor_strdup(fname);
  1151. clean_name_for_stat(f);
  1152. log_debug(LD_FS, "stat()ing %s", f);
  1153. r = stat(sandbox_intern_string(f), &st);
  1154. tor_free(f);
  1155. if (r) {
  1156. if (errno == ENOENT) {
  1157. return FN_NOENT;
  1158. }
  1159. return FN_ERROR;
  1160. }
  1161. if (st.st_mode & S_IFDIR) {
  1162. return FN_DIR;
  1163. } else if (st.st_mode & S_IFREG) {
  1164. if (st.st_size > 0) {
  1165. return FN_FILE;
  1166. } else if (st.st_size == 0) {
  1167. return FN_EMPTY;
  1168. } else {
  1169. return FN_ERROR;
  1170. }
  1171. #ifndef _WIN32
  1172. } else if (st.st_mode & S_IFIFO) {
  1173. return FN_FILE;
  1174. #endif
  1175. } else {
  1176. return FN_ERROR;
  1177. }
  1178. }
  1179. /** Check whether <b>dirname</b> exists and is private. If yes return 0.
  1180. * If <b>dirname</b> does not exist:
  1181. * - if <b>check</b>&CPD_CREATE, try to create it and return 0 on success.
  1182. * - if <b>check</b>&CPD_CHECK, and we think we can create it, return 0.
  1183. * - if <b>check</b>&CPD_CHECK is false, and the directory exists, return 0.
  1184. * - otherwise, return -1.
  1185. * If CPD_GROUP_OK is set, then it's okay if the directory
  1186. * is group-readable, but in all cases we create the directory mode 0700.
  1187. * If CPD_GROUP_READ is set, existing directory behaves as CPD_GROUP_OK and
  1188. * if the directory is created it will use mode 0750 with group read
  1189. * permission. Group read privileges also assume execute permission
  1190. * as norm for directories. If CPD_CHECK_MODE_ONLY is set, then we don't
  1191. * alter the directory permissions if they are too permissive:
  1192. * we just return -1.
  1193. * When effective_user is not NULL, check permissions against the given user
  1194. * and its primary group.
  1195. */
  1196. MOCK_IMPL(int,
  1197. check_private_dir,(const char *dirname, cpd_check_t check,
  1198. const char *effective_user))
  1199. {
  1200. int r;
  1201. struct stat st;
  1202. tor_assert(dirname);
  1203. #ifndef _WIN32
  1204. int fd;
  1205. const struct passwd *pw = NULL;
  1206. uid_t running_uid;
  1207. gid_t running_gid;
  1208. /*
  1209. * Goal is to harden the implementation by removing any
  1210. * potential for race between stat() and chmod().
  1211. * chmod() accepts filename as argument. If an attacker can move
  1212. * the file between stat() and chmod(), a potential race exists.
  1213. *
  1214. * Several suggestions taken from:
  1215. * https://developer.apple.com/library/mac/documentation/
  1216. * Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html
  1217. */
  1218. /* Open directory.
  1219. * O_NOFOLLOW to ensure that it does not follow symbolic links */
  1220. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1221. /* Was there an error? Maybe the directory does not exist? */
  1222. if (fd == -1) {
  1223. if (errno != ENOENT) {
  1224. /* Other directory error */
  1225. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1226. strerror(errno));
  1227. return -1;
  1228. }
  1229. /* Received ENOENT: Directory does not exist */
  1230. /* Should we create the directory? */
  1231. if (check & CPD_CREATE) {
  1232. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1233. if (check & CPD_GROUP_READ) {
  1234. r = mkdir(dirname, 0750);
  1235. } else {
  1236. r = mkdir(dirname, 0700);
  1237. }
  1238. /* check for mkdir() error */
  1239. if (r) {
  1240. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1241. strerror(errno));
  1242. return -1;
  1243. }
  1244. /* we just created the directory. try to open it again.
  1245. * permissions on the directory will be checked again below.*/
  1246. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1247. if (fd == -1) {
  1248. log_warn(LD_FS, "Could not reopen recently created directory %s: %s",
  1249. dirname,
  1250. strerror(errno));
  1251. return -1;
  1252. } else {
  1253. close(fd);
  1254. }
  1255. } else if (!(check & CPD_CHECK)) {
  1256. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1257. return -1;
  1258. }
  1259. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1260. * parent directory a little harder. */
  1261. return 0;
  1262. }
  1263. tor_assert(fd >= 0);
  1264. //f = tor_strdup(dirname);
  1265. //clean_name_for_stat(f);
  1266. log_debug(LD_FS, "stat()ing %s", dirname);
  1267. //r = stat(sandbox_intern_string(f), &st);
  1268. r = fstat(fd, &st);
  1269. if (r == -1) {
  1270. log_warn(LD_FS, "fstat() on directory %s failed.", dirname);
  1271. close(fd);
  1272. return -1;
  1273. }
  1274. //tor_free(f);
  1275. /* check that dirname is a directory */
  1276. if (!(st.st_mode & S_IFDIR)) {
  1277. log_warn(LD_FS, "%s is not a directory", dirname);
  1278. close(fd);
  1279. return -1;
  1280. }
  1281. if (effective_user) {
  1282. /* Look up the user and group information.
  1283. * If we have a problem, bail out. */
  1284. pw = tor_getpwnam(effective_user);
  1285. if (pw == NULL) {
  1286. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1287. effective_user);
  1288. close(fd);
  1289. return -1;
  1290. }
  1291. running_uid = pw->pw_uid;
  1292. running_gid = pw->pw_gid;
  1293. } else {
  1294. running_uid = getuid();
  1295. running_gid = getgid();
  1296. }
  1297. if (st.st_uid != running_uid) {
  1298. char *process_ownername = NULL, *file_ownername = NULL;
  1299. {
  1300. const struct passwd *pw_running = tor_getpwuid(running_uid);
  1301. process_ownername = pw_running ? tor_strdup(pw_running->pw_name) :
  1302. tor_strdup("<unknown>");
  1303. }
  1304. {
  1305. const struct passwd *pw_stat = tor_getpwuid(st.st_uid);
  1306. file_ownername = pw_stat ? tor_strdup(pw_stat->pw_name) :
  1307. tor_strdup("<unknown>");
  1308. }
  1309. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1310. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1311. dirname, process_ownername, (int)running_uid,
  1312. file_ownername, (int)st.st_uid);
  1313. tor_free(process_ownername);
  1314. tor_free(file_ownername);
  1315. close(fd);
  1316. return -1;
  1317. }
  1318. if ( (check & (CPD_GROUP_OK|CPD_GROUP_READ))
  1319. && (st.st_gid != running_gid) && (st.st_gid != 0)) {
  1320. struct group *gr;
  1321. char *process_groupname = NULL;
  1322. gr = getgrgid(running_gid);
  1323. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1324. gr = getgrgid(st.st_gid);
  1325. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1326. "%s (%d). Are you running Tor as the wrong user?",
  1327. dirname, process_groupname, (int)running_gid,
  1328. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1329. tor_free(process_groupname);
  1330. close(fd);
  1331. return -1;
  1332. }
  1333. unsigned unwanted_bits = 0;
  1334. if (check & (CPD_GROUP_OK|CPD_GROUP_READ)) {
  1335. unwanted_bits = 0027;
  1336. } else {
  1337. unwanted_bits = 0077;
  1338. }
  1339. unsigned check_bits_filter = ~0;
  1340. if (check & CPD_RELAX_DIRMODE_CHECK) {
  1341. check_bits_filter = 0022;
  1342. }
  1343. if ((st.st_mode & unwanted_bits & check_bits_filter) != 0) {
  1344. unsigned new_mode;
  1345. if (check & CPD_CHECK_MODE_ONLY) {
  1346. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1347. dirname);
  1348. close(fd);
  1349. return -1;
  1350. }
  1351. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1352. new_mode = st.st_mode;
  1353. new_mode |= 0700; /* Owner should have rwx */
  1354. if (check & CPD_GROUP_READ) {
  1355. new_mode |= 0050; /* Group should have rx */
  1356. }
  1357. new_mode &= ~unwanted_bits; /* Clear the bits that we didn't want set...*/
  1358. if (fchmod(fd, new_mode)) {
  1359. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1360. strerror(errno));
  1361. close(fd);
  1362. return -1;
  1363. } else {
  1364. close(fd);
  1365. return 0;
  1366. }
  1367. }
  1368. close(fd);
  1369. #else /* !(!defined(_WIN32)) */
  1370. /* Win32 case: we can't open() a directory. */
  1371. (void)effective_user;
  1372. char *f = tor_strdup(dirname);
  1373. clean_name_for_stat(f);
  1374. log_debug(LD_FS, "stat()ing %s", f);
  1375. r = stat(sandbox_intern_string(f), &st);
  1376. tor_free(f);
  1377. if (r) {
  1378. if (errno != ENOENT) {
  1379. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1380. strerror(errno));
  1381. return -1;
  1382. }
  1383. if (check & CPD_CREATE) {
  1384. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1385. r = mkdir(dirname);
  1386. if (r) {
  1387. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1388. strerror(errno));
  1389. return -1;
  1390. }
  1391. } else if (!(check & CPD_CHECK)) {
  1392. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1393. return -1;
  1394. }
  1395. return 0;
  1396. }
  1397. if (!(st.st_mode & S_IFDIR)) {
  1398. log_warn(LD_FS, "%s is not a directory", dirname);
  1399. return -1;
  1400. }
  1401. #endif /* !defined(_WIN32) */
  1402. return 0;
  1403. }
  1404. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1405. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1406. *
  1407. * This function replaces the old file atomically, if possible. This
  1408. * function, and all other functions in util.c that create files, create them
  1409. * with mode 0600.
  1410. */
  1411. MOCK_IMPL(int,
  1412. write_str_to_file,(const char *fname, const char *str, int bin))
  1413. {
  1414. #ifdef _WIN32
  1415. if (!bin && strchr(str, '\r')) {
  1416. log_warn(LD_BUG,
  1417. "We're writing a text string that already contains a CR to %s",
  1418. escaped(fname));
  1419. }
  1420. #endif /* defined(_WIN32) */
  1421. return write_bytes_to_file(fname, str, strlen(str), bin);
  1422. }
  1423. /** Represents a file that we're writing to, with support for atomic commit:
  1424. * we can write into a temporary file, and either remove the file on
  1425. * failure, or replace the original file on success. */
  1426. struct open_file_t {
  1427. char *tempname; /**< Name of the temporary file. */
  1428. char *filename; /**< Name of the original file. */
  1429. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1430. unsigned binary:1; /**< Did we open in binary mode? */
  1431. int fd; /**< fd for the open file. */
  1432. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1433. };
  1434. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1435. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1436. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1437. * original file. Otherwise, we open a new temporary file in the same
  1438. * directory, and either replace the original or remove the temporary file
  1439. * when we're done.
  1440. *
  1441. * Return the fd for the newly opened file, and store working data in
  1442. * *<b>data_out</b>. The caller should not close the fd manually:
  1443. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1444. * Returns -1 on failure.
  1445. *
  1446. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1447. * as true and the flag O_EXCL is treated as false.
  1448. *
  1449. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1450. * write()". We don't do that.
  1451. */
  1452. int
  1453. start_writing_to_file(const char *fname, int open_flags, int mode,
  1454. open_file_t **data_out)
  1455. {
  1456. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1457. const char *open_name;
  1458. int append = 0;
  1459. tor_assert(fname);
  1460. tor_assert(data_out);
  1461. #if (O_BINARY != 0 && O_TEXT != 0)
  1462. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1463. #endif
  1464. new_file->fd = -1;
  1465. new_file->filename = tor_strdup(fname);
  1466. if (open_flags & O_APPEND) {
  1467. open_name = fname;
  1468. new_file->rename_on_close = 0;
  1469. append = 1;
  1470. open_flags &= ~O_APPEND;
  1471. } else {
  1472. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1473. open_name = new_file->tempname;
  1474. /* We always replace an existing temporary file if there is one. */
  1475. open_flags |= O_CREAT|O_TRUNC;
  1476. open_flags &= ~O_EXCL;
  1477. new_file->rename_on_close = 1;
  1478. }
  1479. #if O_BINARY != 0
  1480. if (open_flags & O_BINARY)
  1481. new_file->binary = 1;
  1482. #endif
  1483. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1484. if (new_file->fd < 0) {
  1485. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1486. open_name, fname, strerror(errno));
  1487. goto err;
  1488. }
  1489. if (append) {
  1490. if (tor_fd_seekend(new_file->fd) < 0) {
  1491. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1492. strerror(errno));
  1493. goto err;
  1494. }
  1495. }
  1496. *data_out = new_file;
  1497. return new_file->fd;
  1498. err:
  1499. if (new_file->fd >= 0)
  1500. close(new_file->fd);
  1501. *data_out = NULL;
  1502. tor_free(new_file->filename);
  1503. tor_free(new_file->tempname);
  1504. tor_free(new_file);
  1505. return -1;
  1506. }
  1507. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1508. * that can be used to write to the same file. The caller should not mix
  1509. * stdio calls with non-stdio calls. */
  1510. FILE *
  1511. fdopen_file(open_file_t *file_data)
  1512. {
  1513. tor_assert(file_data);
  1514. if (file_data->stdio_file)
  1515. return file_data->stdio_file;
  1516. tor_assert(file_data->fd >= 0);
  1517. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1518. file_data->binary?"ab":"a"))) {
  1519. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1520. file_data->fd, strerror(errno));
  1521. }
  1522. return file_data->stdio_file;
  1523. }
  1524. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1525. * for start_writing_to_file, but */
  1526. FILE *
  1527. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1528. open_file_t **data_out)
  1529. {
  1530. FILE *res;
  1531. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1532. return NULL;
  1533. if (!(res = fdopen_file(*data_out))) {
  1534. abort_writing_to_file(*data_out);
  1535. *data_out = NULL;
  1536. }
  1537. return res;
  1538. }
  1539. /** Helper function: close and free the underlying file and memory in
  1540. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1541. * that file (if abort_write is true) or replaces the target file with
  1542. * the temporary file (if abort_write is false). */
  1543. static int
  1544. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1545. {
  1546. int r = 0;
  1547. tor_assert(file_data && file_data->filename);
  1548. if (file_data->stdio_file) {
  1549. if (fclose(file_data->stdio_file)) {
  1550. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1551. strerror(errno));
  1552. abort_write = r = -1;
  1553. }
  1554. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1555. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1556. strerror(errno));
  1557. abort_write = r = -1;
  1558. }
  1559. if (file_data->rename_on_close) {
  1560. tor_assert(file_data->tempname && file_data->filename);
  1561. if (!abort_write) {
  1562. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1563. if (replace_file(file_data->tempname, file_data->filename)) {
  1564. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1565. strerror(errno));
  1566. abort_write = r = -1;
  1567. }
  1568. }
  1569. if (abort_write) {
  1570. int res = unlink(file_data->tempname);
  1571. if (res != 0) {
  1572. /* We couldn't unlink and we'll leave a mess behind */
  1573. log_warn(LD_FS, "Failed to unlink %s: %s",
  1574. file_data->tempname, strerror(errno));
  1575. r = -1;
  1576. }
  1577. }
  1578. }
  1579. tor_free(file_data->filename);
  1580. tor_free(file_data->tempname);
  1581. tor_free(file_data);
  1582. return r;
  1583. }
  1584. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1585. * needed, and if using a temporary file, replace the original file with
  1586. * the temporary file. */
  1587. int
  1588. finish_writing_to_file(open_file_t *file_data)
  1589. {
  1590. return finish_writing_to_file_impl(file_data, 0);
  1591. }
  1592. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1593. * needed, and if using a temporary file, delete it. */
  1594. int
  1595. abort_writing_to_file(open_file_t *file_data)
  1596. {
  1597. return finish_writing_to_file_impl(file_data, 1);
  1598. }
  1599. /** Helper: given a set of flags as passed to open(2), open the file
  1600. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1601. * the file. Do so as atomically as possible e.g. by opening temp files and
  1602. * renaming. */
  1603. static int
  1604. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1605. int open_flags)
  1606. {
  1607. open_file_t *file = NULL;
  1608. int fd;
  1609. ssize_t result;
  1610. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1611. if (fd<0)
  1612. return -1;
  1613. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1614. {
  1615. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1616. if (result < 0) {
  1617. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1618. strerror(errno));
  1619. goto err;
  1620. }
  1621. tor_assert((size_t)result == chunk->len);
  1622. });
  1623. return finish_writing_to_file(file);
  1624. err:
  1625. abort_writing_to_file(file);
  1626. return -1;
  1627. }
  1628. /** Given a smartlist of sized_chunk_t, write them to a file
  1629. * <b>fname</b>, overwriting or creating the file as necessary.
  1630. * If <b>no_tempfile</b> is 0 then the file will be written
  1631. * atomically. */
  1632. int
  1633. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin,
  1634. int no_tempfile)
  1635. {
  1636. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1637. if (no_tempfile) {
  1638. /* O_APPEND stops write_chunks_to_file from using tempfiles */
  1639. flags |= O_APPEND;
  1640. }
  1641. return write_chunks_to_file_impl(fname, chunks, flags);
  1642. }
  1643. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  1644. using the open() flags passed in <b>flags</b>. */
  1645. static int
  1646. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  1647. int flags)
  1648. {
  1649. int r;
  1650. sized_chunk_t c = { str, len };
  1651. smartlist_t *chunks = smartlist_new();
  1652. smartlist_add(chunks, &c);
  1653. r = write_chunks_to_file_impl(fname, chunks, flags);
  1654. smartlist_free(chunks);
  1655. return r;
  1656. }
  1657. /** As write_str_to_file, but does not assume a NUL-terminated
  1658. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1659. MOCK_IMPL(int,
  1660. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  1661. int bin))
  1662. {
  1663. return write_bytes_to_file_impl(fname, str, len,
  1664. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  1665. }
  1666. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1667. * to the end of the file instead of overwriting it. */
  1668. int
  1669. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1670. int bin)
  1671. {
  1672. return write_bytes_to_file_impl(fname, str, len,
  1673. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  1674. }
  1675. /** Like write_str_to_file(), but also return -1 if there was a file
  1676. already residing in <b>fname</b>. */
  1677. int
  1678. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  1679. int bin)
  1680. {
  1681. return write_bytes_to_file_impl(fname, str, len,
  1682. OPEN_FLAGS_DONT_REPLACE|
  1683. (bin?O_BINARY:O_TEXT));
  1684. }
  1685. /**
  1686. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  1687. * (or similar) file descriptor for which the size of the file isn't
  1688. * known ahead of time. Return NULL on failure, and a NUL-terminated
  1689. * string on success. On success, set <b>sz_out</b> to the number of
  1690. * bytes read.
  1691. */
  1692. char *
  1693. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  1694. {
  1695. ssize_t r;
  1696. size_t pos = 0;
  1697. char *string = NULL;
  1698. size_t string_max = 0;
  1699. if (max_bytes_to_read+1 >= SIZE_T_CEILING) {
  1700. errno = EINVAL;
  1701. return NULL;
  1702. }
  1703. do {
  1704. /* XXXX This "add 1K" approach is a little goofy; if we care about
  1705. * performance here, we should be doubling. But in practice we shouldn't
  1706. * be using this function on big files anyway. */
  1707. string_max = pos + 1024;
  1708. if (string_max > max_bytes_to_read)
  1709. string_max = max_bytes_to_read + 1;
  1710. string = tor_realloc(string, string_max);
  1711. r = read(fd, string + pos, string_max - pos - 1);
  1712. if (r < 0) {
  1713. int save_errno = errno;
  1714. tor_free(string);
  1715. errno = save_errno;
  1716. return NULL;
  1717. }
  1718. pos += r;
  1719. } while (r > 0 && pos < max_bytes_to_read);
  1720. tor_assert(pos < string_max);
  1721. *sz_out = pos;
  1722. string[pos] = '\0';
  1723. return string;
  1724. }
  1725. /** Read the contents of <b>filename</b> into a newly allocated
  1726. * string; return the string on success or NULL on failure.
  1727. *
  1728. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1729. * file into <b>stat_out</b>.
  1730. *
  1731. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1732. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1733. * doesn't exist.
  1734. */
  1735. /*
  1736. * This function <em>may</em> return an erroneous result if the file
  1737. * is modified while it is running, but must not crash or overflow.
  1738. * Right now, the error case occurs when the file length grows between
  1739. * the call to stat and the call to read_all: the resulting string will
  1740. * be truncated.
  1741. */
  1742. MOCK_IMPL(char *,
  1743. read_file_to_str, (const char *filename, int flags, struct stat *stat_out))
  1744. {
  1745. int fd; /* router file */
  1746. struct stat statbuf;
  1747. char *string;
  1748. ssize_t r;
  1749. int bin = flags & RFTS_BIN;
  1750. tor_assert(filename);
  1751. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1752. if (fd<0) {
  1753. int severity = LOG_WARN;
  1754. int save_errno = errno;
  1755. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1756. severity = LOG_INFO;
  1757. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  1758. strerror(errno));
  1759. errno = save_errno;
  1760. return NULL;
  1761. }
  1762. if (fstat(fd, &statbuf)<0) {
  1763. int save_errno = errno;
  1764. close(fd);
  1765. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1766. errno = save_errno;
  1767. return NULL;
  1768. }
  1769. #ifndef _WIN32
  1770. /** When we detect that we're reading from a FIFO, don't read more than
  1771. * this many bytes. It's insane overkill for most uses. */
  1772. #define FIFO_READ_MAX (1024*1024)
  1773. if (S_ISFIFO(statbuf.st_mode)) {
  1774. size_t sz = 0;
  1775. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  1776. int save_errno = errno;
  1777. if (string && stat_out) {
  1778. statbuf.st_size = sz;
  1779. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1780. }
  1781. close(fd);
  1782. if (!string)
  1783. errno = save_errno;
  1784. return string;
  1785. }
  1786. #endif /* !defined(_WIN32) */
  1787. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  1788. close(fd);
  1789. errno = EINVAL;
  1790. return NULL;
  1791. }
  1792. string = tor_malloc((size_t)(statbuf.st_size+1));
  1793. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1794. if (r<0) {
  1795. int save_errno = errno;
  1796. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1797. strerror(errno));
  1798. tor_free(string);
  1799. close(fd);
  1800. errno = save_errno;
  1801. return NULL;
  1802. }
  1803. string[r] = '\0'; /* NUL-terminate the result. */
  1804. #if defined(_WIN32) || defined(__CYGWIN__)
  1805. if (!bin && strchr(string, '\r')) {
  1806. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1807. "when reading %s. Coping.",
  1808. filename);
  1809. tor_strstrip(string, "\r");
  1810. r = strlen(string);
  1811. }
  1812. if (!bin) {
  1813. statbuf.st_size = (size_t) r;
  1814. } else
  1815. #endif /* defined(_WIN32) || defined(__CYGWIN__) */
  1816. if (r != statbuf.st_size) {
  1817. /* Unless we're using text mode on win32, we'd better have an exact
  1818. * match for size. */
  1819. int save_errno = errno;
  1820. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1821. (int)r, (long)statbuf.st_size,filename);
  1822. tor_free(string);
  1823. close(fd);
  1824. errno = save_errno;
  1825. return NULL;
  1826. }
  1827. close(fd);
  1828. if (stat_out) {
  1829. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1830. }
  1831. return string;
  1832. }
  1833. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  1834. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  1835. * decode its contents into a newly allocated string. On success, assign this
  1836. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  1837. * provided), and return a pointer to the position in <b>s</b> immediately
  1838. * after the string. On failure, return NULL.
  1839. */
  1840. const char *
  1841. unescape_string(const char *s, char **result, size_t *size_out)
  1842. {
  1843. const char *cp;
  1844. char *out;
  1845. if (s[0] != '\"')
  1846. return NULL;
  1847. cp = s+1;
  1848. while (1) {
  1849. switch (*cp) {
  1850. case '\0':
  1851. case '\n':
  1852. return NULL;
  1853. case '\"':
  1854. goto end_of_loop;
  1855. case '\\':
  1856. if (cp[1] == 'x' || cp[1] == 'X') {
  1857. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  1858. return NULL;
  1859. cp += 4;
  1860. } else if (TOR_ISODIGIT(cp[1])) {
  1861. cp += 2;
  1862. if (TOR_ISODIGIT(*cp)) ++cp;
  1863. if (TOR_ISODIGIT(*cp)) ++cp;
  1864. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  1865. || cp[1] == '\\' || cp[1] == '\'') {
  1866. cp += 2;
  1867. } else {
  1868. return NULL;
  1869. }
  1870. break;
  1871. default:
  1872. ++cp;
  1873. break;
  1874. }
  1875. }
  1876. end_of_loop:
  1877. out = *result = tor_malloc(cp-s + 1);
  1878. cp = s+1;
  1879. while (1) {
  1880. switch (*cp)
  1881. {
  1882. case '\"':
  1883. *out = '\0';
  1884. if (size_out) *size_out = out - *result;
  1885. return cp+1;
  1886. /* LCOV_EXCL_START -- we caught this in parse_config_from_line. */
  1887. case '\0':
  1888. tor_fragile_assert();
  1889. tor_free(*result);
  1890. return NULL;
  1891. /* LCOV_EXCL_STOP */
  1892. case '\\':
  1893. switch (cp[1])
  1894. {
  1895. case 'n': *out++ = '\n'; cp += 2; break;
  1896. case 'r': *out++ = '\r'; cp += 2; break;
  1897. case 't': *out++ = '\t'; cp += 2; break;
  1898. case 'x': case 'X':
  1899. {
  1900. int x1, x2;
  1901. x1 = hex_decode_digit(cp[2]);
  1902. x2 = hex_decode_digit(cp[3]);
  1903. if (x1 == -1 || x2 == -1) {
  1904. /* LCOV_EXCL_START */
  1905. /* we caught this above in the initial loop. */
  1906. tor_assert_nonfatal_unreached();
  1907. tor_free(*result);
  1908. return NULL;
  1909. /* LCOV_EXCL_STOP */
  1910. }
  1911. *out++ = ((x1<<4) + x2);
  1912. cp += 4;
  1913. }
  1914. break;
  1915. case '0': case '1': case '2': case '3': case '4': case '5':
  1916. case '6': case '7':
  1917. {
  1918. int n = cp[1]-'0';
  1919. cp += 2;
  1920. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  1921. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  1922. if (n > 255) { tor_free(*result); return NULL; }
  1923. *out++ = (char)n;
  1924. }
  1925. break;
  1926. case '\'':
  1927. case '\"':
  1928. case '\\':
  1929. case '\?':
  1930. *out++ = cp[1];
  1931. cp += 2;
  1932. break;
  1933. /* LCOV_EXCL_START */
  1934. default:
  1935. /* we caught this above in the initial loop. */
  1936. tor_assert_nonfatal_unreached();
  1937. tor_free(*result); return NULL;
  1938. /* LCOV_EXCL_STOP */
  1939. }
  1940. break;
  1941. default:
  1942. *out++ = *cp++;
  1943. }
  1944. }
  1945. }
  1946. /** Removes enclosing quotes from <b>path</b> and unescapes quotes between the
  1947. * enclosing quotes. Backslashes are not unescaped. Return the unquoted
  1948. * <b>path</b> on success or 0 if <b>path</b> is not quoted correctly. */
  1949. char *
  1950. get_unquoted_path(const char *path)
  1951. {
  1952. size_t len = strlen(path);
  1953. if (len == 0) {
  1954. return tor_strdup("");
  1955. }
  1956. int has_start_quote = (path[0] == '\"');
  1957. int has_end_quote = (len > 0 && path[len-1] == '\"');
  1958. if (has_start_quote != has_end_quote || (len == 1 && has_start_quote)) {
  1959. return NULL;
  1960. }
  1961. char *unquoted_path = tor_malloc(len - has_start_quote - has_end_quote + 1);
  1962. char *s = unquoted_path;
  1963. size_t i;
  1964. for (i = has_start_quote; i < len - has_end_quote; i++) {
  1965. if (path[i] == '\"' && (i > 0 && path[i-1] == '\\')) {
  1966. *(s-1) = path[i];
  1967. } else if (path[i] != '\"') {
  1968. *s++ = path[i];
  1969. } else { /* unescaped quote */
  1970. tor_free(unquoted_path);
  1971. return NULL;
  1972. }
  1973. }
  1974. *s = '\0';
  1975. return unquoted_path;
  1976. }
  1977. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  1978. * string. */
  1979. char *
  1980. expand_filename(const char *filename)
  1981. {
  1982. tor_assert(filename);
  1983. #ifdef _WIN32
  1984. /* Might consider using GetFullPathName() as described here:
  1985. * http://etutorials.org/Programming/secure+programming/
  1986. * Chapter+3.+Input+Validation/3.7+Validating+Filenames+and+Paths/
  1987. */
  1988. return tor_strdup(filename);
  1989. #else /* !(defined(_WIN32)) */
  1990. if (*filename == '~') {
  1991. char *home, *result=NULL;
  1992. const char *rest;
  1993. if (filename[1] == '/' || filename[1] == '\0') {
  1994. home = getenv("HOME");
  1995. if (!home) {
  1996. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  1997. "expanding \"%s\"; defaulting to \"\".", filename);
  1998. home = tor_strdup("");
  1999. } else {
  2000. home = tor_strdup(home);
  2001. }
  2002. rest = strlen(filename)>=2?(filename+2):"";
  2003. } else {
  2004. #ifdef HAVE_PWD_H
  2005. char *username, *slash;
  2006. slash = strchr(filename, '/');
  2007. if (slash)
  2008. username = tor_strndup(filename+1,slash-filename-1);
  2009. else
  2010. username = tor_strdup(filename+1);
  2011. if (!(home = get_user_homedir(username))) {
  2012. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2013. tor_free(username);
  2014. return NULL;
  2015. }
  2016. tor_free(username);
  2017. rest = slash ? (slash+1) : "";
  2018. #else /* !(defined(HAVE_PWD_H)) */
  2019. log_warn(LD_CONFIG, "Couldn't expand homedir on system without pwd.h");
  2020. return tor_strdup(filename);
  2021. #endif /* defined(HAVE_PWD_H) */
  2022. }
  2023. tor_assert(home);
  2024. /* Remove trailing slash. */
  2025. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2026. home[strlen(home)-1] = '\0';
  2027. }
  2028. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2029. tor_free(home);
  2030. return result;
  2031. } else {
  2032. return tor_strdup(filename);
  2033. }
  2034. #endif /* defined(_WIN32) */
  2035. }
  2036. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2037. * Return NULL on error or if <b>dirname</b> is not a directory.
  2038. */
  2039. MOCK_IMPL(smartlist_t *,
  2040. tor_listdir, (const char *dirname))
  2041. {
  2042. smartlist_t *result;
  2043. #ifdef _WIN32
  2044. char *pattern=NULL;
  2045. TCHAR tpattern[MAX_PATH] = {0};
  2046. char name[MAX_PATH*2+1] = {0};
  2047. HANDLE handle;
  2048. WIN32_FIND_DATA findData;
  2049. tor_asprintf(&pattern, "%s\\*", dirname);
  2050. #ifdef UNICODE
  2051. mbstowcs(tpattern,pattern,MAX_PATH);
  2052. #else
  2053. strlcpy(tpattern, pattern, MAX_PATH);
  2054. #endif
  2055. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2056. tor_free(pattern);
  2057. return NULL;
  2058. }
  2059. result = smartlist_new();
  2060. while (1) {
  2061. #ifdef UNICODE
  2062. wcstombs(name,findData.cFileName,MAX_PATH);
  2063. name[sizeof(name)-1] = '\0';
  2064. #else
  2065. strlcpy(name,findData.cFileName,sizeof(name));
  2066. #endif /* defined(UNICODE) */
  2067. if (strcmp(name, ".") &&
  2068. strcmp(name, "..")) {
  2069. smartlist_add_strdup(result, name);
  2070. }
  2071. if (!FindNextFile(handle, &findData)) {
  2072. DWORD err;
  2073. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2074. char *errstr = format_win32_error(err);
  2075. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2076. tor_free(errstr);
  2077. }
  2078. break;
  2079. }
  2080. }
  2081. FindClose(handle);
  2082. tor_free(pattern);
  2083. #else /* !(defined(_WIN32)) */
  2084. const char *prot_dname = sandbox_intern_string(dirname);
  2085. DIR *d;
  2086. struct dirent *de;
  2087. if (!(d = opendir(prot_dname)))
  2088. return NULL;
  2089. result = smartlist_new();
  2090. while ((de = readdir(d))) {
  2091. if (!strcmp(de->d_name, ".") ||
  2092. !strcmp(de->d_name, ".."))
  2093. continue;
  2094. smartlist_add_strdup(result, de->d_name);
  2095. }
  2096. closedir(d);
  2097. #endif /* defined(_WIN32) */
  2098. return result;
  2099. }
  2100. /** Return true iff <b>filename</b> is a relative path. */
  2101. int
  2102. path_is_relative(const char *filename)
  2103. {
  2104. if (filename && filename[0] == '/')
  2105. return 0;
  2106. #ifdef _WIN32
  2107. else if (filename && filename[0] == '\\')
  2108. return 0;
  2109. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2110. filename[1] == ':' && filename[2] == '\\')
  2111. return 0;
  2112. #endif /* defined(_WIN32) */
  2113. else
  2114. return 1;
  2115. }
  2116. /* =====
  2117. * Process helpers
  2118. * ===== */
  2119. #ifndef _WIN32
  2120. /* Based on code contributed by christian grothoff */
  2121. /** True iff we've called start_daemon(). */
  2122. static int start_daemon_called = 0;
  2123. /** True iff we've called finish_daemon(). */
  2124. static int finish_daemon_called = 0;
  2125. /** Socketpair used to communicate between parent and child process while
  2126. * daemonizing. */
  2127. static int daemon_filedes[2];
  2128. /** Start putting the process into daemon mode: fork and drop all resources
  2129. * except standard fds. The parent process never returns, but stays around
  2130. * until finish_daemon is called. (Note: it's safe to call this more
  2131. * than once: calls after the first are ignored.)
  2132. */
  2133. void
  2134. start_daemon(void)
  2135. {
  2136. pid_t pid;
  2137. if (start_daemon_called)
  2138. return;
  2139. start_daemon_called = 1;
  2140. if (pipe(daemon_filedes)) {
  2141. /* LCOV_EXCL_START */
  2142. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2143. exit(1); // exit ok: during daemonize, pipe failed.
  2144. /* LCOV_EXCL_STOP */
  2145. }
  2146. pid = fork();
  2147. if (pid < 0) {
  2148. /* LCOV_EXCL_START */
  2149. log_err(LD_GENERAL,"fork failed. Exiting.");
  2150. exit(1); // exit ok: during daemonize, fork failed
  2151. /* LCOV_EXCL_STOP */
  2152. }
  2153. if (pid) { /* Parent */
  2154. int ok;
  2155. char c;
  2156. close(daemon_filedes[1]); /* we only read */
  2157. ok = -1;
  2158. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2159. if (c == '.')
  2160. ok = 1;
  2161. }
  2162. fflush(stdout);
  2163. if (ok == 1)
  2164. exit(0); // exit ok: during daemonize, daemonizing.
  2165. else
  2166. exit(1); /* child reported error. exit ok: daemonize failed. */
  2167. } else { /* Child */
  2168. close(daemon_filedes[0]); /* we only write */
  2169. (void) setsid(); /* Detach from controlling terminal */
  2170. /*
  2171. * Fork one more time, so the parent (the session group leader) can exit.
  2172. * This means that we, as a non-session group leader, can never regain a
  2173. * controlling terminal. This part is recommended by Stevens's
  2174. * _Advanced Programming in the Unix Environment_.
  2175. */
  2176. if (fork() != 0) {
  2177. exit(0); // exit ok: during daemonize, fork failed (2)
  2178. }
  2179. set_main_thread(); /* We are now the main thread. */
  2180. return;
  2181. }
  2182. }
  2183. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2184. * the parent process to exit. (Note: it's safe to call this more than once:
  2185. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2186. * been called already.)
  2187. */
  2188. void
  2189. finish_daemon(const char *desired_cwd)
  2190. {
  2191. int nullfd;
  2192. char c = '.';
  2193. if (finish_daemon_called)
  2194. return;
  2195. if (!start_daemon_called)
  2196. start_daemon();
  2197. finish_daemon_called = 1;
  2198. if (!desired_cwd)
  2199. desired_cwd = "/";
  2200. /* Don't hold the wrong FS mounted */
  2201. if (chdir(desired_cwd) < 0) {
  2202. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2203. exit(1); // exit ok: during daemonize, chdir failed.
  2204. }
  2205. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2206. if (nullfd < 0) {
  2207. /* LCOV_EXCL_START */
  2208. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2209. exit(1); // exit ok: during daemonize, couldn't open /dev/null
  2210. /* LCOV_EXCL_STOP */
  2211. }
  2212. /* close fds linking to invoking terminal, but
  2213. * close usual incoming fds, but redirect them somewhere
  2214. * useful so the fds don't get reallocated elsewhere.
  2215. */
  2216. if (dup2(nullfd,0) < 0 ||
  2217. dup2(nullfd,1) < 0 ||
  2218. dup2(nullfd,2) < 0) {
  2219. /* LCOV_EXCL_START */
  2220. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2221. exit(1); // exit ok: during daemonize, dup2 failed.
  2222. /* LCOV_EXCL_STOP */
  2223. }
  2224. if (nullfd > 2)
  2225. close(nullfd);
  2226. /* signal success */
  2227. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2228. log_err(LD_GENERAL,"write failed. Exiting.");
  2229. }
  2230. close(daemon_filedes[1]);
  2231. }
  2232. #else /* !(!defined(_WIN32)) */
  2233. /* defined(_WIN32) */
  2234. void
  2235. start_daemon(void)
  2236. {
  2237. }
  2238. void
  2239. finish_daemon(const char *cp)
  2240. {
  2241. (void)cp;
  2242. }
  2243. #endif /* !defined(_WIN32) */
  2244. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2245. * Return 0 on success, -1 on failure.
  2246. */
  2247. int
  2248. write_pidfile(const char *filename)
  2249. {
  2250. FILE *pidfile;
  2251. if ((pidfile = fopen(filename, "w")) == NULL) {
  2252. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2253. strerror(errno));
  2254. return -1;
  2255. } else {
  2256. #ifdef _WIN32
  2257. int pid = (int)_getpid();
  2258. #else
  2259. int pid = (int)getpid();
  2260. #endif
  2261. int rv = 0;
  2262. if (fprintf(pidfile, "%d\n", pid) < 0)
  2263. rv = -1;
  2264. if (fclose(pidfile) < 0)
  2265. rv = -1;
  2266. return rv;
  2267. }
  2268. }
  2269. #ifdef _WIN32
  2270. HANDLE
  2271. load_windows_system_library(const TCHAR *library_name)
  2272. {
  2273. TCHAR path[MAX_PATH];
  2274. unsigned n;
  2275. n = GetSystemDirectory(path, MAX_PATH);
  2276. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2277. return 0;
  2278. _tcscat(path, TEXT("\\"));
  2279. _tcscat(path, library_name);
  2280. return LoadLibrary(path);
  2281. }
  2282. #endif /* defined(_WIN32) */
  2283. /** Format a single argument for being put on a Windows command line.
  2284. * Returns a newly allocated string */
  2285. static char *
  2286. format_win_cmdline_argument(const char *arg)
  2287. {
  2288. char *formatted_arg;
  2289. char need_quotes;
  2290. const char *c;
  2291. int i;
  2292. int bs_counter = 0;
  2293. /* Backslash we can point to when one is inserted into the string */
  2294. const char backslash = '\\';
  2295. /* Smartlist of *char */
  2296. smartlist_t *arg_chars;
  2297. arg_chars = smartlist_new();
  2298. /* Quote string if it contains whitespace or is empty */
  2299. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  2300. /* Build up smartlist of *chars */
  2301. for (c=arg; *c != '\0'; c++) {
  2302. if ('"' == *c) {
  2303. /* Double up backslashes preceding a quote */
  2304. for (i=0; i<(bs_counter*2); i++)
  2305. smartlist_add(arg_chars, (void*)&backslash);
  2306. bs_counter = 0;
  2307. /* Escape the quote */
  2308. smartlist_add(arg_chars, (void*)&backslash);
  2309. smartlist_add(arg_chars, (void*)c);
  2310. } else if ('\\' == *c) {
  2311. /* Count backslashes until we know whether to double up */
  2312. bs_counter++;
  2313. } else {
  2314. /* Don't double up slashes preceding a non-quote */
  2315. for (i=0; i<bs_counter; i++)
  2316. smartlist_add(arg_chars, (void*)&backslash);
  2317. bs_counter = 0;
  2318. smartlist_add(arg_chars, (void*)c);
  2319. }
  2320. }
  2321. /* Don't double up trailing backslashes */
  2322. for (i=0; i<bs_counter; i++)
  2323. smartlist_add(arg_chars, (void*)&backslash);
  2324. /* Allocate space for argument, quotes (if needed), and terminator */
  2325. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  2326. (need_quotes ? 2 : 0) + 1;
  2327. formatted_arg = tor_malloc_zero(formatted_arg_len);
  2328. /* Add leading quote */
  2329. i=0;
  2330. if (need_quotes)
  2331. formatted_arg[i++] = '"';
  2332. /* Add characters */
  2333. SMARTLIST_FOREACH(arg_chars, char*, ch,
  2334. {
  2335. formatted_arg[i++] = *ch;
  2336. });
  2337. /* Add trailing quote */
  2338. if (need_quotes)
  2339. formatted_arg[i++] = '"';
  2340. formatted_arg[i] = '\0';
  2341. smartlist_free(arg_chars);
  2342. return formatted_arg;
  2343. }
  2344. /** Format a command line for use on Windows, which takes the command as a
  2345. * string rather than string array. Follows the rules from "Parsing C++
  2346. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  2347. * Python subprocess module. Returns a newly allocated string */
  2348. char *
  2349. tor_join_win_cmdline(const char *argv[])
  2350. {
  2351. smartlist_t *argv_list;
  2352. char *joined_argv;
  2353. int i;
  2354. /* Format each argument and put the result in a smartlist */
  2355. argv_list = smartlist_new();
  2356. for (i=0; argv[i] != NULL; i++) {
  2357. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  2358. }
  2359. /* Join the arguments with whitespace */
  2360. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  2361. /* Free the newly allocated arguments, and the smartlist */
  2362. SMARTLIST_FOREACH(argv_list, char *, arg,
  2363. {
  2364. tor_free(arg);
  2365. });
  2366. smartlist_free(argv_list);
  2367. return joined_argv;
  2368. }
  2369. #ifndef _WIN32
  2370. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  2371. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  2372. * safe.
  2373. *
  2374. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  2375. *
  2376. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  2377. * with spaces. CHILD_STATE indicates where
  2378. * in the process of starting the child process did the failure occur (see
  2379. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  2380. * errno when the failure occurred.
  2381. *
  2382. * On success return the number of characters added to hex_errno, not counting
  2383. * the terminating NUL; return -1 on error.
  2384. */
  2385. STATIC int
  2386. format_helper_exit_status(unsigned char child_state, int saved_errno,
  2387. char *hex_errno)
  2388. {
  2389. unsigned int unsigned_errno;
  2390. int written, left;
  2391. char *cur;
  2392. size_t i;
  2393. int res = -1;
  2394. /* Fill hex_errno with spaces, and a trailing newline (memset may
  2395. not be signal handler safe, so we can't use it) */
  2396. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  2397. hex_errno[i] = ' ';
  2398. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  2399. /* Convert errno to be unsigned for hex conversion */
  2400. if (saved_errno < 0) {
  2401. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  2402. // by adding 1 to the signed int negative value,
  2403. // then, after it has been negated and cast to unsigned,
  2404. // adding the original 1 back (the double-addition is intentional).
  2405. // Otherwise, the cast to signed could cause a temporary int
  2406. // to equal INT_MAX + 1, which is undefined.
  2407. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  2408. } else {
  2409. unsigned_errno = (unsigned int) saved_errno;
  2410. }
  2411. /*
  2412. * Count how many chars of space we have left, and keep a pointer into the
  2413. * current point in the buffer.
  2414. */
  2415. left = HEX_ERRNO_SIZE+1;
  2416. cur = hex_errno;
  2417. /* Emit child_state */
  2418. written = format_hex_number_sigsafe(child_state, cur, left);
  2419. if (written <= 0)
  2420. goto err;
  2421. /* Adjust left and cur */
  2422. left -= written;
  2423. cur += written;
  2424. if (left <= 0)
  2425. goto err;
  2426. /* Now the '/' */
  2427. *cur = '/';
  2428. /* Adjust left and cur */
  2429. ++cur;
  2430. --left;
  2431. if (left <= 0)
  2432. goto err;
  2433. /* Need minus? */
  2434. if (saved_errno < 0) {
  2435. *cur = '-';
  2436. ++cur;
  2437. --left;
  2438. if (left <= 0)
  2439. goto err;
  2440. }
  2441. /* Emit unsigned_errno */
  2442. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  2443. if (written <= 0)
  2444. goto err;
  2445. /* Adjust left and cur */
  2446. left -= written;
  2447. cur += written;
  2448. /* Check that we have enough space left for a newline and a NUL */
  2449. if (left <= 1)
  2450. goto err;
  2451. /* Emit the newline and NUL */
  2452. *cur++ = '\n';
  2453. *cur++ = '\0';
  2454. res = (int)(cur - hex_errno - 1);
  2455. goto done;
  2456. err:
  2457. /*
  2458. * In error exit, just write a '\0' in the first char so whatever called
  2459. * this at least won't fall off the end.
  2460. */
  2461. *hex_errno = '\0';
  2462. done:
  2463. return res;
  2464. }
  2465. #endif /* !defined(_WIN32) */
  2466. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  2467. #define DEFAULT_MAX_FD 256
  2468. /** Terminate the process of <b>process_handle</b>, if that process has not
  2469. * already exited.
  2470. *
  2471. * Return 0 if we succeeded in terminating the process (or if the process
  2472. * already exited), and -1 if we tried to kill the process but failed.
  2473. *
  2474. * Based on code originally borrowed from Python's os.kill. */
  2475. int
  2476. tor_terminate_process(process_handle_t *process_handle)
  2477. {
  2478. #ifdef _WIN32
  2479. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  2480. HANDLE handle = process_handle->pid.hProcess;
  2481. if (!TerminateProcess(handle, 0))
  2482. return -1;
  2483. else
  2484. return 0;
  2485. }
  2486. #else /* !(defined(_WIN32)) */
  2487. if (process_handle->waitpid_cb) {
  2488. /* We haven't got a waitpid yet, so we can just kill off the process. */
  2489. return kill(process_handle->pid, SIGTERM);
  2490. }
  2491. #endif /* defined(_WIN32) */
  2492. return 0; /* We didn't need to kill the process, so report success */
  2493. }
  2494. /** Return the Process ID of <b>process_handle</b>. */
  2495. int
  2496. tor_process_get_pid(process_handle_t *process_handle)
  2497. {
  2498. #ifdef _WIN32
  2499. return (int) process_handle->pid.dwProcessId;
  2500. #else
  2501. return (int) process_handle->pid;
  2502. #endif
  2503. }
  2504. #ifdef _WIN32
  2505. HANDLE
  2506. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2507. {
  2508. return process_handle->stdout_pipe;
  2509. }
  2510. #else /* !(defined(_WIN32)) */
  2511. /* DOCDOC tor_process_get_stdout_pipe */
  2512. int
  2513. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2514. {
  2515. return process_handle->stdout_pipe;
  2516. }
  2517. #endif /* defined(_WIN32) */
  2518. /* DOCDOC process_handle_new */
  2519. static process_handle_t *
  2520. process_handle_new(void)
  2521. {
  2522. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  2523. #ifdef _WIN32
  2524. out->stdin_pipe = INVALID_HANDLE_VALUE;
  2525. out->stdout_pipe = INVALID_HANDLE_VALUE;
  2526. out->stderr_pipe = INVALID_HANDLE_VALUE;
  2527. #else
  2528. out->stdin_pipe = -1;
  2529. out->stdout_pipe = -1;
  2530. out->stderr_pipe = -1;
  2531. #endif /* defined(_WIN32) */
  2532. return out;
  2533. }
  2534. #ifndef _WIN32
  2535. /** Invoked when a process that we've launched via tor_spawn_background() has
  2536. * been found to have terminated.
  2537. */
  2538. static void
  2539. process_handle_waitpid_cb(int status, void *arg)
  2540. {
  2541. process_handle_t *process_handle = arg;
  2542. process_handle->waitpid_exit_status = status;
  2543. clear_waitpid_callback(process_handle->waitpid_cb);
  2544. if (process_handle->status == PROCESS_STATUS_RUNNING)
  2545. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  2546. process_handle->waitpid_cb = 0;
  2547. }
  2548. #endif /* !defined(_WIN32) */
  2549. /**
  2550. * @name child-process states
  2551. *
  2552. * Each of these values represents a possible state that a child process can
  2553. * be in. They're used to determine what to say when telling the parent how
  2554. * far along we were before failure.
  2555. *
  2556. * @{
  2557. */
  2558. #define CHILD_STATE_INIT 0
  2559. #define CHILD_STATE_PIPE 1
  2560. #define CHILD_STATE_MAXFD 2
  2561. #define CHILD_STATE_FORK 3
  2562. #define CHILD_STATE_DUPOUT 4
  2563. #define CHILD_STATE_DUPERR 5
  2564. #define CHILD_STATE_DUPIN 6
  2565. #define CHILD_STATE_CLOSEFD 7
  2566. #define CHILD_STATE_EXEC 8
  2567. #define CHILD_STATE_FAILEXEC 9
  2568. /** @} */
  2569. /**
  2570. * Boolean. If true, then Tor may call execve or CreateProcess via
  2571. * tor_spawn_background.
  2572. **/
  2573. static int may_spawn_background_process = 1;
  2574. /**
  2575. * Turn off may_spawn_background_process, so that all future calls to
  2576. * tor_spawn_background are guaranteed to fail.
  2577. **/
  2578. void
  2579. tor_disable_spawning_background_processes(void)
  2580. {
  2581. may_spawn_background_process = 0;
  2582. }
  2583. /** Start a program in the background. If <b>filename</b> contains a '/', then
  2584. * it will be treated as an absolute or relative path. Otherwise, on
  2585. * non-Windows systems, the system path will be searched for <b>filename</b>.
  2586. * On Windows, only the current directory will be searched. Here, to search the
  2587. * system path (as well as the application directory, current working
  2588. * directory, and system directories), set filename to NULL.
  2589. *
  2590. * The strings in <b>argv</b> will be passed as the command line arguments of
  2591. * the child program (following convention, argv[0] should normally be the
  2592. * filename of the executable, and this must be the case if <b>filename</b> is
  2593. * NULL). The last element of argv must be NULL. A handle to the child process
  2594. * will be returned in process_handle (which must be non-NULL). Read
  2595. * process_handle.status to find out if the process was successfully launched.
  2596. * For convenience, process_handle.status is returned by this function.
  2597. *
  2598. * Some parts of this code are based on the POSIX subprocess module from
  2599. * Python, and example code from
  2600. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  2601. */
  2602. int
  2603. tor_spawn_background(const char *const filename, const char **argv,
  2604. process_environment_t *env,
  2605. process_handle_t **process_handle_out)
  2606. {
  2607. if (BUG(may_spawn_background_process == 0)) {
  2608. /* We should never reach this point if we're forbidden to spawn
  2609. * processes. Instead we should have caught the attempt earlier. */
  2610. return PROCESS_STATUS_ERROR;
  2611. }
  2612. #ifdef _WIN32
  2613. HANDLE stdout_pipe_read = NULL;
  2614. HANDLE stdout_pipe_write = NULL;
  2615. HANDLE stderr_pipe_read = NULL;
  2616. HANDLE stderr_pipe_write = NULL;
  2617. HANDLE stdin_pipe_read = NULL;
  2618. HANDLE stdin_pipe_write = NULL;
  2619. process_handle_t *process_handle;
  2620. int status;
  2621. STARTUPINFOA siStartInfo;
  2622. BOOL retval = FALSE;
  2623. SECURITY_ATTRIBUTES saAttr;
  2624. char *joined_argv;
  2625. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  2626. saAttr.bInheritHandle = TRUE;
  2627. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  2628. saAttr.lpSecurityDescriptor = NULL;
  2629. /* Assume failure to start process */
  2630. status = PROCESS_STATUS_ERROR;
  2631. /* Set up pipe for stdout */
  2632. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  2633. log_warn(LD_GENERAL,
  2634. "Failed to create pipe for stdout communication with child process: %s",
  2635. format_win32_error(GetLastError()));
  2636. return status;
  2637. }
  2638. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  2639. log_warn(LD_GENERAL,
  2640. "Failed to configure pipe for stdout communication with child "
  2641. "process: %s", format_win32_error(GetLastError()));
  2642. return status;
  2643. }
  2644. /* Set up pipe for stderr */
  2645. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  2646. log_warn(LD_GENERAL,
  2647. "Failed to create pipe for stderr communication with child process: %s",
  2648. format_win32_error(GetLastError()));
  2649. return status;
  2650. }
  2651. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  2652. log_warn(LD_GENERAL,
  2653. "Failed to configure pipe for stderr communication with child "
  2654. "process: %s", format_win32_error(GetLastError()));
  2655. return status;
  2656. }
  2657. /* Set up pipe for stdin */
  2658. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  2659. log_warn(LD_GENERAL,
  2660. "Failed to create pipe for stdin communication with child process: %s",
  2661. format_win32_error(GetLastError()));
  2662. return status;
  2663. }
  2664. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  2665. log_warn(LD_GENERAL,
  2666. "Failed to configure pipe for stdin communication with child "
  2667. "process: %s", format_win32_error(GetLastError()));
  2668. return status;
  2669. }
  2670. /* Create the child process */
  2671. /* Windows expects argv to be a whitespace delimited string, so join argv up
  2672. */
  2673. joined_argv = tor_join_win_cmdline(argv);
  2674. process_handle = process_handle_new();
  2675. process_handle->status = status;
  2676. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  2677. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  2678. siStartInfo.cb = sizeof(STARTUPINFO);
  2679. siStartInfo.hStdError = stderr_pipe_write;
  2680. siStartInfo.hStdOutput = stdout_pipe_write;
  2681. siStartInfo.hStdInput = stdin_pipe_read;
  2682. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  2683. /* Create the child process */
  2684. retval = CreateProcessA(filename, // module name
  2685. joined_argv, // command line
  2686. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  2687. NULL, // process security attributes
  2688. NULL, // primary thread security attributes
  2689. TRUE, // handles are inherited
  2690. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  2691. * work?) */
  2692. CREATE_NO_WINDOW, // creation flags
  2693. (env==NULL) ? NULL : env->windows_environment_block,
  2694. NULL, // use parent's current directory
  2695. &siStartInfo, // STARTUPINFO pointer
  2696. &(process_handle->pid)); // receives PROCESS_INFORMATION
  2697. tor_free(joined_argv);
  2698. if (!retval) {
  2699. log_warn(LD_GENERAL,
  2700. "Failed to create child process %s: %s", filename?filename:argv[0],
  2701. format_win32_error(GetLastError()));
  2702. tor_free(process_handle);
  2703. } else {
  2704. /* TODO: Close hProcess and hThread in process_handle->pid? */
  2705. process_handle->stdout_pipe = stdout_pipe_read;
  2706. process_handle->stderr_pipe = stderr_pipe_read;
  2707. process_handle->stdin_pipe = stdin_pipe_write;
  2708. status = process_handle->status = PROCESS_STATUS_RUNNING;
  2709. }
  2710. /* TODO: Close pipes on exit */
  2711. *process_handle_out = process_handle;
  2712. return status;
  2713. #else /* !(defined(_WIN32)) */
  2714. pid_t pid;
  2715. int stdout_pipe[2];
  2716. int stderr_pipe[2];
  2717. int stdin_pipe[2];
  2718. int fd, retval;
  2719. process_handle_t *process_handle;
  2720. int status;
  2721. const char *error_message = SPAWN_ERROR_MESSAGE;
  2722. size_t error_message_length;
  2723. /* Represents where in the process of spawning the program is;
  2724. this is used for printing out the error message */
  2725. unsigned char child_state = CHILD_STATE_INIT;
  2726. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  2727. static int max_fd = -1;
  2728. status = PROCESS_STATUS_ERROR;
  2729. /* We do the strlen here because strlen() is not signal handler safe,
  2730. and we are not allowed to use unsafe functions between fork and exec */
  2731. error_message_length = strlen(error_message);
  2732. // child_state = CHILD_STATE_PIPE;
  2733. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  2734. retval = pipe(stdout_pipe);
  2735. if (-1 == retval) {
  2736. log_warn(LD_GENERAL,
  2737. "Failed to set up pipe for stdout communication with child process: %s",
  2738. strerror(errno));
  2739. return status;
  2740. }
  2741. retval = pipe(stderr_pipe);
  2742. if (-1 == retval) {
  2743. log_warn(LD_GENERAL,
  2744. "Failed to set up pipe for stderr communication with child process: %s",
  2745. strerror(errno));
  2746. close(stdout_pipe[0]);
  2747. close(stdout_pipe[1]);
  2748. return status;
  2749. }
  2750. retval = pipe(stdin_pipe);
  2751. if (-1 == retval) {
  2752. log_warn(LD_GENERAL,
  2753. "Failed to set up pipe for stdin communication with child process: %s",
  2754. strerror(errno));
  2755. close(stdout_pipe[0]);
  2756. close(stdout_pipe[1]);
  2757. close(stderr_pipe[0]);
  2758. close(stderr_pipe[1]);
  2759. return status;
  2760. }
  2761. // child_state = CHILD_STATE_MAXFD;
  2762. #ifdef _SC_OPEN_MAX
  2763. if (-1 == max_fd) {
  2764. max_fd = (int) sysconf(_SC_OPEN_MAX);
  2765. if (max_fd == -1) {
  2766. max_fd = DEFAULT_MAX_FD;
  2767. log_warn(LD_GENERAL,
  2768. "Cannot find maximum file descriptor, assuming %d", max_fd);
  2769. }
  2770. }
  2771. #else /* !(defined(_SC_OPEN_MAX)) */
  2772. max_fd = DEFAULT_MAX_FD;
  2773. #endif /* defined(_SC_OPEN_MAX) */
  2774. // child_state = CHILD_STATE_FORK;
  2775. pid = fork();
  2776. if (0 == pid) {
  2777. /* In child */
  2778. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  2779. /* Attempt to have the kernel issue a SIGTERM if the parent
  2780. * goes away. Certain attributes of the binary being execve()ed
  2781. * will clear this during the execve() call, but it's better
  2782. * than nothing.
  2783. */
  2784. prctl(PR_SET_PDEATHSIG, SIGTERM);
  2785. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  2786. child_state = CHILD_STATE_DUPOUT;
  2787. /* Link child stdout to the write end of the pipe */
  2788. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  2789. if (-1 == retval)
  2790. goto error;
  2791. child_state = CHILD_STATE_DUPERR;
  2792. /* Link child stderr to the write end of the pipe */
  2793. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  2794. if (-1 == retval)
  2795. goto error;
  2796. child_state = CHILD_STATE_DUPIN;
  2797. /* Link child stdin to the read end of the pipe */
  2798. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  2799. if (-1 == retval)
  2800. goto error;
  2801. // child_state = CHILD_STATE_CLOSEFD;
  2802. close(stderr_pipe[0]);
  2803. close(stderr_pipe[1]);
  2804. close(stdout_pipe[0]);
  2805. close(stdout_pipe[1]);
  2806. close(stdin_pipe[0]);
  2807. close(stdin_pipe[1]);
  2808. /* Close all other fds, including the read end of the pipe */
  2809. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  2810. * this needless. */
  2811. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  2812. close(fd);
  2813. }
  2814. // child_state = CHILD_STATE_EXEC;
  2815. /* Call the requested program. We need the cast because
  2816. execvp doesn't define argv as const, even though it
  2817. does not modify the arguments */
  2818. if (env)
  2819. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  2820. else {
  2821. static char *new_env[] = { NULL };
  2822. execve(filename, (char *const *) argv, new_env);
  2823. }
  2824. /* If we got here, the exec or open(/dev/null) failed */
  2825. child_state = CHILD_STATE_FAILEXEC;
  2826. error:
  2827. {
  2828. /* XXX: are we leaking fds from the pipe? */
  2829. int n, err=0;
  2830. ssize_t nbytes;
  2831. n = format_helper_exit_status(child_state, errno, hex_errno);
  2832. if (n >= 0) {
  2833. /* Write the error message. GCC requires that we check the return
  2834. value, but there is nothing we can do if it fails */
  2835. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  2836. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  2837. err = (nbytes < 0);
  2838. nbytes = write(STDOUT_FILENO, hex_errno, n);
  2839. err += (nbytes < 0);
  2840. }
  2841. _exit(err?254:255); // exit ok: in child.
  2842. }
  2843. /* Never reached, but avoids compiler warning */
  2844. return status; // LCOV_EXCL_LINE
  2845. }
  2846. /* In parent */
  2847. if (-1 == pid) {
  2848. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  2849. close(stdin_pipe[0]);
  2850. close(stdin_pipe[1]);
  2851. close(stdout_pipe[0]);
  2852. close(stdout_pipe[1]);
  2853. close(stderr_pipe[0]);
  2854. close(stderr_pipe[1]);
  2855. return status;
  2856. }
  2857. process_handle = process_handle_new();
  2858. process_handle->status = status;
  2859. process_handle->pid = pid;
  2860. /* TODO: If the child process forked but failed to exec, waitpid it */
  2861. /* Return read end of the pipes to caller, and close write end */
  2862. process_handle->stdout_pipe = stdout_pipe[0];
  2863. retval = close(stdout_pipe[1]);
  2864. if (-1 == retval) {
  2865. log_warn(LD_GENERAL,
  2866. "Failed to close write end of stdout pipe in parent process: %s",
  2867. strerror(errno));
  2868. }
  2869. process_handle->waitpid_cb = set_waitpid_callback(pid,
  2870. process_handle_waitpid_cb,
  2871. process_handle);
  2872. process_handle->stderr_pipe = stderr_pipe[0];
  2873. retval = close(stderr_pipe[1]);
  2874. if (-1 == retval) {
  2875. log_warn(LD_GENERAL,
  2876. "Failed to close write end of stderr pipe in parent process: %s",
  2877. strerror(errno));
  2878. }
  2879. /* Return write end of the stdin pipe to caller, and close the read end */
  2880. process_handle->stdin_pipe = stdin_pipe[1];
  2881. retval = close(stdin_pipe[0]);
  2882. if (-1 == retval) {
  2883. log_warn(LD_GENERAL,
  2884. "Failed to close read end of stdin pipe in parent process: %s",
  2885. strerror(errno));
  2886. }
  2887. status = process_handle->status = PROCESS_STATUS_RUNNING;
  2888. /* Set stdin/stdout/stderr pipes to be non-blocking */
  2889. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  2890. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  2891. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  2892. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  2893. "nonblocking in parent process: %s", strerror(errno));
  2894. }
  2895. *process_handle_out = process_handle;
  2896. return status;
  2897. #endif /* defined(_WIN32) */
  2898. }
  2899. /** Destroy all resources allocated by the process handle in
  2900. * <b>process_handle</b>.
  2901. * If <b>also_terminate_process</b> is true, also terminate the
  2902. * process of the process handle. */
  2903. MOCK_IMPL(void,
  2904. tor_process_handle_destroy,(process_handle_t *process_handle,
  2905. int also_terminate_process))
  2906. {
  2907. if (!process_handle)
  2908. return;
  2909. if (also_terminate_process) {
  2910. if (tor_terminate_process(process_handle) < 0) {
  2911. const char *errstr =
  2912. #ifdef _WIN32
  2913. format_win32_error(GetLastError());
  2914. #else
  2915. strerror(errno);
  2916. #endif
  2917. log_notice(LD_GENERAL, "Failed to terminate process with "
  2918. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  2919. errstr);
  2920. } else {
  2921. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  2922. tor_process_get_pid(process_handle));
  2923. }
  2924. }
  2925. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  2926. #ifdef _WIN32
  2927. if (process_handle->stdout_pipe)
  2928. CloseHandle(process_handle->stdout_pipe);
  2929. if (process_handle->stderr_pipe)
  2930. CloseHandle(process_handle->stderr_pipe);
  2931. if (process_handle->stdin_pipe)
  2932. CloseHandle(process_handle->stdin_pipe);
  2933. #else /* !(defined(_WIN32)) */
  2934. close(process_handle->stdout_pipe);
  2935. close(process_handle->stderr_pipe);
  2936. close(process_handle->stdin_pipe);
  2937. clear_waitpid_callback(process_handle->waitpid_cb);
  2938. #endif /* defined(_WIN32) */
  2939. memset(process_handle, 0x0f, sizeof(process_handle_t));
  2940. tor_free(process_handle);
  2941. }
  2942. /** Get the exit code of a process specified by <b>process_handle</b> and store
  2943. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  2944. * to true, the call will block until the process has exited. Otherwise if
  2945. * the process is still running, the function will return
  2946. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  2947. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  2948. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  2949. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  2950. * probably not work in Tor, because waitpid() is called in main.c to reap any
  2951. * terminated child processes.*/
  2952. int
  2953. tor_get_exit_code(process_handle_t *process_handle,
  2954. int block, int *exit_code)
  2955. {
  2956. #ifdef _WIN32
  2957. DWORD retval;
  2958. BOOL success;
  2959. if (block) {
  2960. /* Wait for the process to exit */
  2961. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  2962. if (retval != WAIT_OBJECT_0) {
  2963. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  2964. (int)retval, format_win32_error(GetLastError()));
  2965. return PROCESS_EXIT_ERROR;
  2966. }
  2967. } else {
  2968. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  2969. if (WAIT_TIMEOUT == retval) {
  2970. /* Process has not exited */
  2971. return PROCESS_EXIT_RUNNING;
  2972. } else if (retval != WAIT_OBJECT_0) {
  2973. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  2974. (int)retval, format_win32_error(GetLastError()));
  2975. return PROCESS_EXIT_ERROR;
  2976. }
  2977. }
  2978. if (exit_code != NULL) {
  2979. success = GetExitCodeProcess(process_handle->pid.hProcess,
  2980. (PDWORD)exit_code);
  2981. if (!success) {
  2982. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  2983. format_win32_error(GetLastError()));
  2984. return PROCESS_EXIT_ERROR;
  2985. }
  2986. }
  2987. #else /* !(defined(_WIN32)) */
  2988. int stat_loc;
  2989. int retval;
  2990. if (process_handle->waitpid_cb) {
  2991. /* We haven't processed a SIGCHLD yet. */
  2992. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  2993. if (retval == process_handle->pid) {
  2994. clear_waitpid_callback(process_handle->waitpid_cb);
  2995. process_handle->waitpid_cb = NULL;
  2996. process_handle->waitpid_exit_status = stat_loc;
  2997. }
  2998. } else {
  2999. /* We already got a SIGCHLD for this process, and handled it. */
  3000. retval = process_handle->pid;
  3001. stat_loc = process_handle->waitpid_exit_status;
  3002. }
  3003. if (!block && 0 == retval) {
  3004. /* Process has not exited */
  3005. return PROCESS_EXIT_RUNNING;
  3006. } else if (retval != process_handle->pid) {
  3007. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3008. (int)process_handle->pid, strerror(errno));
  3009. return PROCESS_EXIT_ERROR;
  3010. }
  3011. if (!WIFEXITED(stat_loc)) {
  3012. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3013. (int)process_handle->pid);
  3014. return PROCESS_EXIT_ERROR;
  3015. }
  3016. if (exit_code != NULL)
  3017. *exit_code = WEXITSTATUS(stat_loc);
  3018. #endif /* defined(_WIN32) */
  3019. return PROCESS_EXIT_EXITED;
  3020. }
  3021. /** Helper: return the number of characters in <b>s</b> preceding the first
  3022. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  3023. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  3024. static inline size_t
  3025. str_num_before(const char *s, char ch)
  3026. {
  3027. const char *cp = strchr(s, ch);
  3028. if (cp)
  3029. return cp - s;
  3030. else
  3031. return strlen(s);
  3032. }
  3033. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3034. * to have the same name as strings in a process's environment. */
  3035. int
  3036. environment_variable_names_equal(const char *s1, const char *s2)
  3037. {
  3038. size_t s1_name_len = str_num_before(s1, '=');
  3039. size_t s2_name_len = str_num_before(s2, '=');
  3040. return (s1_name_len == s2_name_len &&
  3041. tor_memeq(s1, s2, s1_name_len));
  3042. }
  3043. /** Free <b>env</b> (assuming it was produced by
  3044. * process_environment_make). */
  3045. void
  3046. process_environment_free_(process_environment_t *env)
  3047. {
  3048. if (env == NULL) return;
  3049. /* As both an optimization hack to reduce consing on Unixoid systems
  3050. * and a nice way to ensure that some otherwise-Windows-specific
  3051. * code will always get tested before changes to it get merged, the
  3052. * strings which env->unixoid_environment_block points to are packed
  3053. * into env->windows_environment_block. */
  3054. tor_free(env->unixoid_environment_block);
  3055. tor_free(env->windows_environment_block);
  3056. tor_free(env);
  3057. }
  3058. /** Make a process_environment_t containing the environment variables
  3059. * specified in <b>env_vars</b> (as C strings of the form
  3060. * "NAME=VALUE"). */
  3061. process_environment_t *
  3062. process_environment_make(struct smartlist_t *env_vars)
  3063. {
  3064. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3065. int n_env_vars = smartlist_len(env_vars);
  3066. int i;
  3067. size_t total_env_length;
  3068. smartlist_t *env_vars_sorted;
  3069. tor_assert(n_env_vars + 1 != 0);
  3070. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3071. /* env->unixoid_environment_block is already NULL-terminated,
  3072. * because we assume that NULL == 0 (and check that during compilation). */
  3073. total_env_length = 1; /* terminating NUL of terminating empty string */
  3074. for (i = 0; i < n_env_vars; ++i) {
  3075. const char *s = smartlist_get(env_vars, (int)i);
  3076. size_t slen = strlen(s);
  3077. tor_assert(slen + 1 != 0);
  3078. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3079. total_env_length += slen + 1;
  3080. }
  3081. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3082. /* env->windows_environment_block is already
  3083. * (NUL-terminated-empty-string)-terminated. */
  3084. /* Some versions of Windows supposedly require that environment
  3085. * blocks be sorted. Or maybe some Windows programs (or their
  3086. * runtime libraries) fail to look up strings in non-sorted
  3087. * environment blocks.
  3088. *
  3089. * Also, sorting strings makes it easy to find duplicate environment
  3090. * variables and environment-variable strings without an '=' on all
  3091. * OSes, and they can cause badness. Let's complain about those. */
  3092. env_vars_sorted = smartlist_new();
  3093. smartlist_add_all(env_vars_sorted, env_vars);
  3094. smartlist_sort_strings(env_vars_sorted);
  3095. /* Now copy the strings into the environment blocks. */
  3096. {
  3097. char *cp = env->windows_environment_block;
  3098. const char *prev_env_var = NULL;
  3099. for (i = 0; i < n_env_vars; ++i) {
  3100. const char *s = smartlist_get(env_vars_sorted, (int)i);
  3101. size_t slen = strlen(s);
  3102. size_t s_name_len = str_num_before(s, '=');
  3103. if (s_name_len == slen) {
  3104. log_warn(LD_GENERAL,
  3105. "Preparing an environment containing a variable "
  3106. "without a value: %s",
  3107. s);
  3108. }
  3109. if (prev_env_var != NULL &&
  3110. environment_variable_names_equal(s, prev_env_var)) {
  3111. log_warn(LD_GENERAL,
  3112. "Preparing an environment containing two variables "
  3113. "with the same name: %s and %s",
  3114. prev_env_var, s);
  3115. }
  3116. prev_env_var = s;
  3117. /* Actually copy the string into the environment. */
  3118. memcpy(cp, s, slen+1);
  3119. env->unixoid_environment_block[i] = cp;
  3120. cp += slen+1;
  3121. }
  3122. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3123. }
  3124. smartlist_free(env_vars_sorted);
  3125. return env;
  3126. }
  3127. /** Return a newly allocated smartlist containing every variable in
  3128. * this process's environment, as a NUL-terminated string of the form
  3129. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3130. * process can put strings not of that form in our environment;
  3131. * callers should try to not get crashed by that.
  3132. *
  3133. * The returned strings are heap-allocated, and must be freed by the
  3134. * caller. */
  3135. struct smartlist_t *
  3136. get_current_process_environment_variables(void)
  3137. {
  3138. smartlist_t *sl = smartlist_new();
  3139. char **environ_tmp; /* Not const char ** ? Really? */
  3140. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  3141. smartlist_add_strdup(sl, *environ_tmp);
  3142. }
  3143. return sl;
  3144. }
  3145. /** For each string s in <b>env_vars</b> such that
  3146. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3147. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3148. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3149. void
  3150. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3151. const char *new_var,
  3152. void (*free_old)(void*),
  3153. int free_p)
  3154. {
  3155. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3156. if (environment_variable_names_equal(s, new_var)) {
  3157. SMARTLIST_DEL_CURRENT(env_vars, s);
  3158. if (free_p) {
  3159. free_old((void *)s);
  3160. }
  3161. }
  3162. } SMARTLIST_FOREACH_END(s);
  3163. if (strchr(new_var, '=') != NULL) {
  3164. smartlist_add(env_vars, (void *)new_var);
  3165. }
  3166. }
  3167. #ifdef _WIN32
  3168. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3169. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3170. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3171. * to the process owning the <b>h</b>. In this case, the function will exit
  3172. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3173. * the number of bytes read, or -1 on error. */
  3174. ssize_t
  3175. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  3176. const process_handle_t *process)
  3177. {
  3178. size_t numread = 0;
  3179. BOOL retval;
  3180. DWORD byte_count;
  3181. BOOL process_exited = FALSE;
  3182. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  3183. return -1;
  3184. while (numread < count) {
  3185. /* Check if there is anything to read */
  3186. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  3187. if (!retval) {
  3188. log_warn(LD_GENERAL,
  3189. "Failed to peek from handle: %s",
  3190. format_win32_error(GetLastError()));
  3191. return -1;
  3192. } else if (0 == byte_count) {
  3193. /* Nothing available: process exited or it is busy */
  3194. /* Exit if we don't know whether the process is running */
  3195. if (NULL == process)
  3196. break;
  3197. /* The process exited and there's nothing left to read from it */
  3198. if (process_exited)
  3199. break;
  3200. /* If process is not running, check for output one more time in case
  3201. it wrote something after the peek was performed. Otherwise keep on
  3202. waiting for output */
  3203. tor_assert(process != NULL);
  3204. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  3205. if (WAIT_TIMEOUT != byte_count)
  3206. process_exited = TRUE;
  3207. continue;
  3208. }
  3209. /* There is data to read; read it */
  3210. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  3211. tor_assert(byte_count + numread <= count);
  3212. if (!retval) {
  3213. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  3214. format_win32_error(GetLastError()));
  3215. return -1;
  3216. } else if (0 == byte_count) {
  3217. /* End of file */
  3218. break;
  3219. }
  3220. numread += byte_count;
  3221. }
  3222. return (ssize_t)numread;
  3223. }
  3224. #else /* !(defined(_WIN32)) */
  3225. /** Read from a handle <b>fd</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3226. * <b>process</b> is NULL, the function will return immediately if there is
  3227. * nothing more to read. Otherwise data will be read until end of file, or
  3228. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  3229. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  3230. * file has been reached. */
  3231. ssize_t
  3232. tor_read_all_handle(int fd, char *buf, size_t count,
  3233. const process_handle_t *process,
  3234. int *eof)
  3235. {
  3236. size_t numread = 0;
  3237. ssize_t result;
  3238. if (eof)
  3239. *eof = 0;
  3240. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  3241. return -1;
  3242. while (numread < count) {
  3243. result = read(fd, buf+numread, count-numread);
  3244. if (result == 0) {
  3245. log_debug(LD_GENERAL, "read() reached end of file");
  3246. if (eof)
  3247. *eof = 1;
  3248. break;
  3249. } else if (result < 0 && errno == EAGAIN) {
  3250. if (process)
  3251. continue;
  3252. else
  3253. break;
  3254. } else if (result < 0) {
  3255. log_warn(LD_GENERAL, "read() failed: %s", strerror(errno));
  3256. return -1;
  3257. }
  3258. numread += result;
  3259. }
  3260. log_debug(LD_GENERAL, "read() read %d bytes from handle", (int)numread);
  3261. return (ssize_t)numread;
  3262. }
  3263. #endif /* defined(_WIN32) */
  3264. /** Read from stdout of a process until the process exits. */
  3265. ssize_t
  3266. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  3267. char *buf, size_t count)
  3268. {
  3269. #ifdef _WIN32
  3270. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3271. process_handle);
  3272. #else
  3273. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3274. process_handle, NULL);
  3275. #endif /* defined(_WIN32) */
  3276. }
  3277. /** Read from stdout of a process until the process exits. */
  3278. ssize_t
  3279. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  3280. char *buf, size_t count)
  3281. {
  3282. #ifdef _WIN32
  3283. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3284. process_handle);
  3285. #else
  3286. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3287. process_handle, NULL);
  3288. #endif /* defined(_WIN32) */
  3289. }
  3290. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  3291. * modified. The resulting smartlist will consist of pointers to buf, so there
  3292. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  3293. * string. <b>len</b> should be set to the length of the buffer excluding the
  3294. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  3295. int
  3296. tor_split_lines(smartlist_t *sl, char *buf, int len)
  3297. {
  3298. /* Index in buf of the start of the current line */
  3299. int start = 0;
  3300. /* Index in buf of the current character being processed */
  3301. int cur = 0;
  3302. /* Are we currently in a line */
  3303. char in_line = 0;
  3304. /* Loop over string */
  3305. while (cur < len) {
  3306. /* Loop until end of line or end of string */
  3307. for (; cur < len; cur++) {
  3308. if (in_line) {
  3309. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3310. /* End of line */
  3311. buf[cur] = '\0';
  3312. /* Point cur to the next line */
  3313. cur++;
  3314. /* Line starts at start and ends with a nul */
  3315. break;
  3316. } else {
  3317. if (!TOR_ISPRINT(buf[cur]))
  3318. buf[cur] = '.';
  3319. }
  3320. } else {
  3321. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3322. /* Skip leading vertical space */
  3323. ;
  3324. } else {
  3325. in_line = 1;
  3326. start = cur;
  3327. if (!TOR_ISPRINT(buf[cur]))
  3328. buf[cur] = '.';
  3329. }
  3330. }
  3331. }
  3332. /* We are at the end of the line or end of string. If in_line is true there
  3333. * is a line which starts at buf+start and ends at a NUL. cur points to
  3334. * the character after the NUL. */
  3335. if (in_line)
  3336. smartlist_add(sl, (void *)(buf+start));
  3337. in_line = 0;
  3338. }
  3339. return smartlist_len(sl);
  3340. }
  3341. /** Return a string corresponding to <b>stream_status</b>. */
  3342. const char *
  3343. stream_status_to_string(enum stream_status stream_status)
  3344. {
  3345. switch (stream_status) {
  3346. case IO_STREAM_OKAY:
  3347. return "okay";
  3348. case IO_STREAM_EAGAIN:
  3349. return "temporarily unavailable";
  3350. case IO_STREAM_TERM:
  3351. return "terminated";
  3352. case IO_STREAM_CLOSED:
  3353. return "closed";
  3354. default:
  3355. tor_fragile_assert();
  3356. return "unknown";
  3357. }
  3358. }
  3359. #ifdef _WIN32
  3360. /** Return a smartlist containing lines outputted from
  3361. * <b>handle</b>. Return NULL on error, and set
  3362. * <b>stream_status_out</b> appropriately. */
  3363. MOCK_IMPL(smartlist_t *,
  3364. tor_get_lines_from_handle, (HANDLE *handle,
  3365. enum stream_status *stream_status_out))
  3366. {
  3367. int pos;
  3368. char stdout_buf[600] = {0};
  3369. smartlist_t *lines = NULL;
  3370. tor_assert(stream_status_out);
  3371. *stream_status_out = IO_STREAM_TERM;
  3372. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  3373. if (pos < 0) {
  3374. *stream_status_out = IO_STREAM_TERM;
  3375. return NULL;
  3376. }
  3377. if (pos == 0) {
  3378. *stream_status_out = IO_STREAM_EAGAIN;
  3379. return NULL;
  3380. }
  3381. /* End with a null even if there isn't a \r\n at the end */
  3382. /* TODO: What if this is a partial line? */
  3383. stdout_buf[pos] = '\0';
  3384. /* Split up the buffer */
  3385. lines = smartlist_new();
  3386. tor_split_lines(lines, stdout_buf, pos);
  3387. /* Currently 'lines' is populated with strings residing on the
  3388. stack. Replace them with their exact copies on the heap: */
  3389. SMARTLIST_FOREACH(lines, char *, line,
  3390. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  3391. *stream_status_out = IO_STREAM_OKAY;
  3392. return lines;
  3393. }
  3394. #else /* !(defined(_WIN32)) */
  3395. /** Return a smartlist containing lines outputted from
  3396. * <b>fd</b>. Return NULL on error, and set
  3397. * <b>stream_status_out</b> appropriately. */
  3398. MOCK_IMPL(smartlist_t *,
  3399. tor_get_lines_from_handle, (int fd, enum stream_status *stream_status_out))
  3400. {
  3401. enum stream_status stream_status;
  3402. char stdout_buf[400];
  3403. smartlist_t *lines = NULL;
  3404. while (1) {
  3405. memset(stdout_buf, 0, sizeof(stdout_buf));
  3406. stream_status = get_string_from_pipe(fd,
  3407. stdout_buf, sizeof(stdout_buf) - 1);
  3408. if (stream_status != IO_STREAM_OKAY)
  3409. goto done;
  3410. if (!lines) lines = smartlist_new();
  3411. smartlist_split_string(lines, stdout_buf, "\n", 0, 0);
  3412. }
  3413. done:
  3414. *stream_status_out = stream_status;
  3415. return lines;
  3416. }
  3417. #endif /* defined(_WIN32) */
  3418. /** Reads from <b>fd</b> and stores input in <b>buf_out</b> making
  3419. * sure it's below <b>count</b> bytes.
  3420. * If the string has a trailing newline, we strip it off.
  3421. *
  3422. * This function is specifically created to handle input from managed
  3423. * proxies, according to the pluggable transports spec. Make sure it
  3424. * fits your needs before using it.
  3425. *
  3426. * Returns:
  3427. * IO_STREAM_CLOSED: If the stream is closed.
  3428. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  3429. * later.
  3430. * IO_STREAM_TERM: If something is wrong with the stream.
  3431. * IO_STREAM_OKAY: If everything went okay and we got a string
  3432. * in <b>buf_out</b>. */
  3433. enum stream_status
  3434. get_string_from_pipe(int fd, char *buf_out, size_t count)
  3435. {
  3436. ssize_t ret;
  3437. tor_assert(count <= INT_MAX);
  3438. ret = read(fd, buf_out, count);
  3439. if (ret == 0)
  3440. return IO_STREAM_CLOSED;
  3441. else if (ret < 0 && errno == EAGAIN)
  3442. return IO_STREAM_EAGAIN;
  3443. else if (ret < 0)
  3444. return IO_STREAM_TERM;
  3445. if (buf_out[ret - 1] == '\n') {
  3446. /* Remove the trailing newline */
  3447. buf_out[ret - 1] = '\0';
  3448. } else
  3449. buf_out[ret] = '\0';
  3450. return IO_STREAM_OKAY;
  3451. }
  3452. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  3453. void
  3454. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  3455. {
  3456. rng->state = (uint32_t)(seed & 0x7fffffff);
  3457. }
  3458. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  3459. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  3460. * strong; do not rely on it for anything an adversary should not be able to
  3461. * predict. */
  3462. int32_t
  3463. tor_weak_random(tor_weak_rng_t *rng)
  3464. {
  3465. /* Here's a linear congruential generator. OpenBSD and glibc use these
  3466. * parameters; they aren't too bad, and should have maximal period over the
  3467. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  3468. * since some platforms have bad weak RNGs that only return values in the
  3469. * range 0..INT16_MAX, which just isn't enough. */
  3470. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  3471. return (int32_t) rng->state;
  3472. }
  3473. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  3474. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  3475. * top is greater than 0. This randomness is not cryptographically strong; do
  3476. * not rely on it for anything an adversary should not be able to predict. */
  3477. int32_t
  3478. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  3479. {
  3480. /* We don't want to just do tor_weak_random() % top, since random() is often
  3481. * implemented with an LCG whose modulus is a power of 2, and those are
  3482. * cyclic in their low-order bits. */
  3483. int divisor, result;
  3484. tor_assert(top > 0);
  3485. divisor = TOR_WEAK_RANDOM_MAX / top;
  3486. do {
  3487. result = (int32_t)(tor_weak_random(rng) / divisor);
  3488. } while (result >= top);
  3489. return result;
  3490. }
  3491. /** Cast a given double value to a int64_t. Return 0 if number is NaN.
  3492. * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
  3493. * range. */
  3494. int64_t
  3495. clamp_double_to_int64(double number)
  3496. {
  3497. int exponent;
  3498. #if defined(MINGW_ANY) && GCC_VERSION >= 409
  3499. /*
  3500. Mingw's math.h uses gcc's __builtin_choose_expr() facility to declare
  3501. isnan, isfinite, and signbit. But as implemented in at least some
  3502. versions of gcc, __builtin_choose_expr() can generate type warnings
  3503. even from branches that are not taken. So, suppress those warnings.
  3504. */
  3505. #define PROBLEMATIC_FLOAT_CONVERSION_WARNING
  3506. DISABLE_GCC_WARNING(float-conversion)
  3507. #endif /* defined(MINGW_ANY) && GCC_VERSION >= 409 */
  3508. /*
  3509. With clang 4.0 we apparently run into "double promotion" warnings here,
  3510. since clang thinks we're promoting a double to a long double.
  3511. */
  3512. #if defined(__clang__)
  3513. #if __has_warning("-Wdouble-promotion")
  3514. #define PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  3515. DISABLE_GCC_WARNING(double-promotion)
  3516. #endif
  3517. #endif /* defined(__clang__) */
  3518. /* NaN is a special case that can't be used with the logic below. */
  3519. if (isnan(number)) {
  3520. return 0;
  3521. }
  3522. /* Time to validate if result can overflows a int64_t value. Fun with
  3523. * float! Find that exponent exp such that
  3524. * number == x * 2^exp
  3525. * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
  3526. * magnitude of number is strictly less than 2^exp.
  3527. *
  3528. * If number is infinite, the call to frexp is legal but the contents of
  3529. * are exponent unspecified. */
  3530. frexp(number, &exponent);
  3531. /* If the magnitude of number is strictly less than 2^63, the truncated
  3532. * version of number is guaranteed to be representable. The only
  3533. * representable integer for which this is not the case is INT64_MIN, but
  3534. * it is covered by the logic below. */
  3535. if (isfinite(number) && exponent <= 63) {
  3536. return (int64_t)number;
  3537. }
  3538. /* Handle infinities and finite numbers with magnitude >= 2^63. */
  3539. return signbit(number) ? INT64_MIN : INT64_MAX;
  3540. #ifdef PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  3541. ENABLE_GCC_WARNING(double-promotion)
  3542. #endif
  3543. #ifdef PROBLEMATIC_FLOAT_CONVERSION_WARNING
  3544. ENABLE_GCC_WARNING(float-conversion)
  3545. #endif
  3546. }
  3547. /** Return a uint64_t value from <b>a</b> in network byte order. */
  3548. uint64_t
  3549. tor_htonll(uint64_t a)
  3550. {
  3551. #ifdef WORDS_BIGENDIAN
  3552. /* Big endian. */
  3553. return a;
  3554. #else /* WORDS_BIGENDIAN */
  3555. /* Little endian. The worst... */
  3556. return htonl((uint32_t)(a>>32)) |
  3557. (((uint64_t)htonl((uint32_t)a))<<32);
  3558. #endif /* defined(WORDS_BIGENDIAN) */
  3559. }
  3560. /** Return a uint64_t value from <b>a</b> in host byte order. */
  3561. uint64_t
  3562. tor_ntohll(uint64_t a)
  3563. {
  3564. return tor_htonll(a);
  3565. }