util.c 150 KB

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