util.c 142 KB

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