util.c 136 KB

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