util.c 143 KB

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