util.c 139 KB

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