util.c 134 KB

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