util.c 134 KB

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