util.c 150 KB

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