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 ";" or "\" character of <b>string</b>. Use
  1114. * <b>escape_char</b> as the character to use for escaping.
  1115. * The returned string is allocated on the heap and it's the
  1116. * responsibility of the caller to free it. */
  1117. char *
  1118. tor_escape_str_for_socks_arg(const char *string)
  1119. {
  1120. char *new_string = NULL;
  1121. char *new_cp = NULL;
  1122. size_t length, new_length;
  1123. static const char *chars_to_escape = ";\\";
  1124. tor_assert(string);
  1125. length = strlen(string);
  1126. if (!length) /* If we were given the empty string, return the same. */
  1127. return tor_strdup("");
  1128. /* (new_length > SIZE_MAX) => ((length * 2) + 1 > SIZE_MAX) =>
  1129. (length*2 > SIZE_MAX - 1) => (length > (SIZE_MAX - 1)/2) */
  1130. if (length > (SIZE_MAX - 1)/2) /* check for overflow */
  1131. return NULL;
  1132. /* this should be enough even if all characters must be escaped */
  1133. new_length = (length * 2) + 1;
  1134. new_string = new_cp = tor_malloc(new_length);
  1135. while (*string) {
  1136. if (strchr(chars_to_escape, *string))
  1137. *new_cp++ = '\\';
  1138. *new_cp++ = *string++;
  1139. }
  1140. *new_cp = '\0'; /* NUL-terminate the new string */
  1141. return new_string;
  1142. }
  1143. /* =====
  1144. * Time
  1145. * ===== */
  1146. /** Return the number of microseconds elapsed between *start and *end.
  1147. */
  1148. long
  1149. tv_udiff(const struct timeval *start, const struct timeval *end)
  1150. {
  1151. long udiff;
  1152. long secdiff = end->tv_sec - start->tv_sec;
  1153. if (labs(secdiff+1) > LONG_MAX/1000000) {
  1154. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  1155. "apart: %ld seconds", secdiff);
  1156. return LONG_MAX;
  1157. }
  1158. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  1159. return udiff;
  1160. }
  1161. /** Return the number of milliseconds elapsed between *start and *end.
  1162. */
  1163. long
  1164. tv_mdiff(const struct timeval *start, const struct timeval *end)
  1165. {
  1166. long mdiff;
  1167. long secdiff = end->tv_sec - start->tv_sec;
  1168. if (labs(secdiff+1) > LONG_MAX/1000) {
  1169. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  1170. "apart: %ld seconds", secdiff);
  1171. return LONG_MAX;
  1172. }
  1173. /* Subtract and round */
  1174. mdiff = secdiff*1000L +
  1175. ((long)end->tv_usec - (long)start->tv_usec + 500L) / 1000L;
  1176. return mdiff;
  1177. }
  1178. /** Yield true iff <b>y</b> is a leap-year. */
  1179. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  1180. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  1181. static int
  1182. n_leapdays(int y1, int y2)
  1183. {
  1184. --y1;
  1185. --y2;
  1186. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  1187. }
  1188. /** Number of days per month in non-leap year; used by tor_timegm. */
  1189. static const int days_per_month[] =
  1190. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1191. /** Compute a time_t given a struct tm. The result is given in UTC, and
  1192. * does not account for leap seconds. Return 0 on success, -1 on failure.
  1193. */
  1194. int
  1195. tor_timegm(const struct tm *tm, time_t *time_out)
  1196. {
  1197. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1198. * It's way more brute-force than fiddling with tzset().
  1199. */
  1200. time_t year, days, hours, minutes, seconds;
  1201. int i;
  1202. year = tm->tm_year + 1900;
  1203. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1204. tm->tm_year >= INT32_MAX-1900) {
  1205. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1206. return -1;
  1207. }
  1208. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1209. for (i = 0; i < tm->tm_mon; ++i)
  1210. days += days_per_month[i];
  1211. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1212. ++days;
  1213. days += tm->tm_mday - 1;
  1214. hours = days*24 + tm->tm_hour;
  1215. minutes = hours*60 + tm->tm_min;
  1216. seconds = minutes*60 + tm->tm_sec;
  1217. *time_out = seconds;
  1218. return 0;
  1219. }
  1220. /* strftime is locale-specific, so we need to replace those parts */
  1221. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1222. static const char *WEEKDAY_NAMES[] =
  1223. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1224. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1225. static const char *MONTH_NAMES[] =
  1226. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1227. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1228. /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
  1229. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1230. *
  1231. * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
  1232. * rather than "UTC".)
  1233. */
  1234. void
  1235. format_rfc1123_time(char *buf, time_t t)
  1236. {
  1237. struct tm tm;
  1238. tor_gmtime_r(&t, &tm);
  1239. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1240. tor_assert(tm.tm_wday >= 0);
  1241. tor_assert(tm.tm_wday <= 6);
  1242. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1243. tor_assert(tm.tm_mon >= 0);
  1244. tor_assert(tm.tm_mon <= 11);
  1245. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1246. }
  1247. /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
  1248. * <b>buf</b>, and store the result in *<b>t</b>.
  1249. *
  1250. * Note that we only accept the subset generated by format_rfc1123_time above,
  1251. * not the full range of formats suggested by RFC 1123.
  1252. *
  1253. * Return 0 on success, -1 on failure.
  1254. */
  1255. int
  1256. parse_rfc1123_time(const char *buf, time_t *t)
  1257. {
  1258. struct tm tm;
  1259. char month[4];
  1260. char weekday[4];
  1261. int i, m;
  1262. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1263. if (strlen(buf) != RFC1123_TIME_LEN)
  1264. return -1;
  1265. memset(&tm, 0, sizeof(tm));
  1266. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1267. &tm_mday, month, &tm_year, &tm_hour,
  1268. &tm_min, &tm_sec) < 7) {
  1269. char *esc = esc_for_log(buf);
  1270. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1271. tor_free(esc);
  1272. return -1;
  1273. }
  1274. if (tm_mday < 1 || tm_mday > 31 || tm_hour > 23 || tm_min > 59 ||
  1275. tm_sec > 60 || tm_year >= INT32_MAX || tm_year < 1970) {
  1276. char *esc = esc_for_log(buf);
  1277. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1278. tor_free(esc);
  1279. return -1;
  1280. }
  1281. tm.tm_mday = (int)tm_mday;
  1282. tm.tm_year = (int)tm_year;
  1283. tm.tm_hour = (int)tm_hour;
  1284. tm.tm_min = (int)tm_min;
  1285. tm.tm_sec = (int)tm_sec;
  1286. m = -1;
  1287. for (i = 0; i < 12; ++i) {
  1288. if (!strcmp(month, MONTH_NAMES[i])) {
  1289. m = i;
  1290. break;
  1291. }
  1292. }
  1293. if (m<0) {
  1294. char *esc = esc_for_log(buf);
  1295. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1296. tor_free(esc);
  1297. return -1;
  1298. }
  1299. tm.tm_mon = m;
  1300. if (tm.tm_year < 1970) {
  1301. char *esc = esc_for_log(buf);
  1302. log_warn(LD_GENERAL,
  1303. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1304. tor_free(esc);
  1305. return -1;
  1306. }
  1307. tm.tm_year -= 1900;
  1308. return tor_timegm(&tm, t);
  1309. }
  1310. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1311. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1312. *
  1313. * (ISO8601 format is 2006-10-29 10:57:20)
  1314. */
  1315. void
  1316. format_local_iso_time(char *buf, time_t t)
  1317. {
  1318. struct tm tm;
  1319. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1320. }
  1321. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1322. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1323. */
  1324. void
  1325. format_iso_time(char *buf, time_t t)
  1326. {
  1327. struct tm tm;
  1328. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1329. }
  1330. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  1331. * embedding an internal space. */
  1332. void
  1333. format_iso_time_nospace(char *buf, time_t t)
  1334. {
  1335. format_iso_time(buf, t);
  1336. buf[10] = 'T';
  1337. }
  1338. /** As format_iso_time_nospace, but include microseconds in decimal
  1339. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  1340. * bytes long. */
  1341. void
  1342. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  1343. {
  1344. tor_assert(tv);
  1345. format_iso_time_nospace(buf, tv->tv_sec);
  1346. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  1347. }
  1348. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1349. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1350. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1351. * the end of the time string. */
  1352. int
  1353. parse_iso_time(const char *cp, time_t *t)
  1354. {
  1355. struct tm st_tm;
  1356. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  1357. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1358. &day, &hour, &minute, &second) < 6) {
  1359. char *esc = esc_for_log(cp);
  1360. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1361. tor_free(esc);
  1362. return -1;
  1363. }
  1364. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1365. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  1366. char *esc = esc_for_log(cp);
  1367. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1368. tor_free(esc);
  1369. return -1;
  1370. }
  1371. st_tm.tm_year = (int)year-1900;
  1372. st_tm.tm_mon = month-1;
  1373. st_tm.tm_mday = day;
  1374. st_tm.tm_hour = hour;
  1375. st_tm.tm_min = minute;
  1376. st_tm.tm_sec = second;
  1377. if (st_tm.tm_year < 70) {
  1378. char *esc = esc_for_log(cp);
  1379. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1380. tor_free(esc);
  1381. return -1;
  1382. }
  1383. return tor_timegm(&st_tm, t);
  1384. }
  1385. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1386. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1387. int
  1388. parse_http_time(const char *date, struct tm *tm)
  1389. {
  1390. const char *cp;
  1391. char month[4];
  1392. char wkday[4];
  1393. int i;
  1394. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1395. tor_assert(tm);
  1396. memset(tm, 0, sizeof(*tm));
  1397. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1398. if ((cp = strchr(date, ','))) {
  1399. ++cp;
  1400. if (*cp != ' ')
  1401. return -1;
  1402. ++cp;
  1403. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  1404. &tm_mday, month, &tm_year,
  1405. &tm_hour, &tm_min, &tm_sec) == 6) {
  1406. /* rfc1123-date */
  1407. tm_year -= 1900;
  1408. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1409. &tm_mday, month, &tm_year,
  1410. &tm_hour, &tm_min, &tm_sec) == 6) {
  1411. /* rfc850-date */
  1412. } else {
  1413. return -1;
  1414. }
  1415. } else {
  1416. /* No comma; possibly asctime() format. */
  1417. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1418. wkday, month, &tm_mday,
  1419. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1420. tm_year -= 1900;
  1421. } else {
  1422. return -1;
  1423. }
  1424. }
  1425. tm->tm_mday = (int)tm_mday;
  1426. tm->tm_year = (int)tm_year;
  1427. tm->tm_hour = (int)tm_hour;
  1428. tm->tm_min = (int)tm_min;
  1429. tm->tm_sec = (int)tm_sec;
  1430. month[3] = '\0';
  1431. /* Okay, now decode the month. */
  1432. /* set tm->tm_mon to dummy value so the check below fails. */
  1433. tm->tm_mon = -1;
  1434. for (i = 0; i < 12; ++i) {
  1435. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1436. tm->tm_mon = i;
  1437. }
  1438. }
  1439. if (tm->tm_year < 0 ||
  1440. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1441. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  1442. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1443. tm->tm_min < 0 || tm->tm_min > 59 ||
  1444. tm->tm_sec < 0 || tm->tm_sec > 60)
  1445. return -1; /* Out of range, or bad month. */
  1446. return 0;
  1447. }
  1448. /** Given an <b>interval</b> in seconds, try to write it to the
  1449. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1450. * Return 0 on success, -1 on failure.
  1451. */
  1452. int
  1453. format_time_interval(char *out, size_t out_len, long interval)
  1454. {
  1455. /* We only report seconds if there's no hours. */
  1456. long sec = 0, min = 0, hour = 0, day = 0;
  1457. if (interval < 0)
  1458. interval = -interval;
  1459. if (interval >= 86400) {
  1460. day = interval / 86400;
  1461. interval %= 86400;
  1462. }
  1463. if (interval >= 3600) {
  1464. hour = interval / 3600;
  1465. interval %= 3600;
  1466. }
  1467. if (interval >= 60) {
  1468. min = interval / 60;
  1469. interval %= 60;
  1470. }
  1471. sec = interval;
  1472. if (day) {
  1473. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1474. day, hour, min);
  1475. } else if (hour) {
  1476. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1477. } else if (min) {
  1478. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1479. } else {
  1480. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1481. }
  1482. }
  1483. /* =====
  1484. * Cached time
  1485. * ===== */
  1486. #ifndef TIME_IS_FAST
  1487. /** Cached estimate of the current time. Updated around once per second;
  1488. * may be a few seconds off if we are really busy. This is a hack to avoid
  1489. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1490. */
  1491. static time_t cached_approx_time = 0;
  1492. /** Return a cached estimate of the current time from when
  1493. * update_approx_time() was last called. This is a hack to avoid calling
  1494. * time(NULL) on critical paths: please do not even think of calling it
  1495. * anywhere else. */
  1496. time_t
  1497. approx_time(void)
  1498. {
  1499. return cached_approx_time;
  1500. }
  1501. /** Update the cached estimate of the current time. This function SHOULD be
  1502. * called once per second, and MUST be called before the first call to
  1503. * get_approx_time. */
  1504. void
  1505. update_approx_time(time_t now)
  1506. {
  1507. cached_approx_time = now;
  1508. }
  1509. #endif
  1510. /* =====
  1511. * Rate limiting
  1512. * ===== */
  1513. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1514. * of calls to rate_limit_is_ready (including this one!) since the last time
  1515. * rate_limit_is_ready returned nonzero. Otherwise return 0. */
  1516. static int
  1517. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1518. {
  1519. if (lim->rate + lim->last_allowed <= now) {
  1520. int res = lim->n_calls_since_last_time + 1;
  1521. lim->last_allowed = now;
  1522. lim->n_calls_since_last_time = 0;
  1523. return res;
  1524. } else {
  1525. ++lim->n_calls_since_last_time;
  1526. return 0;
  1527. }
  1528. }
  1529. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1530. * allocated string indicating how many messages were suppressed, suitable to
  1531. * append to a log message. Otherwise return NULL. */
  1532. char *
  1533. rate_limit_log(ratelim_t *lim, time_t now)
  1534. {
  1535. int n;
  1536. if ((n = rate_limit_is_ready(lim, now))) {
  1537. if (n == 1) {
  1538. return tor_strdup("");
  1539. } else {
  1540. char *cp=NULL;
  1541. tor_asprintf(&cp,
  1542. " [%d similar message(s) suppressed in last %d seconds]",
  1543. n-1, lim->rate);
  1544. return cp;
  1545. }
  1546. } else {
  1547. return NULL;
  1548. }
  1549. }
  1550. /* =====
  1551. * File helpers
  1552. * ===== */
  1553. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1554. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1555. * was returned by open(). Return the number of bytes written, or -1
  1556. * on error. Only use if fd is a blocking fd. */
  1557. ssize_t
  1558. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1559. {
  1560. size_t written = 0;
  1561. ssize_t result;
  1562. tor_assert(count < SSIZE_T_MAX);
  1563. while (written != count) {
  1564. if (isSocket)
  1565. result = tor_socket_send(fd, buf+written, count-written, 0);
  1566. else
  1567. result = write((int)fd, buf+written, count-written);
  1568. if (result<0)
  1569. return -1;
  1570. written += result;
  1571. }
  1572. return (ssize_t)count;
  1573. }
  1574. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1575. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1576. * was returned by socket() or accept(), and 0 if fd was returned by
  1577. * open(). Return the number of bytes read, or -1 on error. Only use
  1578. * if fd is a blocking fd. */
  1579. ssize_t
  1580. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1581. {
  1582. size_t numread = 0;
  1583. ssize_t result;
  1584. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1585. return -1;
  1586. while (numread != count) {
  1587. if (isSocket)
  1588. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1589. else
  1590. result = read((int)fd, buf+numread, count-numread);
  1591. if (result<0)
  1592. return -1;
  1593. else if (result == 0)
  1594. break;
  1595. numread += result;
  1596. }
  1597. return (ssize_t)numread;
  1598. }
  1599. /*
  1600. * Filesystem operations.
  1601. */
  1602. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1603. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1604. * the root of a disk. */
  1605. static void
  1606. clean_name_for_stat(char *name)
  1607. {
  1608. #ifdef _WIN32
  1609. size_t len = strlen(name);
  1610. if (!len)
  1611. return;
  1612. if (name[len-1]=='\\' || name[len-1]=='/') {
  1613. if (len == 1 || (len==3 && name[1]==':'))
  1614. return;
  1615. name[len-1]='\0';
  1616. }
  1617. #else
  1618. (void)name;
  1619. #endif
  1620. }
  1621. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1622. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1623. * directory. On FN_ERROR, sets errno. */
  1624. file_status_t
  1625. file_status(const char *fname)
  1626. {
  1627. struct stat st;
  1628. char *f;
  1629. int r;
  1630. f = tor_strdup(fname);
  1631. clean_name_for_stat(f);
  1632. r = stat(f, &st);
  1633. tor_free(f);
  1634. if (r) {
  1635. if (errno == ENOENT) {
  1636. return FN_NOENT;
  1637. }
  1638. return FN_ERROR;
  1639. }
  1640. if (st.st_mode & S_IFDIR)
  1641. return FN_DIR;
  1642. else if (st.st_mode & S_IFREG)
  1643. return FN_FILE;
  1644. #ifndef _WIN32
  1645. else if (st.st_mode & S_IFIFO)
  1646. return FN_FILE;
  1647. #endif
  1648. else
  1649. return FN_ERROR;
  1650. }
  1651. /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
  1652. * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
  1653. * and return 0 on success. If it does not exist, and
  1654. * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
  1655. * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
  1656. * is group-readable, but in all cases we create the directory mode 0700.
  1657. * If CPD_CHECK_MODE_ONLY is set, then we don't alter the directory permissions
  1658. * if they are too permissive: we just return -1.
  1659. * When effective_user is not NULL, check permissions against the given user
  1660. * and its primary group.
  1661. */
  1662. int
  1663. check_private_dir(const char *dirname, cpd_check_t check,
  1664. const char *effective_user)
  1665. {
  1666. int r;
  1667. struct stat st;
  1668. char *f;
  1669. #ifndef _WIN32
  1670. int mask;
  1671. struct passwd *pw = NULL;
  1672. uid_t running_uid;
  1673. gid_t running_gid;
  1674. #else
  1675. (void)effective_user;
  1676. #endif
  1677. tor_assert(dirname);
  1678. f = tor_strdup(dirname);
  1679. clean_name_for_stat(f);
  1680. r = stat(f, &st);
  1681. tor_free(f);
  1682. if (r) {
  1683. if (errno != ENOENT) {
  1684. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1685. strerror(errno));
  1686. return -1;
  1687. }
  1688. if (check & CPD_CREATE) {
  1689. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1690. #if defined (_WIN32) && !defined (WINCE)
  1691. r = mkdir(dirname);
  1692. #else
  1693. r = mkdir(dirname, 0700);
  1694. #endif
  1695. if (r) {
  1696. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1697. strerror(errno));
  1698. return -1;
  1699. }
  1700. } else if (!(check & CPD_CHECK)) {
  1701. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1702. return -1;
  1703. }
  1704. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1705. * parent directory a little harder. */
  1706. return 0;
  1707. }
  1708. if (!(st.st_mode & S_IFDIR)) {
  1709. log_warn(LD_FS, "%s is not a directory", dirname);
  1710. return -1;
  1711. }
  1712. #ifndef _WIN32
  1713. if (effective_user) {
  1714. /* Look up the user and group information.
  1715. * If we have a problem, bail out. */
  1716. pw = getpwnam(effective_user);
  1717. if (pw == NULL) {
  1718. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1719. effective_user);
  1720. return -1;
  1721. }
  1722. running_uid = pw->pw_uid;
  1723. running_gid = pw->pw_gid;
  1724. } else {
  1725. running_uid = getuid();
  1726. running_gid = getgid();
  1727. }
  1728. if (st.st_uid != running_uid) {
  1729. struct passwd *pw = NULL;
  1730. char *process_ownername = NULL;
  1731. pw = getpwuid(running_uid);
  1732. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1733. pw = getpwuid(st.st_uid);
  1734. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1735. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1736. dirname, process_ownername, (int)running_uid,
  1737. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1738. tor_free(process_ownername);
  1739. return -1;
  1740. }
  1741. if ((check & CPD_GROUP_OK) && st.st_gid != running_gid) {
  1742. struct group *gr;
  1743. char *process_groupname = NULL;
  1744. gr = getgrgid(running_gid);
  1745. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1746. gr = getgrgid(st.st_gid);
  1747. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1748. "%s (%d). Are you running Tor as the wrong user?",
  1749. dirname, process_groupname, (int)running_gid,
  1750. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1751. tor_free(process_groupname);
  1752. return -1;
  1753. }
  1754. if (check & CPD_GROUP_OK) {
  1755. mask = 0027;
  1756. } else {
  1757. mask = 0077;
  1758. }
  1759. if (st.st_mode & mask) {
  1760. unsigned new_mode;
  1761. if (check & CPD_CHECK_MODE_ONLY) {
  1762. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1763. dirname);
  1764. return -1;
  1765. }
  1766. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1767. new_mode = st.st_mode;
  1768. new_mode |= 0700; /* Owner should have rwx */
  1769. new_mode &= ~mask; /* Clear the other bits that we didn't want set...*/
  1770. if (chmod(dirname, new_mode)) {
  1771. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1772. strerror(errno));
  1773. return -1;
  1774. } else {
  1775. return 0;
  1776. }
  1777. }
  1778. #endif
  1779. return 0;
  1780. }
  1781. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1782. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1783. *
  1784. * This function replaces the old file atomically, if possible. This
  1785. * function, and all other functions in util.c that create files, create them
  1786. * with mode 0600.
  1787. */
  1788. int
  1789. write_str_to_file(const char *fname, const char *str, int bin)
  1790. {
  1791. #ifdef _WIN32
  1792. if (!bin && strchr(str, '\r')) {
  1793. log_warn(LD_BUG,
  1794. "We're writing a text string that already contains a CR.");
  1795. }
  1796. #endif
  1797. return write_bytes_to_file(fname, str, strlen(str), bin);
  1798. }
  1799. /** Represents a file that we're writing to, with support for atomic commit:
  1800. * we can write into a temporary file, and either remove the file on
  1801. * failure, or replace the original file on success. */
  1802. struct open_file_t {
  1803. char *tempname; /**< Name of the temporary file. */
  1804. char *filename; /**< Name of the original file. */
  1805. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1806. unsigned binary:1; /**< Did we open in binary mode? */
  1807. int fd; /**< fd for the open file. */
  1808. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1809. };
  1810. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1811. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1812. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1813. * original file. Otherwise, we open a new temporary file in the same
  1814. * directory, and either replace the original or remove the temporary file
  1815. * when we're done.
  1816. *
  1817. * Return the fd for the newly opened file, and store working data in
  1818. * *<b>data_out</b>. The caller should not close the fd manually:
  1819. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1820. * Returns -1 on failure.
  1821. *
  1822. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1823. * as true and the flag O_EXCL is treated as false.
  1824. *
  1825. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1826. * write()". We don't do that.
  1827. */
  1828. int
  1829. start_writing_to_file(const char *fname, int open_flags, int mode,
  1830. open_file_t **data_out)
  1831. {
  1832. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1833. const char *open_name;
  1834. int append = 0;
  1835. tor_assert(fname);
  1836. tor_assert(data_out);
  1837. #if (O_BINARY != 0 && O_TEXT != 0)
  1838. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1839. #endif
  1840. new_file->fd = -1;
  1841. new_file->filename = tor_strdup(fname);
  1842. if (open_flags & O_APPEND) {
  1843. open_name = fname;
  1844. new_file->rename_on_close = 0;
  1845. append = 1;
  1846. open_flags &= ~O_APPEND;
  1847. } else {
  1848. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1849. open_name = new_file->tempname;
  1850. /* We always replace an existing temporary file if there is one. */
  1851. open_flags |= O_CREAT|O_TRUNC;
  1852. open_flags &= ~O_EXCL;
  1853. new_file->rename_on_close = 1;
  1854. }
  1855. if (open_flags & O_BINARY)
  1856. new_file->binary = 1;
  1857. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1858. if (new_file->fd < 0) {
  1859. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1860. open_name, fname, strerror(errno));
  1861. goto err;
  1862. }
  1863. if (append) {
  1864. if (tor_fd_seekend(new_file->fd) < 0) {
  1865. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1866. strerror(errno));
  1867. goto err;
  1868. }
  1869. }
  1870. *data_out = new_file;
  1871. return new_file->fd;
  1872. err:
  1873. if (new_file->fd >= 0)
  1874. close(new_file->fd);
  1875. *data_out = NULL;
  1876. tor_free(new_file->filename);
  1877. tor_free(new_file->tempname);
  1878. tor_free(new_file);
  1879. return -1;
  1880. }
  1881. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1882. * that can be used to write to the same file. The caller should not mix
  1883. * stdio calls with non-stdio calls. */
  1884. FILE *
  1885. fdopen_file(open_file_t *file_data)
  1886. {
  1887. tor_assert(file_data);
  1888. if (file_data->stdio_file)
  1889. return file_data->stdio_file;
  1890. tor_assert(file_data->fd >= 0);
  1891. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1892. file_data->binary?"ab":"a"))) {
  1893. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1894. file_data->fd, strerror(errno));
  1895. }
  1896. return file_data->stdio_file;
  1897. }
  1898. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1899. * for start_writing_to_file, but */
  1900. FILE *
  1901. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1902. open_file_t **data_out)
  1903. {
  1904. FILE *res;
  1905. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1906. return NULL;
  1907. if (!(res = fdopen_file(*data_out))) {
  1908. abort_writing_to_file(*data_out);
  1909. *data_out = NULL;
  1910. }
  1911. return res;
  1912. }
  1913. /** Helper function: close and free the underlying file and memory in
  1914. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1915. * that file (if abort_write is true) or replaces the target file with
  1916. * the temporary file (if abort_write is false). */
  1917. static int
  1918. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1919. {
  1920. int r = 0;
  1921. tor_assert(file_data && file_data->filename);
  1922. if (file_data->stdio_file) {
  1923. if (fclose(file_data->stdio_file)) {
  1924. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1925. strerror(errno));
  1926. abort_write = r = -1;
  1927. }
  1928. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1929. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1930. strerror(errno));
  1931. abort_write = r = -1;
  1932. }
  1933. if (file_data->rename_on_close) {
  1934. tor_assert(file_data->tempname && file_data->filename);
  1935. if (abort_write) {
  1936. unlink(file_data->tempname);
  1937. } else {
  1938. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1939. if (replace_file(file_data->tempname, file_data->filename)) {
  1940. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1941. strerror(errno));
  1942. r = -1;
  1943. }
  1944. }
  1945. }
  1946. tor_free(file_data->filename);
  1947. tor_free(file_data->tempname);
  1948. tor_free(file_data);
  1949. return r;
  1950. }
  1951. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1952. * needed, and if using a temporary file, replace the original file with
  1953. * the temporary file. */
  1954. int
  1955. finish_writing_to_file(open_file_t *file_data)
  1956. {
  1957. return finish_writing_to_file_impl(file_data, 0);
  1958. }
  1959. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1960. * needed, and if using a temporary file, delete it. */
  1961. int
  1962. abort_writing_to_file(open_file_t *file_data)
  1963. {
  1964. return finish_writing_to_file_impl(file_data, 1);
  1965. }
  1966. /** Helper: given a set of flags as passed to open(2), open the file
  1967. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1968. * the file. Do so as atomically as possible e.g. by opening temp files and
  1969. * renaming. */
  1970. static int
  1971. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1972. int open_flags)
  1973. {
  1974. open_file_t *file = NULL;
  1975. int fd;
  1976. ssize_t result;
  1977. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1978. if (fd<0)
  1979. return -1;
  1980. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1981. {
  1982. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1983. if (result < 0) {
  1984. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1985. strerror(errno));
  1986. goto err;
  1987. }
  1988. tor_assert((size_t)result == chunk->len);
  1989. });
  1990. return finish_writing_to_file(file);
  1991. err:
  1992. abort_writing_to_file(file);
  1993. return -1;
  1994. }
  1995. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1996. * <b>fname</b>, overwriting or creating the file as necessary. */
  1997. int
  1998. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1999. {
  2000. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  2001. return write_chunks_to_file_impl(fname, chunks, flags);
  2002. }
  2003. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  2004. using the open() flags passed in <b>flags</b>. */
  2005. static int
  2006. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  2007. int flags)
  2008. {
  2009. int r;
  2010. sized_chunk_t c = { str, len };
  2011. smartlist_t *chunks = smartlist_new();
  2012. smartlist_add(chunks, &c);
  2013. r = write_chunks_to_file_impl(fname, chunks, flags);
  2014. smartlist_free(chunks);
  2015. return r;
  2016. }
  2017. /** As write_str_to_file, but does not assume a NUL-terminated
  2018. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  2019. int
  2020. write_bytes_to_file(const char *fname, const char *str, size_t len,
  2021. int bin)
  2022. {
  2023. return write_bytes_to_file_impl(fname, str, len,
  2024. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  2025. }
  2026. /** As write_bytes_to_file, but if the file already exists, append the bytes
  2027. * to the end of the file instead of overwriting it. */
  2028. int
  2029. append_bytes_to_file(const char *fname, const char *str, size_t len,
  2030. int bin)
  2031. {
  2032. return write_bytes_to_file_impl(fname, str, len,
  2033. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  2034. }
  2035. /** Like write_str_to_file(), but also return -1 if there was a file
  2036. already residing in <b>fname</b>. */
  2037. int
  2038. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  2039. int bin)
  2040. {
  2041. return write_bytes_to_file_impl(fname, str, len,
  2042. OPEN_FLAGS_DONT_REPLACE|
  2043. (bin?O_BINARY:O_TEXT));
  2044. }
  2045. /**
  2046. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  2047. * (or similar) file descriptor for which the size of the file isn't
  2048. * known ahead of time. Return NULL on failure, and a NUL-terminated
  2049. * string on success. On success, set <b>sz_out</b> to the number of
  2050. * bytes read.
  2051. */
  2052. char *
  2053. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  2054. {
  2055. ssize_t r;
  2056. size_t pos = 0;
  2057. char *string = NULL;
  2058. size_t string_max = 0;
  2059. if (max_bytes_to_read+1 >= SIZE_T_CEILING)
  2060. return NULL;
  2061. do {
  2062. /* XXXX This "add 1K" approach is a little goofy; if we care about
  2063. * performance here, we should be doubling. But in practice we shouldn't
  2064. * be using this function on big files anyway. */
  2065. string_max = pos + 1024;
  2066. if (string_max > max_bytes_to_read)
  2067. string_max = max_bytes_to_read + 1;
  2068. string = tor_realloc(string, string_max);
  2069. r = read(fd, string + pos, string_max - pos - 1);
  2070. if (r < 0) {
  2071. tor_free(string);
  2072. return NULL;
  2073. }
  2074. pos += r;
  2075. } while (r > 0 && pos < max_bytes_to_read);
  2076. *sz_out = pos;
  2077. string[pos] = '\0';
  2078. return string;
  2079. }
  2080. /** Read the contents of <b>filename</b> into a newly allocated
  2081. * string; return the string on success or NULL on failure.
  2082. *
  2083. * If <b>stat_out</b> is provided, store the result of stat()ing the
  2084. * file into <b>stat_out</b>.
  2085. *
  2086. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  2087. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  2088. * doesn't exist.
  2089. */
  2090. /*
  2091. * This function <em>may</em> return an erroneous result if the file
  2092. * is modified while it is running, but must not crash or overflow.
  2093. * Right now, the error case occurs when the file length grows between
  2094. * the call to stat and the call to read_all: the resulting string will
  2095. * be truncated.
  2096. */
  2097. char *
  2098. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  2099. {
  2100. int fd; /* router file */
  2101. struct stat statbuf;
  2102. char *string;
  2103. ssize_t r;
  2104. int bin = flags & RFTS_BIN;
  2105. tor_assert(filename);
  2106. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  2107. if (fd<0) {
  2108. int severity = LOG_WARN;
  2109. int save_errno = errno;
  2110. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  2111. severity = LOG_INFO;
  2112. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  2113. strerror(errno));
  2114. errno = save_errno;
  2115. return NULL;
  2116. }
  2117. if (fstat(fd, &statbuf)<0) {
  2118. int save_errno = errno;
  2119. close(fd);
  2120. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  2121. errno = save_errno;
  2122. return NULL;
  2123. }
  2124. #ifndef _WIN32
  2125. /** When we detect that we're reading from a FIFO, don't read more than
  2126. * this many bytes. It's insane overkill for most uses. */
  2127. #define FIFO_READ_MAX (1024*1024)
  2128. if (S_ISFIFO(statbuf.st_mode)) {
  2129. size_t sz = 0;
  2130. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  2131. if (string && stat_out) {
  2132. statbuf.st_size = sz;
  2133. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2134. }
  2135. close(fd);
  2136. return string;
  2137. }
  2138. #endif
  2139. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  2140. close(fd);
  2141. return NULL;
  2142. }
  2143. string = tor_malloc((size_t)(statbuf.st_size+1));
  2144. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  2145. if (r<0) {
  2146. int save_errno = errno;
  2147. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  2148. strerror(errno));
  2149. tor_free(string);
  2150. close(fd);
  2151. errno = save_errno;
  2152. return NULL;
  2153. }
  2154. string[r] = '\0'; /* NUL-terminate the result. */
  2155. #if defined(_WIN32) || defined(__CYGWIN__)
  2156. if (!bin && strchr(string, '\r')) {
  2157. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  2158. "when reading %s. Coping.",
  2159. filename);
  2160. tor_strstrip(string, "\r");
  2161. r = strlen(string);
  2162. }
  2163. if (!bin) {
  2164. statbuf.st_size = (size_t) r;
  2165. } else
  2166. #endif
  2167. if (r != statbuf.st_size) {
  2168. /* Unless we're using text mode on win32, we'd better have an exact
  2169. * match for size. */
  2170. int save_errno = errno;
  2171. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  2172. (int)r, (long)statbuf.st_size,filename);
  2173. tor_free(string);
  2174. close(fd);
  2175. errno = save_errno;
  2176. return NULL;
  2177. }
  2178. close(fd);
  2179. if (stat_out) {
  2180. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2181. }
  2182. return string;
  2183. }
  2184. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2185. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2186. * decode its contents into a newly allocated string. On success, assign this
  2187. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2188. * provided), and return a pointer to the position in <b>s</b> immediately
  2189. * after the string. On failure, return NULL.
  2190. */
  2191. static const char *
  2192. unescape_string(const char *s, char **result, size_t *size_out)
  2193. {
  2194. const char *cp;
  2195. char *out;
  2196. if (s[0] != '\"')
  2197. return NULL;
  2198. cp = s+1;
  2199. while (1) {
  2200. switch (*cp) {
  2201. case '\0':
  2202. case '\n':
  2203. return NULL;
  2204. case '\"':
  2205. goto end_of_loop;
  2206. case '\\':
  2207. if (cp[1] == 'x' || cp[1] == 'X') {
  2208. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  2209. return NULL;
  2210. cp += 4;
  2211. } else if (TOR_ISODIGIT(cp[1])) {
  2212. cp += 2;
  2213. if (TOR_ISODIGIT(*cp)) ++cp;
  2214. if (TOR_ISODIGIT(*cp)) ++cp;
  2215. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  2216. || cp[1] == '\\' || cp[1] == '\'') {
  2217. cp += 2;
  2218. } else {
  2219. return NULL;
  2220. }
  2221. break;
  2222. default:
  2223. ++cp;
  2224. break;
  2225. }
  2226. }
  2227. end_of_loop:
  2228. out = *result = tor_malloc(cp-s + 1);
  2229. cp = s+1;
  2230. while (1) {
  2231. switch (*cp)
  2232. {
  2233. case '\"':
  2234. *out = '\0';
  2235. if (size_out) *size_out = out - *result;
  2236. return cp+1;
  2237. case '\0':
  2238. tor_fragile_assert();
  2239. tor_free(*result);
  2240. return NULL;
  2241. case '\\':
  2242. switch (cp[1])
  2243. {
  2244. case 'n': *out++ = '\n'; cp += 2; break;
  2245. case 'r': *out++ = '\r'; cp += 2; break;
  2246. case 't': *out++ = '\t'; cp += 2; break;
  2247. case 'x': case 'X':
  2248. {
  2249. int x1, x2;
  2250. x1 = hex_decode_digit(cp[2]);
  2251. x2 = hex_decode_digit(cp[3]);
  2252. if (x1 == -1 || x2 == -1) {
  2253. tor_free(*result);
  2254. return NULL;
  2255. }
  2256. *out++ = ((x1<<4) + x2);
  2257. cp += 4;
  2258. }
  2259. break;
  2260. case '0': case '1': case '2': case '3': case '4': case '5':
  2261. case '6': case '7':
  2262. {
  2263. int n = cp[1]-'0';
  2264. cp += 2;
  2265. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2266. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2267. if (n > 255) { tor_free(*result); return NULL; }
  2268. *out++ = (char)n;
  2269. }
  2270. break;
  2271. case '\'':
  2272. case '\"':
  2273. case '\\':
  2274. case '\?':
  2275. *out++ = cp[1];
  2276. cp += 2;
  2277. break;
  2278. default:
  2279. tor_free(*result); return NULL;
  2280. }
  2281. break;
  2282. default:
  2283. *out++ = *cp++;
  2284. }
  2285. }
  2286. }
  2287. /** Given a string containing part of a configuration file or similar format,
  2288. * advance past comments and whitespace and try to parse a single line. If we
  2289. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2290. * key portion and *<b>value_out</b> to a new string holding the value portion
  2291. * of the line, and return a pointer to the start of the next line. If we run
  2292. * out of data, return a pointer to the end of the string. If we encounter an
  2293. * error, return NULL and set *<b>err_out</b> (if provided) to an error
  2294. * message.
  2295. */
  2296. const char *
  2297. parse_config_line_from_str_verbose(const char *line, char **key_out,
  2298. char **value_out,
  2299. const char **err_out)
  2300. {
  2301. /* I believe the file format here is supposed to be:
  2302. FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
  2303. EMPTYLASTLINE = SPACE* | COMMENT
  2304. EMPTYLINE = EMPTYLASTLINE NL
  2305. SPACE = ' ' | '\r' | '\t'
  2306. COMMENT = '#' NOT-NL*
  2307. NOT-NL = Any character except '\n'
  2308. NL = '\n'
  2309. LASTLINE = SPACE* KEY SPACE* VALUES
  2310. LINE = LASTLINE NL
  2311. KEY = KEYCHAR+
  2312. KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
  2313. VALUES = QUOTEDVALUE | NORMALVALUE
  2314. QUOTEDVALUE = QUOTE QVCHAR* QUOTE EOLSPACE?
  2315. QUOTE = '"'
  2316. QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
  2317. ESC = "\\"
  2318. OCTAL = ODIGIT (ODIGIT ODIGIT?)?
  2319. HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
  2320. ODIGIT = '0' .. '7'
  2321. HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
  2322. EOLSPACE = SPACE* COMMENT?
  2323. NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
  2324. VALCHAR = Any character except ESC, '#', and '\n'
  2325. ESC_IGNORE = Any character except '#' or '\n'
  2326. CONTINUATION = ESC NL ( COMMENT NL )*
  2327. */
  2328. const char *key, *val, *cp;
  2329. int continuation = 0;
  2330. tor_assert(key_out);
  2331. tor_assert(value_out);
  2332. *key_out = *value_out = NULL;
  2333. key = val = NULL;
  2334. /* Skip until the first keyword. */
  2335. while (1) {
  2336. while (TOR_ISSPACE(*line))
  2337. ++line;
  2338. if (*line == '#') {
  2339. while (*line && *line != '\n')
  2340. ++line;
  2341. } else {
  2342. break;
  2343. }
  2344. }
  2345. if (!*line) { /* End of string? */
  2346. *key_out = *value_out = NULL;
  2347. return line;
  2348. }
  2349. /* Skip until the next space or \ followed by newline. */
  2350. key = line;
  2351. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2352. ! (line[0] == '\\' && line[1] == '\n'))
  2353. ++line;
  2354. *key_out = tor_strndup(key, line-key);
  2355. /* Skip until the value. */
  2356. while (*line == ' ' || *line == '\t')
  2357. ++line;
  2358. val = line;
  2359. /* Find the end of the line. */
  2360. if (*line == '\"') { // XXX No continuation handling is done here
  2361. if (!(line = unescape_string(line, value_out, NULL))) {
  2362. if (err_out)
  2363. *err_out = "Invalid escape sequence in quoted string";
  2364. return NULL;
  2365. }
  2366. while (*line == ' ' || *line == '\t')
  2367. ++line;
  2368. if (*line && *line != '#' && *line != '\n') {
  2369. if (err_out)
  2370. *err_out = "Excess data after quoted string";
  2371. return NULL;
  2372. }
  2373. } else {
  2374. /* Look for the end of the line. */
  2375. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2376. if (*line == '\\' && line[1] == '\n') {
  2377. continuation = 1;
  2378. line += 2;
  2379. } else if (*line == '#') {
  2380. do {
  2381. ++line;
  2382. } while (*line && *line != '\n');
  2383. if (*line == '\n')
  2384. ++line;
  2385. } else {
  2386. ++line;
  2387. }
  2388. }
  2389. if (*line == '\n') {
  2390. cp = line++;
  2391. } else {
  2392. cp = line;
  2393. }
  2394. /* Now back cp up to be the last nonspace character */
  2395. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2396. --cp;
  2397. tor_assert(cp >= val);
  2398. /* Now copy out and decode the value. */
  2399. *value_out = tor_strndup(val, cp-val);
  2400. if (continuation) {
  2401. char *v_out, *v_in;
  2402. v_out = v_in = *value_out;
  2403. while (*v_in) {
  2404. if (*v_in == '#') {
  2405. do {
  2406. ++v_in;
  2407. } while (*v_in && *v_in != '\n');
  2408. if (*v_in == '\n')
  2409. ++v_in;
  2410. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2411. v_in += 2;
  2412. } else {
  2413. *v_out++ = *v_in++;
  2414. }
  2415. }
  2416. *v_out = '\0';
  2417. }
  2418. }
  2419. if (*line == '#') {
  2420. do {
  2421. ++line;
  2422. } while (*line && *line != '\n');
  2423. }
  2424. while (TOR_ISSPACE(*line)) ++line;
  2425. return line;
  2426. }
  2427. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2428. * string. */
  2429. char *
  2430. expand_filename(const char *filename)
  2431. {
  2432. tor_assert(filename);
  2433. #ifdef _WIN32
  2434. return tor_strdup(filename);
  2435. #else
  2436. if (*filename == '~') {
  2437. char *home, *result=NULL;
  2438. const char *rest;
  2439. if (filename[1] == '/' || filename[1] == '\0') {
  2440. home = getenv("HOME");
  2441. if (!home) {
  2442. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2443. "expanding \"%s\"; defaulting to \"\".", filename);
  2444. home = tor_strdup("");
  2445. } else {
  2446. home = tor_strdup(home);
  2447. }
  2448. rest = strlen(filename)>=2?(filename+2):"";
  2449. } else {
  2450. #ifdef HAVE_PWD_H
  2451. char *username, *slash;
  2452. slash = strchr(filename, '/');
  2453. if (slash)
  2454. username = tor_strndup(filename+1,slash-filename-1);
  2455. else
  2456. username = tor_strdup(filename+1);
  2457. if (!(home = get_user_homedir(username))) {
  2458. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2459. tor_free(username);
  2460. return NULL;
  2461. }
  2462. tor_free(username);
  2463. rest = slash ? (slash+1) : "";
  2464. #else
  2465. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2466. return tor_strdup(filename);
  2467. #endif
  2468. }
  2469. tor_assert(home);
  2470. /* Remove trailing slash. */
  2471. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2472. home[strlen(home)-1] = '\0';
  2473. }
  2474. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2475. tor_free(home);
  2476. return result;
  2477. } else {
  2478. return tor_strdup(filename);
  2479. }
  2480. #endif
  2481. }
  2482. #define MAX_SCANF_WIDTH 9999
  2483. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2484. * NOTE: requires that its input be in-bounds. */
  2485. static int
  2486. digit_to_num(char d)
  2487. {
  2488. int num = ((int)d) - (int)'0';
  2489. tor_assert(num <= 9 && num >= 0);
  2490. return num;
  2491. }
  2492. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2493. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2494. * success, store the result in <b>out</b>, advance bufp to the next
  2495. * character, and return 0. On failure, return -1. */
  2496. static int
  2497. scan_unsigned(const char **bufp, unsigned long *out, int width, int base)
  2498. {
  2499. unsigned long result = 0;
  2500. int scanned_so_far = 0;
  2501. const int hex = base==16;
  2502. tor_assert(base == 10 || base == 16);
  2503. if (!bufp || !*bufp || !out)
  2504. return -1;
  2505. if (width<0)
  2506. width=MAX_SCANF_WIDTH;
  2507. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2508. && scanned_so_far < width) {
  2509. int digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2510. unsigned long new_result = result * base + digit;
  2511. if (new_result < result)
  2512. return -1; /* over/underflow. */
  2513. result = new_result;
  2514. ++scanned_so_far;
  2515. }
  2516. if (!scanned_so_far) /* No actual digits scanned */
  2517. return -1;
  2518. *out = result;
  2519. return 0;
  2520. }
  2521. /** Helper: Read an signed int from *<b>bufp</b> of up to <b>width</b>
  2522. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2523. * success, store the result in <b>out</b>, advance bufp to the next
  2524. * character, and return 0. On failure, return -1. */
  2525. static int
  2526. scan_signed(const char **bufp, long *out, int width)
  2527. {
  2528. int neg = 0;
  2529. unsigned long result = 0;
  2530. if (!bufp || !*bufp || !out)
  2531. return -1;
  2532. if (width<0)
  2533. width=MAX_SCANF_WIDTH;
  2534. if (**bufp == '-') {
  2535. neg = 1;
  2536. ++*bufp;
  2537. --width;
  2538. }
  2539. if (scan_unsigned(bufp, &result, width, 10) < 0)
  2540. return -1;
  2541. if (neg) {
  2542. if (result > ((unsigned long)LONG_MAX) + 1)
  2543. return -1; /* Underflow */
  2544. *out = -(long)result;
  2545. } else {
  2546. if (result > LONG_MAX)
  2547. return -1; /* Overflow */
  2548. *out = (long)result;
  2549. }
  2550. return 0;
  2551. }
  2552. /** Helper: Read a decimal-formatted double from *<b>bufp</b> of up to
  2553. * <b>width</b> characters. (Handle arbitrary width if <b>width</b> is less
  2554. * than 0.) On success, store the result in <b>out</b>, advance bufp to the
  2555. * next character, and return 0. On failure, return -1. */
  2556. static int
  2557. scan_double(const char **bufp, double *out, int width)
  2558. {
  2559. int neg = 0;
  2560. double result = 0;
  2561. int scanned_so_far = 0;
  2562. if (!bufp || !*bufp || !out)
  2563. return -1;
  2564. if (width<0)
  2565. width=MAX_SCANF_WIDTH;
  2566. if (**bufp == '-') {
  2567. neg = 1;
  2568. ++*bufp;
  2569. }
  2570. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2571. const int digit = digit_to_num(*(*bufp)++);
  2572. result = result * 10 + digit;
  2573. ++scanned_so_far;
  2574. }
  2575. if (**bufp == '.') {
  2576. double fracval = 0, denominator = 1;
  2577. ++*bufp;
  2578. ++scanned_so_far;
  2579. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2580. const int digit = digit_to_num(*(*bufp)++);
  2581. fracval = fracval * 10 + digit;
  2582. denominator *= 10;
  2583. ++scanned_so_far;
  2584. }
  2585. result += fracval / denominator;
  2586. }
  2587. if (!scanned_so_far) /* No actual digits scanned */
  2588. return -1;
  2589. *out = neg ? -result : result;
  2590. return 0;
  2591. }
  2592. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2593. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2594. * to the next non-space character or the EOS. */
  2595. static int
  2596. scan_string(const char **bufp, char *out, int width)
  2597. {
  2598. int scanned_so_far = 0;
  2599. if (!bufp || !out || width < 0)
  2600. return -1;
  2601. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2602. *out++ = *(*bufp)++;
  2603. ++scanned_so_far;
  2604. }
  2605. *out = '\0';
  2606. return 0;
  2607. }
  2608. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2609. * restricted pattern format. For more info on what it supports, see
  2610. * tor_sscanf() documentation. */
  2611. int
  2612. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2613. {
  2614. int n_matched = 0;
  2615. while (*pattern) {
  2616. if (*pattern != '%') {
  2617. if (*buf == *pattern) {
  2618. ++buf;
  2619. ++pattern;
  2620. continue;
  2621. } else {
  2622. return n_matched;
  2623. }
  2624. } else {
  2625. int width = -1;
  2626. int longmod = 0;
  2627. ++pattern;
  2628. if (TOR_ISDIGIT(*pattern)) {
  2629. width = digit_to_num(*pattern++);
  2630. while (TOR_ISDIGIT(*pattern)) {
  2631. width *= 10;
  2632. width += digit_to_num(*pattern++);
  2633. if (width > MAX_SCANF_WIDTH)
  2634. return -1;
  2635. }
  2636. if (!width) /* No zero-width things. */
  2637. return -1;
  2638. }
  2639. if (*pattern == 'l') {
  2640. longmod = 1;
  2641. ++pattern;
  2642. }
  2643. if (*pattern == 'u' || *pattern == 'x') {
  2644. unsigned long u;
  2645. const int base = (*pattern == 'u') ? 10 : 16;
  2646. if (!*buf)
  2647. return n_matched;
  2648. if (scan_unsigned(&buf, &u, width, base)<0)
  2649. return n_matched;
  2650. if (longmod) {
  2651. unsigned long *out = va_arg(ap, unsigned long *);
  2652. *out = u;
  2653. } else {
  2654. unsigned *out = va_arg(ap, unsigned *);
  2655. if (u > UINT_MAX)
  2656. return n_matched;
  2657. *out = (unsigned) u;
  2658. }
  2659. ++pattern;
  2660. ++n_matched;
  2661. } else if (*pattern == 'f') {
  2662. double *d = va_arg(ap, double *);
  2663. if (!longmod)
  2664. return -1; /* float not supported */
  2665. if (!*buf)
  2666. return n_matched;
  2667. if (scan_double(&buf, d, width)<0)
  2668. return n_matched;
  2669. ++pattern;
  2670. ++n_matched;
  2671. } else if (*pattern == 'd') {
  2672. long lng=0;
  2673. if (scan_signed(&buf, &lng, width)<0)
  2674. return n_matched;
  2675. if (longmod) {
  2676. long *out = va_arg(ap, long *);
  2677. *out = lng;
  2678. } else {
  2679. int *out = va_arg(ap, int *);
  2680. if (lng < INT_MIN || lng > INT_MAX)
  2681. return n_matched;
  2682. *out = (int)lng;
  2683. }
  2684. ++pattern;
  2685. ++n_matched;
  2686. } else if (*pattern == 's') {
  2687. char *s = va_arg(ap, char *);
  2688. if (longmod)
  2689. return -1;
  2690. if (width < 0)
  2691. return -1;
  2692. if (scan_string(&buf, s, width)<0)
  2693. return n_matched;
  2694. ++pattern;
  2695. ++n_matched;
  2696. } else if (*pattern == 'c') {
  2697. char *ch = va_arg(ap, char *);
  2698. if (longmod)
  2699. return -1;
  2700. if (width != -1)
  2701. return -1;
  2702. if (!*buf)
  2703. return n_matched;
  2704. *ch = *buf++;
  2705. ++pattern;
  2706. ++n_matched;
  2707. } else if (*pattern == '%') {
  2708. if (*buf != '%')
  2709. return n_matched;
  2710. if (longmod)
  2711. return -1;
  2712. ++buf;
  2713. ++pattern;
  2714. } else {
  2715. return -1; /* Unrecognized pattern component. */
  2716. }
  2717. }
  2718. }
  2719. return n_matched;
  2720. }
  2721. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2722. * and store the results in the corresponding argument fields. Differs from
  2723. * sscanf in that:
  2724. * <ul><li>It only handles %u, %lu, %x, %lx, %<NUM>s, %d, %ld, %lf, and %c.
  2725. * <li>It only handles decimal inputs for %lf. (12.3, not 1.23e1)
  2726. * <li>It does not handle arbitrarily long widths.
  2727. * <li>Numbers do not consume any space characters.
  2728. * <li>It is locale-independent.
  2729. * <li>%u and %x do not consume any space.
  2730. * <li>It returns -1 on malformed patterns.</ul>
  2731. *
  2732. * (As with other locale-independent functions, we need this to parse data that
  2733. * is in ASCII without worrying that the C library's locale-handling will make
  2734. * miscellaneous characters look like numbers, spaces, and so on.)
  2735. */
  2736. int
  2737. tor_sscanf(const char *buf, const char *pattern, ...)
  2738. {
  2739. int r;
  2740. va_list ap;
  2741. va_start(ap, pattern);
  2742. r = tor_vsscanf(buf, pattern, ap);
  2743. va_end(ap);
  2744. return r;
  2745. }
  2746. /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
  2747. * to <b>sl</b>. */
  2748. void
  2749. smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  2750. {
  2751. va_list ap;
  2752. va_start(ap, pattern);
  2753. smartlist_add_vasprintf(sl, pattern, ap);
  2754. va_end(ap);
  2755. }
  2756. /** va_list-based backend of smartlist_add_asprintf. */
  2757. void
  2758. smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  2759. va_list args)
  2760. {
  2761. char *str = NULL;
  2762. tor_vasprintf(&str, pattern, args);
  2763. tor_assert(str != NULL);
  2764. smartlist_add(sl, str);
  2765. }
  2766. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2767. * Return NULL on error or if <b>dirname</b> is not a directory.
  2768. */
  2769. smartlist_t *
  2770. tor_listdir(const char *dirname)
  2771. {
  2772. smartlist_t *result;
  2773. #ifdef _WIN32
  2774. char *pattern=NULL;
  2775. TCHAR tpattern[MAX_PATH] = {0};
  2776. char name[MAX_PATH*2+1] = {0};
  2777. HANDLE handle;
  2778. WIN32_FIND_DATA findData;
  2779. tor_asprintf(&pattern, "%s\\*", dirname);
  2780. #ifdef UNICODE
  2781. mbstowcs(tpattern,pattern,MAX_PATH);
  2782. #else
  2783. strlcpy(tpattern, pattern, MAX_PATH);
  2784. #endif
  2785. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2786. tor_free(pattern);
  2787. return NULL;
  2788. }
  2789. result = smartlist_new();
  2790. while (1) {
  2791. #ifdef UNICODE
  2792. wcstombs(name,findData.cFileName,MAX_PATH);
  2793. name[sizeof(name)-1] = '\0';
  2794. #else
  2795. strlcpy(name,findData.cFileName,sizeof(name));
  2796. #endif
  2797. if (strcmp(name, ".") &&
  2798. strcmp(name, "..")) {
  2799. smartlist_add(result, tor_strdup(name));
  2800. }
  2801. if (!FindNextFile(handle, &findData)) {
  2802. DWORD err;
  2803. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2804. char *errstr = format_win32_error(err);
  2805. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2806. tor_free(errstr);
  2807. }
  2808. break;
  2809. }
  2810. }
  2811. FindClose(handle);
  2812. tor_free(pattern);
  2813. #else
  2814. DIR *d;
  2815. struct dirent *de;
  2816. if (!(d = opendir(dirname)))
  2817. return NULL;
  2818. result = smartlist_new();
  2819. while ((de = readdir(d))) {
  2820. if (!strcmp(de->d_name, ".") ||
  2821. !strcmp(de->d_name, ".."))
  2822. continue;
  2823. smartlist_add(result, tor_strdup(de->d_name));
  2824. }
  2825. closedir(d);
  2826. #endif
  2827. return result;
  2828. }
  2829. /** Return true iff <b>filename</b> is a relative path. */
  2830. int
  2831. path_is_relative(const char *filename)
  2832. {
  2833. if (filename && filename[0] == '/')
  2834. return 0;
  2835. #ifdef _WIN32
  2836. else if (filename && filename[0] == '\\')
  2837. return 0;
  2838. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2839. filename[1] == ':' && filename[2] == '\\')
  2840. return 0;
  2841. #endif
  2842. else
  2843. return 1;
  2844. }
  2845. /* =====
  2846. * Process helpers
  2847. * ===== */
  2848. #ifndef _WIN32
  2849. /* Based on code contributed by christian grothoff */
  2850. /** True iff we've called start_daemon(). */
  2851. static int start_daemon_called = 0;
  2852. /** True iff we've called finish_daemon(). */
  2853. static int finish_daemon_called = 0;
  2854. /** Socketpair used to communicate between parent and child process while
  2855. * daemonizing. */
  2856. static int daemon_filedes[2];
  2857. /** Start putting the process into daemon mode: fork and drop all resources
  2858. * except standard fds. The parent process never returns, but stays around
  2859. * until finish_daemon is called. (Note: it's safe to call this more
  2860. * than once: calls after the first are ignored.)
  2861. */
  2862. void
  2863. start_daemon(void)
  2864. {
  2865. pid_t pid;
  2866. if (start_daemon_called)
  2867. return;
  2868. start_daemon_called = 1;
  2869. if (pipe(daemon_filedes)) {
  2870. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2871. exit(1);
  2872. }
  2873. pid = fork();
  2874. if (pid < 0) {
  2875. log_err(LD_GENERAL,"fork failed. Exiting.");
  2876. exit(1);
  2877. }
  2878. if (pid) { /* Parent */
  2879. int ok;
  2880. char c;
  2881. close(daemon_filedes[1]); /* we only read */
  2882. ok = -1;
  2883. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2884. if (c == '.')
  2885. ok = 1;
  2886. }
  2887. fflush(stdout);
  2888. if (ok == 1)
  2889. exit(0);
  2890. else
  2891. exit(1); /* child reported error */
  2892. } else { /* Child */
  2893. close(daemon_filedes[0]); /* we only write */
  2894. pid = setsid(); /* Detach from controlling terminal */
  2895. /*
  2896. * Fork one more time, so the parent (the session group leader) can exit.
  2897. * This means that we, as a non-session group leader, can never regain a
  2898. * controlling terminal. This part is recommended by Stevens's
  2899. * _Advanced Programming in the Unix Environment_.
  2900. */
  2901. if (fork() != 0) {
  2902. exit(0);
  2903. }
  2904. set_main_thread(); /* We are now the main thread. */
  2905. return;
  2906. }
  2907. }
  2908. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2909. * the parent process to exit. (Note: it's safe to call this more than once:
  2910. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2911. * been called already.)
  2912. */
  2913. void
  2914. finish_daemon(const char *desired_cwd)
  2915. {
  2916. int nullfd;
  2917. char c = '.';
  2918. if (finish_daemon_called)
  2919. return;
  2920. if (!start_daemon_called)
  2921. start_daemon();
  2922. finish_daemon_called = 1;
  2923. if (!desired_cwd)
  2924. desired_cwd = "/";
  2925. /* Don't hold the wrong FS mounted */
  2926. if (chdir(desired_cwd) < 0) {
  2927. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2928. exit(1);
  2929. }
  2930. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2931. if (nullfd < 0) {
  2932. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2933. exit(1);
  2934. }
  2935. /* close fds linking to invoking terminal, but
  2936. * close usual incoming fds, but redirect them somewhere
  2937. * useful so the fds don't get reallocated elsewhere.
  2938. */
  2939. if (dup2(nullfd,0) < 0 ||
  2940. dup2(nullfd,1) < 0 ||
  2941. dup2(nullfd,2) < 0) {
  2942. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2943. exit(1);
  2944. }
  2945. if (nullfd > 2)
  2946. close(nullfd);
  2947. /* signal success */
  2948. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2949. log_err(LD_GENERAL,"write failed. Exiting.");
  2950. }
  2951. close(daemon_filedes[1]);
  2952. }
  2953. #else
  2954. /* defined(_WIN32) */
  2955. void
  2956. start_daemon(void)
  2957. {
  2958. }
  2959. void
  2960. finish_daemon(const char *cp)
  2961. {
  2962. (void)cp;
  2963. }
  2964. #endif
  2965. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2966. */
  2967. void
  2968. write_pidfile(char *filename)
  2969. {
  2970. FILE *pidfile;
  2971. if ((pidfile = fopen(filename, "w")) == NULL) {
  2972. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2973. strerror(errno));
  2974. } else {
  2975. #ifdef _WIN32
  2976. fprintf(pidfile, "%d\n", (int)_getpid());
  2977. #else
  2978. fprintf(pidfile, "%d\n", (int)getpid());
  2979. #endif
  2980. fclose(pidfile);
  2981. }
  2982. }
  2983. #ifdef _WIN32
  2984. HANDLE
  2985. load_windows_system_library(const TCHAR *library_name)
  2986. {
  2987. TCHAR path[MAX_PATH];
  2988. unsigned n;
  2989. n = GetSystemDirectory(path, MAX_PATH);
  2990. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2991. return 0;
  2992. _tcscat(path, TEXT("\\"));
  2993. _tcscat(path, library_name);
  2994. return LoadLibrary(path);
  2995. }
  2996. #endif
  2997. /** Format a single argument for being put on a Windows command line.
  2998. * Returns a newly allocated string */
  2999. static char *
  3000. format_win_cmdline_argument(const char *arg)
  3001. {
  3002. char *formatted_arg;
  3003. char need_quotes;
  3004. const char *c;
  3005. int i;
  3006. int bs_counter = 0;
  3007. /* Backslash we can point to when one is inserted into the string */
  3008. const char backslash = '\\';
  3009. /* Smartlist of *char */
  3010. smartlist_t *arg_chars;
  3011. arg_chars = smartlist_new();
  3012. /* Quote string if it contains whitespace or is empty */
  3013. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  3014. /* Build up smartlist of *chars */
  3015. for (c=arg; *c != '\0'; c++) {
  3016. if ('"' == *c) {
  3017. /* Double up backslashes preceding a quote */
  3018. for (i=0; i<(bs_counter*2); i++)
  3019. smartlist_add(arg_chars, (void*)&backslash);
  3020. bs_counter = 0;
  3021. /* Escape the quote */
  3022. smartlist_add(arg_chars, (void*)&backslash);
  3023. smartlist_add(arg_chars, (void*)c);
  3024. } else if ('\\' == *c) {
  3025. /* Count backslashes until we know whether to double up */
  3026. bs_counter++;
  3027. } else {
  3028. /* Don't double up slashes preceding a non-quote */
  3029. for (i=0; i<bs_counter; i++)
  3030. smartlist_add(arg_chars, (void*)&backslash);
  3031. bs_counter = 0;
  3032. smartlist_add(arg_chars, (void*)c);
  3033. }
  3034. }
  3035. /* Don't double up trailing backslashes */
  3036. for (i=0; i<bs_counter; i++)
  3037. smartlist_add(arg_chars, (void*)&backslash);
  3038. /* Allocate space for argument, quotes (if needed), and terminator */
  3039. formatted_arg = tor_malloc(sizeof(char) *
  3040. (smartlist_len(arg_chars) + (need_quotes?2:0) + 1));
  3041. /* Add leading quote */
  3042. i=0;
  3043. if (need_quotes)
  3044. formatted_arg[i++] = '"';
  3045. /* Add characters */
  3046. SMARTLIST_FOREACH(arg_chars, char*, c,
  3047. {
  3048. formatted_arg[i++] = *c;
  3049. });
  3050. /* Add trailing quote */
  3051. if (need_quotes)
  3052. formatted_arg[i++] = '"';
  3053. formatted_arg[i] = '\0';
  3054. smartlist_free(arg_chars);
  3055. return formatted_arg;
  3056. }
  3057. /** Format a command line for use on Windows, which takes the command as a
  3058. * string rather than string array. Follows the rules from "Parsing C++
  3059. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  3060. * Python subprocess module. Returns a newly allocated string */
  3061. char *
  3062. tor_join_win_cmdline(const char *argv[])
  3063. {
  3064. smartlist_t *argv_list;
  3065. char *joined_argv;
  3066. int i;
  3067. /* Format each argument and put the result in a smartlist */
  3068. argv_list = smartlist_new();
  3069. for (i=0; argv[i] != NULL; i++) {
  3070. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  3071. }
  3072. /* Join the arguments with whitespace */
  3073. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  3074. /* Free the newly allocated arguments, and the smartlist */
  3075. SMARTLIST_FOREACH(argv_list, char *, arg,
  3076. {
  3077. tor_free(arg);
  3078. });
  3079. smartlist_free(argv_list);
  3080. return joined_argv;
  3081. }
  3082. /**
  3083. * Helper function to output hex numbers, called by
  3084. * format_helper_exit_status(). This writes the hexadecimal digits of x into
  3085. * buf, up to max_len digits, and returns the actual number of digits written.
  3086. * If there is insufficient space, it will write nothing and return 0.
  3087. *
  3088. * This function DOES NOT add a terminating NUL character to its output: be
  3089. * careful!
  3090. *
  3091. * This accepts an unsigned int because format_helper_exit_status() needs to
  3092. * call it with a signed int and an unsigned char, and since the C standard
  3093. * does not guarantee that an int is wider than a char (an int must be at
  3094. * least 16 bits but it is permitted for a char to be that wide as well), we
  3095. * can't assume a signed int is sufficient to accomodate an unsigned char.
  3096. * Thus, format_helper_exit_status() will still need to emit any require '-'
  3097. * on its own.
  3098. *
  3099. * For most purposes, you'd want to use tor_snprintf("%x") instead of this
  3100. * function; it's designed to be used in code paths where you can't call
  3101. * arbitrary C functions.
  3102. */
  3103. STATIC int
  3104. format_hex_number_for_helper_exit_status(unsigned int x, char *buf,
  3105. int max_len)
  3106. {
  3107. int len;
  3108. unsigned int tmp;
  3109. char *cur;
  3110. /* Sanity check */
  3111. if (!buf || max_len <= 0)
  3112. return 0;
  3113. /* How many chars do we need for x? */
  3114. if (x > 0) {
  3115. len = 0;
  3116. tmp = x;
  3117. while (tmp > 0) {
  3118. tmp >>= 4;
  3119. ++len;
  3120. }
  3121. } else {
  3122. len = 1;
  3123. }
  3124. /* Bail if we would go past the end of the buffer */
  3125. if (len > max_len)
  3126. return 0;
  3127. /* Point to last one */
  3128. cur = buf + len - 1;
  3129. /* Convert x to hex */
  3130. do {
  3131. *cur-- = "0123456789ABCDEF"[x & 0xf];
  3132. x >>= 4;
  3133. } while (x != 0 && cur >= buf);
  3134. /* Return len */
  3135. return len;
  3136. }
  3137. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  3138. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  3139. * safe.
  3140. *
  3141. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE bytes available.
  3142. *
  3143. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  3144. * with spaces. Note that there is no trailing \0. CHILD_STATE indicates where
  3145. * in the processs of starting the child process did the failure occur (see
  3146. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  3147. * errno when the failure occurred.
  3148. *
  3149. * On success return the number of characters added to hex_errno, not counting
  3150. * the terminating NUL; return -1 on error.
  3151. */
  3152. STATIC int
  3153. format_helper_exit_status(unsigned char child_state, int saved_errno,
  3154. char *hex_errno)
  3155. {
  3156. unsigned int unsigned_errno;
  3157. int written, left;
  3158. char *cur;
  3159. size_t i;
  3160. int res = -1;
  3161. /* Fill hex_errno with spaces, and a trailing newline (memset may
  3162. not be signal handler safe, so we can't use it) */
  3163. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  3164. hex_errno[i] = ' ';
  3165. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  3166. /* Convert errno to be unsigned for hex conversion */
  3167. if (saved_errno < 0) {
  3168. unsigned_errno = (unsigned int) -saved_errno;
  3169. } else {
  3170. unsigned_errno = (unsigned int) saved_errno;
  3171. }
  3172. /*
  3173. * Count how many chars of space we have left, and keep a pointer into the
  3174. * current point in the buffer.
  3175. */
  3176. left = HEX_ERRNO_SIZE;
  3177. cur = hex_errno;
  3178. /* Emit child_state */
  3179. written = format_hex_number_for_helper_exit_status(child_state,
  3180. cur, left);
  3181. if (written <= 0)
  3182. goto err;
  3183. /* Adjust left and cur */
  3184. left -= written;
  3185. cur += written;
  3186. if (left <= 0)
  3187. goto err;
  3188. /* Now the '/' */
  3189. *cur = '/';
  3190. /* Adjust left and cur */
  3191. ++cur;
  3192. --left;
  3193. if (left <= 0)
  3194. goto err;
  3195. /* Need minus? */
  3196. if (saved_errno < 0) {
  3197. *cur = '-';
  3198. ++cur;
  3199. --left;
  3200. if (left <= 0)
  3201. goto err;
  3202. }
  3203. /* Emit unsigned_errno */
  3204. written = format_hex_number_for_helper_exit_status(unsigned_errno,
  3205. cur, left);
  3206. if (written <= 0)
  3207. goto err;
  3208. /* Adjust left and cur */
  3209. left -= written;
  3210. cur += written;
  3211. /* Check that we have enough space left for a newline */
  3212. if (left <= 0)
  3213. goto err;
  3214. /* Emit the newline and NUL */
  3215. *cur++ = '\n';
  3216. *cur++ = '\0';
  3217. res = (int)(cur - hex_errno - 1);
  3218. goto done;
  3219. err:
  3220. /*
  3221. * In error exit, just write a '\0' in the first char so whatever called
  3222. * this at least won't fall off the end.
  3223. */
  3224. *hex_errno = '\0';
  3225. done:
  3226. return res;
  3227. }
  3228. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  3229. #define DEFAULT_MAX_FD 256
  3230. /** Terminate the process of <b>process_handle</b>.
  3231. * Code borrowed from Python's os.kill. */
  3232. int
  3233. tor_terminate_process(process_handle_t *process_handle)
  3234. {
  3235. #ifdef _WIN32
  3236. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  3237. HANDLE handle;
  3238. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  3239. attempt to open and terminate the process. */
  3240. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE,
  3241. process_handle->pid.dwProcessId);
  3242. if (!handle)
  3243. return -1;
  3244. if (!TerminateProcess(handle, 0))
  3245. return -1;
  3246. else
  3247. return 0;
  3248. }
  3249. #else /* Unix */
  3250. return kill(process_handle->pid, SIGTERM);
  3251. #endif
  3252. return -1;
  3253. }
  3254. /** Return the Process ID of <b>process_handle</b>. */
  3255. int
  3256. tor_process_get_pid(process_handle_t *process_handle)
  3257. {
  3258. #ifdef _WIN32
  3259. return (int) process_handle->pid.dwProcessId;
  3260. #else
  3261. return (int) process_handle->pid;
  3262. #endif
  3263. }
  3264. #ifdef _WIN32
  3265. HANDLE
  3266. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3267. {
  3268. return process_handle->stdout_pipe;
  3269. }
  3270. #else
  3271. /* DOCDOC tor_process_get_stdout_pipe */
  3272. FILE *
  3273. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3274. {
  3275. return process_handle->stdout_handle;
  3276. }
  3277. #endif
  3278. /* DOCDOC process_handle_new */
  3279. static process_handle_t *
  3280. process_handle_new(void)
  3281. {
  3282. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  3283. #ifdef _WIN32
  3284. out->stdout_pipe = INVALID_HANDLE_VALUE;
  3285. out->stderr_pipe = INVALID_HANDLE_VALUE;
  3286. #else
  3287. out->stdout_pipe = -1;
  3288. out->stderr_pipe = -1;
  3289. #endif
  3290. return out;
  3291. }
  3292. /**
  3293. * @name child-process states
  3294. *
  3295. * Each of these values represents a possible state that a child process can
  3296. * be in. They're used to determine what to say when telling the parent how
  3297. * far along we were before failure.
  3298. *
  3299. * @{
  3300. */
  3301. #define CHILD_STATE_INIT 0
  3302. #define CHILD_STATE_PIPE 1
  3303. #define CHILD_STATE_MAXFD 2
  3304. #define CHILD_STATE_FORK 3
  3305. #define CHILD_STATE_DUPOUT 4
  3306. #define CHILD_STATE_DUPERR 5
  3307. #define CHILD_STATE_REDIRECT 6
  3308. #define CHILD_STATE_CLOSEFD 7
  3309. #define CHILD_STATE_EXEC 8
  3310. #define CHILD_STATE_FAILEXEC 9
  3311. /** @} */
  3312. /** Start a program in the background. If <b>filename</b> contains a '/', then
  3313. * it will be treated as an absolute or relative path. Otherwise, on
  3314. * non-Windows systems, the system path will be searched for <b>filename</b>.
  3315. * On Windows, only the current directory will be searched. Here, to search the
  3316. * system path (as well as the application directory, current working
  3317. * directory, and system directories), set filename to NULL.
  3318. *
  3319. * The strings in <b>argv</b> will be passed as the command line arguments of
  3320. * the child program (following convention, argv[0] should normally be the
  3321. * filename of the executable, and this must be the case if <b>filename</b> is
  3322. * NULL). The last element of argv must be NULL. A handle to the child process
  3323. * will be returned in process_handle (which must be non-NULL). Read
  3324. * process_handle.status to find out if the process was successfully launched.
  3325. * For convenience, process_handle.status is returned by this function.
  3326. *
  3327. * Some parts of this code are based on the POSIX subprocess module from
  3328. * Python, and example code from
  3329. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  3330. */
  3331. int
  3332. tor_spawn_background(const char *const filename, const char **argv,
  3333. process_environment_t *env,
  3334. process_handle_t **process_handle_out)
  3335. {
  3336. #ifdef _WIN32
  3337. HANDLE stdout_pipe_read = NULL;
  3338. HANDLE stdout_pipe_write = NULL;
  3339. HANDLE stderr_pipe_read = NULL;
  3340. HANDLE stderr_pipe_write = NULL;
  3341. process_handle_t *process_handle;
  3342. int status;
  3343. STARTUPINFOA siStartInfo;
  3344. BOOL retval = FALSE;
  3345. SECURITY_ATTRIBUTES saAttr;
  3346. char *joined_argv;
  3347. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  3348. saAttr.bInheritHandle = TRUE;
  3349. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3350. saAttr.lpSecurityDescriptor = NULL;
  3351. /* Assume failure to start process */
  3352. status = PROCESS_STATUS_ERROR;
  3353. /* Set up pipe for stdout */
  3354. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  3355. log_warn(LD_GENERAL,
  3356. "Failed to create pipe for stdout communication with child process: %s",
  3357. format_win32_error(GetLastError()));
  3358. return status;
  3359. }
  3360. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3361. log_warn(LD_GENERAL,
  3362. "Failed to configure pipe for stdout communication with child "
  3363. "process: %s", format_win32_error(GetLastError()));
  3364. return status;
  3365. }
  3366. /* Set up pipe for stderr */
  3367. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  3368. log_warn(LD_GENERAL,
  3369. "Failed to create pipe for stderr communication with child process: %s",
  3370. format_win32_error(GetLastError()));
  3371. return status;
  3372. }
  3373. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3374. log_warn(LD_GENERAL,
  3375. "Failed to configure pipe for stderr communication with child "
  3376. "process: %s", format_win32_error(GetLastError()));
  3377. return status;
  3378. }
  3379. /* Create the child process */
  3380. /* Windows expects argv to be a whitespace delimited string, so join argv up
  3381. */
  3382. joined_argv = tor_join_win_cmdline(argv);
  3383. process_handle = process_handle_new();
  3384. process_handle->status = status;
  3385. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  3386. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  3387. siStartInfo.cb = sizeof(STARTUPINFO);
  3388. siStartInfo.hStdError = stderr_pipe_write;
  3389. siStartInfo.hStdOutput = stdout_pipe_write;
  3390. siStartInfo.hStdInput = NULL;
  3391. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  3392. /* Create the child process */
  3393. retval = CreateProcessA(filename, // module name
  3394. joined_argv, // command line
  3395. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3396. NULL, // process security attributes
  3397. NULL, // primary thread security attributes
  3398. TRUE, // handles are inherited
  3399. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  3400. * work?) */
  3401. 0, // creation flags
  3402. (env==NULL) ? NULL : env->windows_environment_block,
  3403. NULL, // use parent's current directory
  3404. &siStartInfo, // STARTUPINFO pointer
  3405. &(process_handle->pid)); // receives PROCESS_INFORMATION
  3406. tor_free(joined_argv);
  3407. if (!retval) {
  3408. log_warn(LD_GENERAL,
  3409. "Failed to create child process %s: %s", filename?filename:argv[0],
  3410. format_win32_error(GetLastError()));
  3411. tor_free(process_handle);
  3412. } else {
  3413. /* TODO: Close hProcess and hThread in process_handle->pid? */
  3414. process_handle->stdout_pipe = stdout_pipe_read;
  3415. process_handle->stderr_pipe = stderr_pipe_read;
  3416. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3417. }
  3418. /* TODO: Close pipes on exit */
  3419. *process_handle_out = process_handle;
  3420. return status;
  3421. #else // _WIN32
  3422. pid_t pid;
  3423. int stdout_pipe[2];
  3424. int stderr_pipe[2];
  3425. int fd, retval;
  3426. ssize_t nbytes;
  3427. process_handle_t *process_handle;
  3428. int status;
  3429. const char *error_message = SPAWN_ERROR_MESSAGE;
  3430. size_t error_message_length;
  3431. /* Represents where in the process of spawning the program is;
  3432. this is used for printing out the error message */
  3433. unsigned char child_state = CHILD_STATE_INIT;
  3434. char hex_errno[HEX_ERRNO_SIZE];
  3435. static int max_fd = -1;
  3436. status = PROCESS_STATUS_ERROR;
  3437. /* We do the strlen here because strlen() is not signal handler safe,
  3438. and we are not allowed to use unsafe functions between fork and exec */
  3439. error_message_length = strlen(error_message);
  3440. child_state = CHILD_STATE_PIPE;
  3441. /* Set up pipe for redirecting stdout and stderr of child */
  3442. retval = pipe(stdout_pipe);
  3443. if (-1 == retval) {
  3444. log_warn(LD_GENERAL,
  3445. "Failed to set up pipe for stdout communication with child process: %s",
  3446. strerror(errno));
  3447. return status;
  3448. }
  3449. retval = pipe(stderr_pipe);
  3450. if (-1 == retval) {
  3451. log_warn(LD_GENERAL,
  3452. "Failed to set up pipe for stderr communication with child process: %s",
  3453. strerror(errno));
  3454. close(stdout_pipe[0]);
  3455. close(stdout_pipe[1]);
  3456. return status;
  3457. }
  3458. child_state = CHILD_STATE_MAXFD;
  3459. #ifdef _SC_OPEN_MAX
  3460. if (-1 == max_fd) {
  3461. max_fd = (int) sysconf(_SC_OPEN_MAX);
  3462. if (max_fd == -1) {
  3463. max_fd = DEFAULT_MAX_FD;
  3464. log_warn(LD_GENERAL,
  3465. "Cannot find maximum file descriptor, assuming %d", max_fd);
  3466. }
  3467. }
  3468. #else
  3469. max_fd = DEFAULT_MAX_FD;
  3470. #endif
  3471. child_state = CHILD_STATE_FORK;
  3472. pid = fork();
  3473. if (0 == pid) {
  3474. /* In child */
  3475. child_state = CHILD_STATE_DUPOUT;
  3476. /* Link child stdout to the write end of the pipe */
  3477. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  3478. if (-1 == retval)
  3479. goto error;
  3480. child_state = CHILD_STATE_DUPERR;
  3481. /* Link child stderr to the write end of the pipe */
  3482. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  3483. if (-1 == retval)
  3484. goto error;
  3485. child_state = CHILD_STATE_REDIRECT;
  3486. /* Link stdin to /dev/null */
  3487. fd = open("/dev/null", O_RDONLY); /* NOT cloexec, obviously. */
  3488. if (fd != -1)
  3489. dup2(fd, STDIN_FILENO);
  3490. else
  3491. goto error;
  3492. child_state = CHILD_STATE_CLOSEFD;
  3493. close(stderr_pipe[0]);
  3494. close(stderr_pipe[1]);
  3495. close(stdout_pipe[0]);
  3496. close(stdout_pipe[1]);
  3497. close(fd);
  3498. /* Close all other fds, including the read end of the pipe */
  3499. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  3500. * this needless. */
  3501. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  3502. close(fd);
  3503. }
  3504. child_state = CHILD_STATE_EXEC;
  3505. /* Call the requested program. We need the cast because
  3506. execvp doesn't define argv as const, even though it
  3507. does not modify the arguments */
  3508. if (env)
  3509. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  3510. else
  3511. execvp(filename, (char *const *) argv);
  3512. /* If we got here, the exec or open(/dev/null) failed */
  3513. child_state = CHILD_STATE_FAILEXEC;
  3514. error:
  3515. {
  3516. /* XXX: are we leaking fds from the pipe? */
  3517. int n;
  3518. n = format_helper_exit_status(child_state, errno, hex_errno);
  3519. if (n >= 0) {
  3520. /* Write the error message. GCC requires that we check the return
  3521. value, but there is nothing we can do if it fails */
  3522. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  3523. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  3524. nbytes = write(STDOUT_FILENO, hex_errno, n);
  3525. }
  3526. }
  3527. (void) nbytes;
  3528. _exit(255);
  3529. /* Never reached, but avoids compiler warning */
  3530. return status;
  3531. }
  3532. /* In parent */
  3533. if (-1 == pid) {
  3534. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  3535. close(stdout_pipe[0]);
  3536. close(stdout_pipe[1]);
  3537. close(stderr_pipe[0]);
  3538. close(stderr_pipe[1]);
  3539. return status;
  3540. }
  3541. process_handle = process_handle_new();
  3542. process_handle->status = status;
  3543. process_handle->pid = pid;
  3544. /* TODO: If the child process forked but failed to exec, waitpid it */
  3545. /* Return read end of the pipes to caller, and close write end */
  3546. process_handle->stdout_pipe = stdout_pipe[0];
  3547. retval = close(stdout_pipe[1]);
  3548. if (-1 == retval) {
  3549. log_warn(LD_GENERAL,
  3550. "Failed to close write end of stdout pipe in parent process: %s",
  3551. strerror(errno));
  3552. }
  3553. process_handle->stderr_pipe = stderr_pipe[0];
  3554. retval = close(stderr_pipe[1]);
  3555. if (-1 == retval) {
  3556. log_warn(LD_GENERAL,
  3557. "Failed to close write end of stderr pipe in parent process: %s",
  3558. strerror(errno));
  3559. }
  3560. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3561. /* Set stdout/stderr pipes to be non-blocking */
  3562. fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK);
  3563. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK);
  3564. /* Open the buffered IO streams */
  3565. process_handle->stdout_handle = fdopen(process_handle->stdout_pipe, "r");
  3566. process_handle->stderr_handle = fdopen(process_handle->stderr_pipe, "r");
  3567. *process_handle_out = process_handle;
  3568. return process_handle->status;
  3569. #endif // _WIN32
  3570. }
  3571. /** Destroy all resources allocated by the process handle in
  3572. * <b>process_handle</b>.
  3573. * If <b>also_terminate_process</b> is true, also terminate the
  3574. * process of the process handle. */
  3575. void
  3576. tor_process_handle_destroy(process_handle_t *process_handle,
  3577. int also_terminate_process)
  3578. {
  3579. if (!process_handle)
  3580. return;
  3581. if (also_terminate_process) {
  3582. if (tor_terminate_process(process_handle) < 0) {
  3583. const char *errstr =
  3584. #ifdef _WIN32
  3585. format_win32_error(GetLastError());
  3586. #else
  3587. strerror(errno);
  3588. #endif
  3589. log_notice(LD_GENERAL, "Failed to terminate process with "
  3590. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  3591. errstr);
  3592. } else {
  3593. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  3594. tor_process_get_pid(process_handle));
  3595. }
  3596. }
  3597. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3598. #ifdef _WIN32
  3599. if (process_handle->stdout_pipe)
  3600. CloseHandle(process_handle->stdout_pipe);
  3601. if (process_handle->stderr_pipe)
  3602. CloseHandle(process_handle->stderr_pipe);
  3603. #else
  3604. if (process_handle->stdout_handle)
  3605. fclose(process_handle->stdout_handle);
  3606. if (process_handle->stderr_handle)
  3607. fclose(process_handle->stderr_handle);
  3608. #endif
  3609. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3610. tor_free(process_handle);
  3611. }
  3612. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3613. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3614. * to true, the call will block until the process has exited. Otherwise if
  3615. * the process is still running, the function will return
  3616. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3617. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3618. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3619. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3620. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3621. * terminated child processes.*/
  3622. int
  3623. tor_get_exit_code(const process_handle_t *process_handle,
  3624. int block, int *exit_code)
  3625. {
  3626. #ifdef _WIN32
  3627. DWORD retval;
  3628. BOOL success;
  3629. if (block) {
  3630. /* Wait for the process to exit */
  3631. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3632. if (retval != WAIT_OBJECT_0) {
  3633. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3634. (int)retval, format_win32_error(GetLastError()));
  3635. return PROCESS_EXIT_ERROR;
  3636. }
  3637. } else {
  3638. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3639. if (WAIT_TIMEOUT == retval) {
  3640. /* Process has not exited */
  3641. return PROCESS_EXIT_RUNNING;
  3642. } else if (retval != WAIT_OBJECT_0) {
  3643. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3644. (int)retval, format_win32_error(GetLastError()));
  3645. return PROCESS_EXIT_ERROR;
  3646. }
  3647. }
  3648. if (exit_code != NULL) {
  3649. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3650. (PDWORD)exit_code);
  3651. if (!success) {
  3652. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3653. format_win32_error(GetLastError()));
  3654. return PROCESS_EXIT_ERROR;
  3655. }
  3656. }
  3657. #else
  3658. int stat_loc;
  3659. int retval;
  3660. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3661. if (!block && 0 == retval) {
  3662. /* Process has not exited */
  3663. return PROCESS_EXIT_RUNNING;
  3664. } else if (retval != process_handle->pid) {
  3665. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3666. process_handle->pid, strerror(errno));
  3667. return PROCESS_EXIT_ERROR;
  3668. }
  3669. if (!WIFEXITED(stat_loc)) {
  3670. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3671. process_handle->pid);
  3672. return PROCESS_EXIT_ERROR;
  3673. }
  3674. if (exit_code != NULL)
  3675. *exit_code = WEXITSTATUS(stat_loc);
  3676. #endif // _WIN32
  3677. return PROCESS_EXIT_EXITED;
  3678. }
  3679. /** Helper: return the number of characters in <b>s</b> preceding the first
  3680. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  3681. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  3682. static INLINE size_t
  3683. str_num_before(const char *s, char ch)
  3684. {
  3685. const char *cp = strchr(s, ch);
  3686. if (cp)
  3687. return cp - s;
  3688. else
  3689. return strlen(s);
  3690. }
  3691. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3692. * to have the same name as strings in a process's environment. */
  3693. int
  3694. environment_variable_names_equal(const char *s1, const char *s2)
  3695. {
  3696. size_t s1_name_len = str_num_before(s1, '=');
  3697. size_t s2_name_len = str_num_before(s2, '=');
  3698. return (s1_name_len == s2_name_len &&
  3699. tor_memeq(s1, s2, s1_name_len));
  3700. }
  3701. /** Free <b>env</b> (assuming it was produced by
  3702. * process_environment_make). */
  3703. void
  3704. process_environment_free(process_environment_t *env)
  3705. {
  3706. if (env == NULL) return;
  3707. /* As both an optimization hack to reduce consing on Unixoid systems
  3708. * and a nice way to ensure that some otherwise-Windows-specific
  3709. * code will always get tested before changes to it get merged, the
  3710. * strings which env->unixoid_environment_block points to are packed
  3711. * into env->windows_environment_block. */
  3712. tor_free(env->unixoid_environment_block);
  3713. tor_free(env->windows_environment_block);
  3714. tor_free(env);
  3715. }
  3716. /** Make a process_environment_t containing the environment variables
  3717. * specified in <b>env_vars</b> (as C strings of the form
  3718. * "NAME=VALUE"). */
  3719. process_environment_t *
  3720. process_environment_make(struct smartlist_t *env_vars)
  3721. {
  3722. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3723. size_t n_env_vars = smartlist_len(env_vars);
  3724. size_t i;
  3725. size_t total_env_length;
  3726. smartlist_t *env_vars_sorted;
  3727. tor_assert(n_env_vars + 1 != 0);
  3728. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3729. /* env->unixoid_environment_block is already NULL-terminated,
  3730. * because we assume that NULL == 0 (and check that during compilation). */
  3731. total_env_length = 1; /* terminating NUL of terminating empty string */
  3732. for (i = 0; i < n_env_vars; ++i) {
  3733. const char *s = smartlist_get(env_vars, i);
  3734. size_t slen = strlen(s);
  3735. tor_assert(slen + 1 != 0);
  3736. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3737. total_env_length += slen + 1;
  3738. }
  3739. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3740. /* env->windows_environment_block is already
  3741. * (NUL-terminated-empty-string)-terminated. */
  3742. /* Some versions of Windows supposedly require that environment
  3743. * blocks be sorted. Or maybe some Windows programs (or their
  3744. * runtime libraries) fail to look up strings in non-sorted
  3745. * environment blocks.
  3746. *
  3747. * Also, sorting strings makes it easy to find duplicate environment
  3748. * variables and environment-variable strings without an '=' on all
  3749. * OSes, and they can cause badness. Let's complain about those. */
  3750. env_vars_sorted = smartlist_new();
  3751. smartlist_add_all(env_vars_sorted, env_vars);
  3752. smartlist_sort_strings(env_vars_sorted);
  3753. /* Now copy the strings into the environment blocks. */
  3754. {
  3755. char *cp = env->windows_environment_block;
  3756. const char *prev_env_var = NULL;
  3757. for (i = 0; i < n_env_vars; ++i) {
  3758. const char *s = smartlist_get(env_vars_sorted, i);
  3759. size_t slen = strlen(s);
  3760. size_t s_name_len = str_num_before(s, '=');
  3761. if (s_name_len == slen) {
  3762. log_warn(LD_GENERAL,
  3763. "Preparing an environment containing a variable "
  3764. "without a value: %s",
  3765. s);
  3766. }
  3767. if (prev_env_var != NULL &&
  3768. environment_variable_names_equal(s, prev_env_var)) {
  3769. log_warn(LD_GENERAL,
  3770. "Preparing an environment containing two variables "
  3771. "with the same name: %s and %s",
  3772. prev_env_var, s);
  3773. }
  3774. prev_env_var = s;
  3775. /* Actually copy the string into the environment. */
  3776. memcpy(cp, s, slen+1);
  3777. env->unixoid_environment_block[i] = cp;
  3778. cp += slen+1;
  3779. }
  3780. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3781. }
  3782. smartlist_free(env_vars_sorted);
  3783. return env;
  3784. }
  3785. /** Return a newly allocated smartlist containing every variable in
  3786. * this process's environment, as a NUL-terminated string of the form
  3787. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3788. * process can put strings not of that form in our environment;
  3789. * callers should try to not get crashed by that.
  3790. *
  3791. * The returned strings are heap-allocated, and must be freed by the
  3792. * caller. */
  3793. struct smartlist_t *
  3794. get_current_process_environment_variables(void)
  3795. {
  3796. smartlist_t *sl = smartlist_new();
  3797. char **environ_tmp; /* Not const char ** ? Really? */
  3798. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  3799. smartlist_add(sl, tor_strdup(*environ_tmp));
  3800. }
  3801. return sl;
  3802. }
  3803. /** For each string s in <b>env_vars</b> such that
  3804. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3805. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3806. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3807. void
  3808. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3809. const char *new_var,
  3810. void (*free_old)(void*),
  3811. int free_p)
  3812. {
  3813. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3814. if (environment_variable_names_equal(s, new_var)) {
  3815. SMARTLIST_DEL_CURRENT(env_vars, s);
  3816. if (free_p) {
  3817. free_old((void *)s);
  3818. }
  3819. }
  3820. } SMARTLIST_FOREACH_END(s);
  3821. if (strchr(new_var, '=') != NULL) {
  3822. smartlist_add(env_vars, (void *)new_var);
  3823. }
  3824. }
  3825. #ifdef _WIN32
  3826. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3827. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3828. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3829. * to the process owning the <b>h</b>. In this case, the function will exit
  3830. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3831. * the number of bytes read, or -1 on error. */
  3832. ssize_t
  3833. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  3834. const process_handle_t *process)
  3835. {
  3836. size_t numread = 0;
  3837. BOOL retval;
  3838. DWORD byte_count;
  3839. BOOL process_exited = FALSE;
  3840. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3841. return -1;
  3842. while (numread != count) {
  3843. /* Check if there is anything to read */
  3844. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  3845. if (!retval) {
  3846. log_warn(LD_GENERAL,
  3847. "Failed to peek from handle: %s",
  3848. format_win32_error(GetLastError()));
  3849. return -1;
  3850. } else if (0 == byte_count) {
  3851. /* Nothing available: process exited or it is busy */
  3852. /* Exit if we don't know whether the process is running */
  3853. if (NULL == process)
  3854. break;
  3855. /* The process exited and there's nothing left to read from it */
  3856. if (process_exited)
  3857. break;
  3858. /* If process is not running, check for output one more time in case
  3859. it wrote something after the peek was performed. Otherwise keep on
  3860. waiting for output */
  3861. tor_assert(process != NULL);
  3862. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  3863. if (WAIT_TIMEOUT != byte_count)
  3864. process_exited = TRUE;
  3865. continue;
  3866. }
  3867. /* There is data to read; read it */
  3868. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  3869. tor_assert(byte_count + numread <= count);
  3870. if (!retval) {
  3871. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  3872. format_win32_error(GetLastError()));
  3873. return -1;
  3874. } else if (0 == byte_count) {
  3875. /* End of file */
  3876. break;
  3877. }
  3878. numread += byte_count;
  3879. }
  3880. return (ssize_t)numread;
  3881. }
  3882. #else
  3883. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3884. * <b>process</b> is NULL, the function will return immediately if there is
  3885. * nothing more to read. Otherwise data will be read until end of file, or
  3886. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  3887. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  3888. * file has been reached. */
  3889. ssize_t
  3890. tor_read_all_handle(FILE *h, char *buf, size_t count,
  3891. const process_handle_t *process,
  3892. int *eof)
  3893. {
  3894. size_t numread = 0;
  3895. char *retval;
  3896. if (eof)
  3897. *eof = 0;
  3898. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3899. return -1;
  3900. while (numread != count) {
  3901. /* Use fgets because that is what we use in log_from_pipe() */
  3902. retval = fgets(buf+numread, (int)(count-numread), h);
  3903. if (NULL == retval) {
  3904. if (feof(h)) {
  3905. log_debug(LD_GENERAL, "fgets() reached end of file");
  3906. if (eof)
  3907. *eof = 1;
  3908. break;
  3909. } else {
  3910. if (EAGAIN == errno) {
  3911. if (process)
  3912. continue;
  3913. else
  3914. break;
  3915. } else {
  3916. log_warn(LD_GENERAL, "fgets() from handle failed: %s",
  3917. strerror(errno));
  3918. return -1;
  3919. }
  3920. }
  3921. }
  3922. tor_assert(retval != NULL);
  3923. tor_assert(strlen(retval) + numread <= count);
  3924. numread += strlen(retval);
  3925. }
  3926. log_debug(LD_GENERAL, "fgets() read %d bytes from handle", (int)numread);
  3927. return (ssize_t)numread;
  3928. }
  3929. #endif
  3930. /** Read from stdout of a process until the process exits. */
  3931. ssize_t
  3932. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  3933. char *buf, size_t count)
  3934. {
  3935. #ifdef _WIN32
  3936. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3937. process_handle);
  3938. #else
  3939. return tor_read_all_handle(process_handle->stdout_handle, buf, count,
  3940. process_handle, NULL);
  3941. #endif
  3942. }
  3943. /** Read from stdout of a process until the process exits. */
  3944. ssize_t
  3945. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  3946. char *buf, size_t count)
  3947. {
  3948. #ifdef _WIN32
  3949. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3950. process_handle);
  3951. #else
  3952. return tor_read_all_handle(process_handle->stderr_handle, buf, count,
  3953. process_handle, NULL);
  3954. #endif
  3955. }
  3956. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  3957. * modified. The resulting smartlist will consist of pointers to buf, so there
  3958. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  3959. * string. <b>len</b> should be set to the length of the buffer excluding the
  3960. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  3961. int
  3962. tor_split_lines(smartlist_t *sl, char *buf, int len)
  3963. {
  3964. /* Index in buf of the start of the current line */
  3965. int start = 0;
  3966. /* Index in buf of the current character being processed */
  3967. int cur = 0;
  3968. /* Are we currently in a line */
  3969. char in_line = 0;
  3970. /* Loop over string */
  3971. while (cur < len) {
  3972. /* Loop until end of line or end of string */
  3973. for (; cur < len; cur++) {
  3974. if (in_line) {
  3975. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3976. /* End of line */
  3977. buf[cur] = '\0';
  3978. /* Point cur to the next line */
  3979. cur++;
  3980. /* Line starts at start and ends with a nul */
  3981. break;
  3982. } else {
  3983. if (!TOR_ISPRINT(buf[cur]))
  3984. buf[cur] = '.';
  3985. }
  3986. } else {
  3987. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3988. /* Skip leading vertical space */
  3989. ;
  3990. } else {
  3991. in_line = 1;
  3992. start = cur;
  3993. if (!TOR_ISPRINT(buf[cur]))
  3994. buf[cur] = '.';
  3995. }
  3996. }
  3997. }
  3998. /* We are at the end of the line or end of string. If in_line is true there
  3999. * is a line which starts at buf+start and ends at a NUL. cur points to
  4000. * the character after the NUL. */
  4001. if (in_line)
  4002. smartlist_add(sl, (void *)(buf+start));
  4003. in_line = 0;
  4004. }
  4005. return smartlist_len(sl);
  4006. }
  4007. /** Return a string corresponding to <b>stream_status</b>. */
  4008. const char *
  4009. stream_status_to_string(enum stream_status stream_status)
  4010. {
  4011. switch (stream_status) {
  4012. case IO_STREAM_OKAY:
  4013. return "okay";
  4014. case IO_STREAM_EAGAIN:
  4015. return "temporarily unavailable";
  4016. case IO_STREAM_TERM:
  4017. return "terminated";
  4018. case IO_STREAM_CLOSED:
  4019. return "closed";
  4020. default:
  4021. tor_fragile_assert();
  4022. return "unknown";
  4023. }
  4024. }
  4025. #ifdef _WIN32
  4026. /** Return a smartlist containing lines outputted from
  4027. * <b>handle</b>. Return NULL on error, and set
  4028. * <b>stream_status_out</b> appropriately. */
  4029. smartlist_t *
  4030. tor_get_lines_from_handle(HANDLE *handle,
  4031. enum stream_status *stream_status_out)
  4032. {
  4033. int pos;
  4034. char stdout_buf[600] = {0};
  4035. smartlist_t *lines = NULL;
  4036. tor_assert(stream_status_out);
  4037. *stream_status_out = IO_STREAM_TERM;
  4038. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  4039. if (pos < 0) {
  4040. *stream_status_out = IO_STREAM_TERM;
  4041. return NULL;
  4042. }
  4043. if (pos == 0) {
  4044. *stream_status_out = IO_STREAM_EAGAIN;
  4045. return NULL;
  4046. }
  4047. /* End with a null even if there isn't a \r\n at the end */
  4048. /* TODO: What if this is a partial line? */
  4049. stdout_buf[pos] = '\0';
  4050. /* Split up the buffer */
  4051. lines = smartlist_new();
  4052. tor_split_lines(lines, stdout_buf, pos);
  4053. /* Currently 'lines' is populated with strings residing on the
  4054. stack. Replace them with their exact copies on the heap: */
  4055. SMARTLIST_FOREACH(lines, char *, line,
  4056. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  4057. *stream_status_out = IO_STREAM_OKAY;
  4058. return lines;
  4059. }
  4060. /** Read from stream, and send lines to log at the specified log level.
  4061. * Returns -1 if there is a error reading, and 0 otherwise.
  4062. * If the generated stream is flushed more often than on new lines, or
  4063. * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
  4064. * along with the corresponding problem on *nix (see bug #2045).
  4065. */
  4066. static int
  4067. log_from_handle(HANDLE *pipe, int severity)
  4068. {
  4069. char buf[256];
  4070. int pos;
  4071. smartlist_t *lines;
  4072. pos = tor_read_all_handle(pipe, buf, sizeof(buf) - 1, NULL);
  4073. if (pos < 0) {
  4074. /* Error */
  4075. log_warn(LD_GENERAL, "Failed to read data from subprocess");
  4076. return -1;
  4077. }
  4078. if (0 == pos) {
  4079. /* There's nothing to read (process is busy or has exited) */
  4080. log_debug(LD_GENERAL, "Subprocess had nothing to say");
  4081. return 0;
  4082. }
  4083. /* End with a null even if there isn't a \r\n at the end */
  4084. /* TODO: What if this is a partial line? */
  4085. buf[pos] = '\0';
  4086. log_debug(LD_GENERAL, "Subprocess had %d bytes to say", pos);
  4087. /* Split up the buffer */
  4088. lines = smartlist_new();
  4089. tor_split_lines(lines, buf, pos);
  4090. /* Log each line */
  4091. SMARTLIST_FOREACH(lines, char *, line,
  4092. {
  4093. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", line);
  4094. });
  4095. smartlist_free(lines);
  4096. return 0;
  4097. }
  4098. #else
  4099. /** Return a smartlist containing lines outputted from
  4100. * <b>handle</b>. Return NULL on error, and set
  4101. * <b>stream_status_out</b> appropriately. */
  4102. smartlist_t *
  4103. tor_get_lines_from_handle(FILE *handle, enum stream_status *stream_status_out)
  4104. {
  4105. enum stream_status stream_status;
  4106. char stdout_buf[400];
  4107. smartlist_t *lines = NULL;
  4108. while (1) {
  4109. memset(stdout_buf, 0, sizeof(stdout_buf));
  4110. stream_status = get_string_from_pipe(handle,
  4111. stdout_buf, sizeof(stdout_buf) - 1);
  4112. if (stream_status != IO_STREAM_OKAY)
  4113. goto done;
  4114. if (!lines) lines = smartlist_new();
  4115. smartlist_add(lines, tor_strdup(stdout_buf));
  4116. }
  4117. done:
  4118. *stream_status_out = stream_status;
  4119. return lines;
  4120. }
  4121. /** Read from stream, and send lines to log at the specified log level.
  4122. * Returns 1 if stream is closed normally, -1 if there is a error reading, and
  4123. * 0 otherwise. Handles lines from tor-fw-helper and
  4124. * tor_spawn_background() specially.
  4125. */
  4126. static int
  4127. log_from_pipe(FILE *stream, int severity, const char *executable,
  4128. int *child_status)
  4129. {
  4130. char buf[256];
  4131. enum stream_status r;
  4132. for (;;) {
  4133. r = get_string_from_pipe(stream, buf, sizeof(buf) - 1);
  4134. if (r == IO_STREAM_CLOSED) {
  4135. return 1;
  4136. } else if (r == IO_STREAM_EAGAIN) {
  4137. return 0;
  4138. } else if (r == IO_STREAM_TERM) {
  4139. return -1;
  4140. }
  4141. tor_assert(r == IO_STREAM_OKAY);
  4142. /* Check if buf starts with SPAWN_ERROR_MESSAGE */
  4143. if (strcmpstart(buf, SPAWN_ERROR_MESSAGE) == 0) {
  4144. /* Parse error message */
  4145. int retval, child_state, saved_errno;
  4146. retval = tor_sscanf(buf, SPAWN_ERROR_MESSAGE "%x/%x",
  4147. &child_state, &saved_errno);
  4148. if (retval == 2) {
  4149. log_warn(LD_GENERAL,
  4150. "Failed to start child process \"%s\" in state %d: %s",
  4151. executable, child_state, strerror(saved_errno));
  4152. if (child_status)
  4153. *child_status = 1;
  4154. } else {
  4155. /* Failed to parse message from child process, log it as a
  4156. warning */
  4157. log_warn(LD_GENERAL,
  4158. "Unexpected message from port forwarding helper \"%s\": %s",
  4159. executable, buf);
  4160. }
  4161. } else {
  4162. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", buf);
  4163. }
  4164. }
  4165. /* We should never get here */
  4166. return -1;
  4167. }
  4168. #endif
  4169. /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
  4170. * sure it's below <b>count</b> bytes.
  4171. * If the string has a trailing newline, we strip it off.
  4172. *
  4173. * This function is specifically created to handle input from managed
  4174. * proxies, according to the pluggable transports spec. Make sure it
  4175. * fits your needs before using it.
  4176. *
  4177. * Returns:
  4178. * IO_STREAM_CLOSED: If the stream is closed.
  4179. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  4180. * later.
  4181. * IO_STREAM_TERM: If something is wrong with the stream.
  4182. * IO_STREAM_OKAY: If everything went okay and we got a string
  4183. * in <b>buf_out</b>. */
  4184. enum stream_status
  4185. get_string_from_pipe(FILE *stream, char *buf_out, size_t count)
  4186. {
  4187. char *retval;
  4188. size_t len;
  4189. tor_assert(count <= INT_MAX);
  4190. retval = fgets(buf_out, (int)count, stream);
  4191. if (!retval) {
  4192. if (feof(stream)) {
  4193. /* Program has closed stream (probably it exited) */
  4194. /* TODO: check error */
  4195. return IO_STREAM_CLOSED;
  4196. } else {
  4197. if (EAGAIN == errno) {
  4198. /* Nothing more to read, try again next time */
  4199. return IO_STREAM_EAGAIN;
  4200. } else {
  4201. /* There was a problem, abandon this child process */
  4202. return IO_STREAM_TERM;
  4203. }
  4204. }
  4205. } else {
  4206. len = strlen(buf_out);
  4207. if (len == 0) {
  4208. /* this probably means we got a NUL at the start of the string. */
  4209. return IO_STREAM_EAGAIN;
  4210. }
  4211. if (buf_out[len - 1] == '\n') {
  4212. /* Remove the trailing newline */
  4213. buf_out[len - 1] = '\0';
  4214. } else {
  4215. /* No newline; check whether we overflowed the buffer */
  4216. if (!feof(stream))
  4217. log_info(LD_GENERAL,
  4218. "Line from stream was truncated: %s", buf_out);
  4219. /* TODO: What to do with this error? */
  4220. }
  4221. return IO_STREAM_OKAY;
  4222. }
  4223. /* We should never get here */
  4224. return IO_STREAM_TERM;
  4225. }
  4226. /** Parse a <b>line</b> from tor-fw-helper and issue an appropriate
  4227. * log message to our user. */
  4228. static void
  4229. handle_fw_helper_line(const char *line)
  4230. {
  4231. smartlist_t *tokens = smartlist_new();
  4232. char *message = NULL;
  4233. char *message_for_log = NULL;
  4234. const char *external_port = NULL;
  4235. const char *internal_port = NULL;
  4236. const char *result = NULL;
  4237. int port = 0;
  4238. int success = 0;
  4239. smartlist_split_string(tokens, line, NULL,
  4240. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4241. if (smartlist_len(tokens) < 5)
  4242. goto err;
  4243. if (strcmp(smartlist_get(tokens, 0), "tor-fw-helper") ||
  4244. strcmp(smartlist_get(tokens, 1), "tcp-forward"))
  4245. goto err;
  4246. external_port = smartlist_get(tokens, 2);
  4247. internal_port = smartlist_get(tokens, 3);
  4248. result = smartlist_get(tokens, 4);
  4249. if (smartlist_len(tokens) > 5) {
  4250. /* If there are more than 5 tokens, they are part of [<message>].
  4251. Let's use a second smartlist to form the whole message;
  4252. strncat loops suck. */
  4253. int i;
  4254. int message_words_n = smartlist_len(tokens) - 5;
  4255. smartlist_t *message_sl = smartlist_new();
  4256. for (i = 0; i < message_words_n; i++)
  4257. smartlist_add(message_sl, smartlist_get(tokens, 5+i));
  4258. tor_assert(smartlist_len(message_sl) > 0);
  4259. message = smartlist_join_strings(message_sl, " ", 0, NULL);
  4260. /* wrap the message in log-friendly wrapping */
  4261. tor_asprintf(&message_for_log, " ('%s')", message);
  4262. smartlist_free(message_sl);
  4263. }
  4264. port = atoi(external_port);
  4265. if (port < 1 || port > 65535)
  4266. goto err;
  4267. port = atoi(internal_port);
  4268. if (port < 1 || port > 65535)
  4269. goto err;
  4270. if (!strcmp(result, "SUCCESS"))
  4271. success = 1;
  4272. else if (!strcmp(result, "FAIL"))
  4273. success = 0;
  4274. else
  4275. goto err;
  4276. if (!success) {
  4277. log_warn(LD_GENERAL, "Tor was unable to forward TCP port '%s' to '%s'%s. "
  4278. "Please make sure that your router supports port "
  4279. "forwarding protocols (like NAT-PMP). Note that if '%s' is "
  4280. "your ORPort, your relay will be unable to receive inbound "
  4281. "traffic.", external_port, internal_port,
  4282. message_for_log ? message_for_log : "",
  4283. internal_port);
  4284. } else {
  4285. log_info(LD_GENERAL,
  4286. "Tor successfully forwarded TCP port '%s' to '%s'%s.",
  4287. external_port, internal_port,
  4288. message_for_log ? message_for_log : "");
  4289. }
  4290. goto done;
  4291. err:
  4292. log_warn(LD_GENERAL, "tor-fw-helper sent us a string we could not "
  4293. "parse (%s).", line);
  4294. done:
  4295. SMARTLIST_FOREACH(tokens, char *, cp, tor_free(cp));
  4296. smartlist_free(tokens);
  4297. tor_free(message);
  4298. tor_free(message_for_log);
  4299. }
  4300. /** Read what tor-fw-helper has to say in its stdout and handle it
  4301. * appropriately */
  4302. static int
  4303. handle_fw_helper_output(process_handle_t *process_handle)
  4304. {
  4305. smartlist_t *fw_helper_output = NULL;
  4306. enum stream_status stream_status = 0;
  4307. fw_helper_output =
  4308. tor_get_lines_from_handle(tor_process_get_stdout_pipe(process_handle),
  4309. &stream_status);
  4310. if (!fw_helper_output) { /* didn't get any output from tor-fw-helper */
  4311. /* if EAGAIN we should retry in the future */
  4312. return (stream_status == IO_STREAM_EAGAIN) ? 0 : -1;
  4313. }
  4314. /* Handle the lines we got: */
  4315. SMARTLIST_FOREACH_BEGIN(fw_helper_output, char *, line) {
  4316. handle_fw_helper_line(line);
  4317. tor_free(line);
  4318. } SMARTLIST_FOREACH_END(line);
  4319. smartlist_free(fw_helper_output);
  4320. return 0;
  4321. }
  4322. /** Spawn tor-fw-helper and ask it to forward the ports in
  4323. * <b>ports_to_forward</b>. <b>ports_to_forward</b> contains strings
  4324. * of the form "<external port>:<internal port>", which is the format
  4325. * that tor-fw-helper expects. */
  4326. void
  4327. tor_check_port_forwarding(const char *filename,
  4328. smartlist_t *ports_to_forward,
  4329. time_t now)
  4330. {
  4331. /* When fw-helper succeeds, how long do we wait until running it again */
  4332. #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
  4333. /* When fw-helper failed to start, how long do we wait until running it again
  4334. */
  4335. #define TIME_TO_EXEC_FWHELPER_FAIL 60
  4336. /* Static variables are initialized to zero, so child_handle.status=0
  4337. * which corresponds to it not running on startup */
  4338. static process_handle_t *child_handle=NULL;
  4339. static time_t time_to_run_helper = 0;
  4340. int stderr_status, retval;
  4341. int stdout_status = 0;
  4342. tor_assert(filename);
  4343. /* Start the child, if it is not already running */
  4344. if ((!child_handle || child_handle->status != PROCESS_STATUS_RUNNING) &&
  4345. time_to_run_helper < now) {
  4346. /*tor-fw-helper cli looks like this: tor_fw_helper -p :5555 -p 4555:1111 */
  4347. const char **argv; /* cli arguments */
  4348. int args_n, status;
  4349. int argv_index = 0; /* index inside 'argv' */
  4350. tor_assert(smartlist_len(ports_to_forward) > 0);
  4351. /* check for overflow during 'argv' allocation:
  4352. (len(ports_to_forward)*2 + 2)*sizeof(char*) > SIZE_MAX ==
  4353. len(ports_to_forward) > (((SIZE_MAX/sizeof(char*)) - 2)/2) */
  4354. if ((size_t) smartlist_len(ports_to_forward) >
  4355. (((SIZE_MAX/sizeof(char*)) - 2)/2)) {
  4356. log_warn(LD_GENERAL,
  4357. "Overflow during argv allocation. This shouldn't happen.");
  4358. return;
  4359. }
  4360. /* check for overflow during 'argv_index' increase:
  4361. ((len(ports_to_forward)*2 + 2) > INT_MAX) ==
  4362. len(ports_to_forward) > (INT_MAX - 2)/2 */
  4363. if (smartlist_len(ports_to_forward) > (INT_MAX - 2)/2) {
  4364. log_warn(LD_GENERAL,
  4365. "Overflow during argv_index increase. This shouldn't happen.");
  4366. return;
  4367. }
  4368. /* Calculate number of cli arguments: one for the filename, two
  4369. for each smartlist element (one for "-p" and one for the
  4370. ports), and one for the final NULL. */
  4371. args_n = 1 + 2*smartlist_len(ports_to_forward) + 1;
  4372. argv = tor_malloc_zero(sizeof(char*)*args_n);
  4373. argv[argv_index++] = filename;
  4374. SMARTLIST_FOREACH_BEGIN(ports_to_forward, const char *, port) {
  4375. argv[argv_index++] = "-p";
  4376. argv[argv_index++] = port;
  4377. } SMARTLIST_FOREACH_END(port);
  4378. argv[argv_index] = NULL;
  4379. /* Assume tor-fw-helper will succeed, start it later*/
  4380. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_SUCCESS;
  4381. if (child_handle) {
  4382. tor_process_handle_destroy(child_handle, 1);
  4383. child_handle = NULL;
  4384. }
  4385. #ifdef _WIN32
  4386. /* Passing NULL as lpApplicationName makes Windows search for the .exe */
  4387. status = tor_spawn_background(NULL, argv, NULL, &child_handle);
  4388. #else
  4389. status = tor_spawn_background(filename, argv, NULL, &child_handle);
  4390. #endif
  4391. tor_free_((void*)argv);
  4392. argv=NULL;
  4393. if (PROCESS_STATUS_ERROR == status) {
  4394. log_warn(LD_GENERAL, "Failed to start port forwarding helper %s",
  4395. filename);
  4396. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4397. return;
  4398. }
  4399. log_info(LD_GENERAL,
  4400. "Started port forwarding helper (%s) with pid '%d'",
  4401. filename, tor_process_get_pid(child_handle));
  4402. }
  4403. /* If child is running, read from its stdout and stderr) */
  4404. if (child_handle && PROCESS_STATUS_RUNNING == child_handle->status) {
  4405. /* Read from stdout/stderr and log result */
  4406. retval = 0;
  4407. #ifdef _WIN32
  4408. stderr_status = log_from_handle(child_handle->stderr_pipe, LOG_INFO);
  4409. #else
  4410. stderr_status = log_from_pipe(child_handle->stderr_handle,
  4411. LOG_INFO, filename, &retval);
  4412. #endif
  4413. if (handle_fw_helper_output(child_handle) < 0) {
  4414. log_warn(LD_GENERAL, "Failed to handle fw helper output.");
  4415. stdout_status = -1;
  4416. retval = -1;
  4417. }
  4418. if (retval) {
  4419. /* There was a problem in the child process */
  4420. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4421. }
  4422. /* Combine the two statuses in order of severity */
  4423. if (-1 == stdout_status || -1 == stderr_status)
  4424. /* There was a failure */
  4425. retval = -1;
  4426. #ifdef _WIN32
  4427. else if (!child_handle || tor_get_exit_code(child_handle, 0, NULL) !=
  4428. PROCESS_EXIT_RUNNING) {
  4429. /* process has exited or there was an error */
  4430. /* TODO: Do something with the process return value */
  4431. /* TODO: What if the process output something since
  4432. * between log_from_handle and tor_get_exit_code? */
  4433. retval = 1;
  4434. }
  4435. #else
  4436. else if (1 == stdout_status || 1 == stderr_status)
  4437. /* stdout or stderr was closed, the process probably
  4438. * exited. It will be reaped by waitpid() in main.c */
  4439. /* TODO: Do something with the process return value */
  4440. retval = 1;
  4441. #endif
  4442. else
  4443. /* Both are fine */
  4444. retval = 0;
  4445. /* If either pipe indicates a failure, act on it */
  4446. if (0 != retval) {
  4447. if (1 == retval) {
  4448. log_info(LD_GENERAL, "Port forwarding helper terminated");
  4449. child_handle->status = PROCESS_STATUS_NOTRUNNING;
  4450. } else {
  4451. log_warn(LD_GENERAL, "Failed to read from port forwarding helper");
  4452. child_handle->status = PROCESS_STATUS_ERROR;
  4453. }
  4454. /* TODO: The child might not actually be finished (maybe it failed or
  4455. closed stdout/stderr), so maybe we shouldn't start another? */
  4456. }
  4457. }
  4458. }
  4459. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  4460. void
  4461. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  4462. {
  4463. rng->state = (uint32_t)(seed & 0x7fffffff);
  4464. }
  4465. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  4466. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  4467. * strong; do not rely on it for anything an adversary should not be able to
  4468. * predict. */
  4469. int32_t
  4470. tor_weak_random(tor_weak_rng_t *rng)
  4471. {
  4472. /* Here's a linear congruential generator. OpenBSD and glibc use these
  4473. * parameters; they aren't too bad, and should have maximal period over the
  4474. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  4475. * since some platforms have bad weak RNGs that only return values in the
  4476. * range 0..INT16_MAX, which just isn't enough. */
  4477. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  4478. return (int32_t) rng->state;
  4479. }
  4480. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  4481. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  4482. * top is greater than 0. This randomness is not cryptographically strong; do
  4483. * not rely on it for anything an adversary should not be able to predict. */
  4484. int32_t
  4485. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  4486. {
  4487. /* We don't want to just do tor_weak_random() % top, since random() is often
  4488. * implemented with an LCG whose modulus is a power of 2, and those are
  4489. * cyclic in their low-order bits. */
  4490. int divisor, result;
  4491. tor_assert(top > 0);
  4492. divisor = TOR_WEAK_RANDOM_MAX / top;
  4493. do {
  4494. result = (int32_t)(tor_weak_random(rng) / divisor);
  4495. } while (result >= top);
  4496. return result;
  4497. }