util.c 163 KB

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