util.c 138 KB

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