directory.c 211 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976
  1. /* Copyright (c) 2001-2004, 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. #define DIRECTORY_PRIVATE
  6. #include "or.h"
  7. #include "backtrace.h"
  8. #include "bridges.h"
  9. #include "buffers.h"
  10. #include "circuitbuild.h"
  11. #include "config.h"
  12. #include "connection.h"
  13. #include "connection_edge.h"
  14. #include "conscache.h"
  15. #include "consdiff.h"
  16. #include "consdiffmgr.h"
  17. #include "control.h"
  18. #include "compat.h"
  19. #include "directory.h"
  20. #include "dirserv.h"
  21. #include "dirvote.h"
  22. #include "entrynodes.h"
  23. #include "geoip.h"
  24. #include "hs_cache.h"
  25. #include "hs_common.h"
  26. #include "hs_client.h"
  27. #include "main.h"
  28. #include "microdesc.h"
  29. #include "networkstatus.h"
  30. #include "nodelist.h"
  31. #include "policies.h"
  32. #include "relay.h"
  33. #include "rendclient.h"
  34. #include "rendcommon.h"
  35. #include "rendservice.h"
  36. #include "rephist.h"
  37. #include "router.h"
  38. #include "routerlist.h"
  39. #include "routerparse.h"
  40. #include "routerset.h"
  41. #include "shared_random.h"
  42. #if defined(EXPORTMALLINFO) && defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
  43. #if !defined(OpenBSD)
  44. #include <malloc.h>
  45. #endif
  46. #endif
  47. /**
  48. * \file directory.c
  49. * \brief Code to send and fetch information from directory authorities and
  50. * caches via HTTP.
  51. *
  52. * Directory caches and authorities use dirserv.c to generate the results of a
  53. * query and stream them to the connection; clients use routerparse.c to parse
  54. * them.
  55. *
  56. * Every directory request has a dir_connection_t on the client side and on
  57. * the server side. In most cases, the dir_connection_t object is a linked
  58. * connection, tunneled through an edge_connection_t so that it can be a
  59. * stream on the Tor network. The only non-tunneled connections are those
  60. * that are used to upload material (descriptors and votes) to authorities.
  61. * Among tunneled connections, some use one-hop circuits, and others use
  62. * multi-hop circuits for anonymity.
  63. *
  64. * Directory requests are launched by calling
  65. * directory_initiate_request(). This
  66. * launch the connection, will construct an HTTP request with
  67. * directory_send_command(), send the and wait for a response. The client
  68. * later handles the response with connection_dir_client_reached_eof(),
  69. * which passes the information received to another part of Tor.
  70. *
  71. * On the server side, requests are read in directory_handle_command(),
  72. * which dispatches first on the request type (GET or POST), and then on
  73. * the URL requested. GET requests are processed with a table-based
  74. * dispatcher in url_table[]. The process of handling larger GET requests
  75. * is complicated because we need to avoid allocating a copy of all the
  76. * data to be sent to the client in one huge buffer. Instead, we spool the
  77. * data into the buffer using logic in connection_dirserv_flushed_some() in
  78. * dirserv.c. (TODO: If we extended buf.c to have a zero-copy
  79. * reference-based buffer type, we could remove most of that code, at the
  80. * cost of a bit more reference counting.)
  81. **/
  82. /* In-points to directory.c:
  83. *
  84. * - directory_post_to_dirservers(), called from
  85. * router_upload_dir_desc_to_dirservers() in router.c
  86. * upload_service_descriptor() in rendservice.c
  87. * - directory_get_from_dirserver(), called from
  88. * rend_client_refetch_renddesc() in rendclient.c
  89. * run_scheduled_events() in main.c
  90. * do_hup() in main.c
  91. * - connection_dir_process_inbuf(), called from
  92. * connection_process_inbuf() in connection.c
  93. * - connection_dir_finished_flushing(), called from
  94. * connection_finished_flushing() in connection.c
  95. * - connection_dir_finished_connecting(), called from
  96. * connection_finished_connecting() in connection.c
  97. */
  98. static void directory_send_command(dir_connection_t *conn,
  99. int direct,
  100. const directory_request_t *request);
  101. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  102. static char *http_get_header(const char *headers, const char *which);
  103. static void http_set_address_origin(const char *headers, connection_t *conn);
  104. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  105. static void connection_dir_bridge_routerdesc_failed(dir_connection_t *conn);
  106. static void connection_dir_download_cert_failed(
  107. dir_connection_t *conn, int status_code);
  108. static void connection_dir_retry_bridges(smartlist_t *descs);
  109. static void dir_routerdesc_download_failed(smartlist_t *failed,
  110. int status_code,
  111. int router_purpose,
  112. int was_extrainfo,
  113. int was_descriptor_digests);
  114. static void dir_microdesc_download_failed(smartlist_t *failed,
  115. int status_code);
  116. static int client_likes_consensus(const struct consensus_cache_entry_t *ent,
  117. const char *want_url);
  118. static void connection_dir_close_consensus_fetches(
  119. dir_connection_t *except_this_one, const char *resource);
  120. /********* START VARIABLES **********/
  121. /** How far in the future do we allow a directory server to tell us it is
  122. * before deciding that one of us has the wrong time? */
  123. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  124. #define X_ADDRESS_HEADER "X-Your-Address-Is: "
  125. #define X_OR_DIFF_FROM_CONSENSUS_HEADER "X-Or-Diff-From-Consensus: "
  126. /** HTTP cache control: how long do we tell proxies they can cache each
  127. * kind of document we serve? */
  128. #define FULL_DIR_CACHE_LIFETIME (60*60)
  129. #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
  130. #define DIRPORTFRONTPAGE_CACHE_LIFETIME (20*60)
  131. #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
  132. #define ROUTERDESC_CACHE_LIFETIME (30*60)
  133. #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
  134. #define ROBOTS_CACHE_LIFETIME (24*60*60)
  135. #define MICRODESC_CACHE_LIFETIME (48*60*60)
  136. /********* END VARIABLES ************/
  137. /** Return false if the directory purpose <b>dir_purpose</b>
  138. * does not require an anonymous (three-hop) connection.
  139. *
  140. * Return true 1) by default, 2) if all directory actions have
  141. * specifically been configured to be over an anonymous connection,
  142. * or 3) if the router is a bridge */
  143. int
  144. purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose,
  145. const char *resource)
  146. {
  147. if (get_options()->AllDirActionsPrivate)
  148. return 1;
  149. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  150. if (dir_purpose == DIR_PURPOSE_FETCH_SERVERDESC
  151. && resource && !strcmp(resource, "authority.z")) {
  152. /* We are asking a bridge for its own descriptor. That doesn't need
  153. anonymity. */
  154. return 0;
  155. }
  156. /* Assume all other bridge stuff needs anonymity. */
  157. return 1; /* if no circuits yet, this might break bootstrapping, but it's
  158. * needed to be safe. */
  159. }
  160. switch (dir_purpose)
  161. {
  162. case DIR_PURPOSE_UPLOAD_DIR:
  163. case DIR_PURPOSE_UPLOAD_VOTE:
  164. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  165. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  166. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  167. case DIR_PURPOSE_FETCH_CONSENSUS:
  168. case DIR_PURPOSE_FETCH_CERTIFICATE:
  169. case DIR_PURPOSE_FETCH_SERVERDESC:
  170. case DIR_PURPOSE_FETCH_EXTRAINFO:
  171. case DIR_PURPOSE_FETCH_MICRODESC:
  172. return 0;
  173. case DIR_PURPOSE_HAS_FETCHED_HSDESC:
  174. case DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2:
  175. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  176. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  177. case DIR_PURPOSE_FETCH_HSDESC:
  178. case DIR_PURPOSE_UPLOAD_HSDESC:
  179. return 1;
  180. case DIR_PURPOSE_SERVER:
  181. default:
  182. log_warn(LD_BUG, "Called with dir_purpose=%d, router_purpose=%d",
  183. dir_purpose, router_purpose);
  184. tor_assert_nonfatal_unreached();
  185. return 1; /* Assume it needs anonymity; better safe than sorry. */
  186. }
  187. }
  188. /** Return a newly allocated string describing <b>auth</b>. Only describes
  189. * authority features. */
  190. STATIC char *
  191. authdir_type_to_string(dirinfo_type_t auth)
  192. {
  193. char *result;
  194. smartlist_t *lst = smartlist_new();
  195. if (auth & V3_DIRINFO)
  196. smartlist_add(lst, (void*)"V3");
  197. if (auth & BRIDGE_DIRINFO)
  198. smartlist_add(lst, (void*)"Bridge");
  199. if (smartlist_len(lst)) {
  200. result = smartlist_join_strings(lst, ", ", 0, NULL);
  201. } else {
  202. result = tor_strdup("[Not an authority]");
  203. }
  204. smartlist_free(lst);
  205. return result;
  206. }
  207. /** Return a string describing a given directory connection purpose. */
  208. STATIC const char *
  209. dir_conn_purpose_to_string(int purpose)
  210. {
  211. switch (purpose)
  212. {
  213. case DIR_PURPOSE_UPLOAD_DIR:
  214. return "server descriptor upload";
  215. case DIR_PURPOSE_UPLOAD_VOTE:
  216. return "server vote upload";
  217. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  218. return "consensus signature upload";
  219. case DIR_PURPOSE_FETCH_SERVERDESC:
  220. return "server descriptor fetch";
  221. case DIR_PURPOSE_FETCH_EXTRAINFO:
  222. return "extra-info fetch";
  223. case DIR_PURPOSE_FETCH_CONSENSUS:
  224. return "consensus network-status fetch";
  225. case DIR_PURPOSE_FETCH_CERTIFICATE:
  226. return "authority cert fetch";
  227. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  228. return "status vote fetch";
  229. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  230. return "consensus signature fetch";
  231. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  232. return "hidden-service v2 descriptor fetch";
  233. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  234. return "hidden-service v2 descriptor upload";
  235. case DIR_PURPOSE_FETCH_HSDESC:
  236. return "hidden-service descriptor fetch";
  237. case DIR_PURPOSE_UPLOAD_HSDESC:
  238. return "hidden-service descriptor upload";
  239. case DIR_PURPOSE_FETCH_MICRODESC:
  240. return "microdescriptor fetch";
  241. }
  242. log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
  243. return "(unknown)";
  244. }
  245. /** Return the requisite directory information types. */
  246. STATIC dirinfo_type_t
  247. dir_fetch_type(int dir_purpose, int router_purpose, const char *resource)
  248. {
  249. dirinfo_type_t type;
  250. switch (dir_purpose) {
  251. case DIR_PURPOSE_FETCH_EXTRAINFO:
  252. type = EXTRAINFO_DIRINFO;
  253. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  254. type |= BRIDGE_DIRINFO;
  255. else
  256. type |= V3_DIRINFO;
  257. break;
  258. case DIR_PURPOSE_FETCH_SERVERDESC:
  259. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  260. type = BRIDGE_DIRINFO;
  261. else
  262. type = V3_DIRINFO;
  263. break;
  264. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  265. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  266. case DIR_PURPOSE_FETCH_CERTIFICATE:
  267. type = V3_DIRINFO;
  268. break;
  269. case DIR_PURPOSE_FETCH_CONSENSUS:
  270. type = V3_DIRINFO;
  271. if (resource && !strcmp(resource, "microdesc"))
  272. type |= MICRODESC_DIRINFO;
  273. break;
  274. case DIR_PURPOSE_FETCH_MICRODESC:
  275. type = MICRODESC_DIRINFO;
  276. break;
  277. default:
  278. log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
  279. type = NO_DIRINFO;
  280. break;
  281. }
  282. return type;
  283. }
  284. /** Return true iff <b>identity_digest</b> is the digest of a router which
  285. * says that it caches extrainfos. (If <b>is_authority</b> we always
  286. * believe that to be true.) */
  287. int
  288. router_supports_extrainfo(const char *identity_digest, int is_authority)
  289. {
  290. const node_t *node = node_get_by_id(identity_digest);
  291. if (node && node->ri) {
  292. if (node->ri->caches_extra_info)
  293. return 1;
  294. }
  295. if (is_authority) {
  296. return 1;
  297. }
  298. return 0;
  299. }
  300. /** Return true iff any trusted directory authority has accepted our
  301. * server descriptor.
  302. *
  303. * We consider any authority sufficient because waiting for all of
  304. * them means it never happens while any authority is down; we don't
  305. * go for something more complex in the middle (like \>1/3 or \>1/2 or
  306. * \>=1/2) because that doesn't seem necessary yet.
  307. */
  308. int
  309. directories_have_accepted_server_descriptor(void)
  310. {
  311. const smartlist_t *servers = router_get_trusted_dir_servers();
  312. const or_options_t *options = get_options();
  313. SMARTLIST_FOREACH(servers, dir_server_t *, d, {
  314. if ((d->type & options->PublishServerDescriptor_) &&
  315. d->has_accepted_serverdesc) {
  316. return 1;
  317. }
  318. });
  319. return 0;
  320. }
  321. /** Start a connection to every suitable directory authority, using
  322. * connection purpose <b>dir_purpose</b> and uploading <b>payload</b>
  323. * (of length <b>payload_len</b>). The dir_purpose should be one of
  324. * 'DIR_PURPOSE_UPLOAD_{DIR|VOTE|SIGNATURES}'.
  325. *
  326. * <b>router_purpose</b> describes the type of descriptor we're
  327. * publishing, if we're publishing a descriptor -- e.g. general or bridge.
  328. *
  329. * <b>type</b> specifies what sort of dir authorities (V3,
  330. * BRIDGE, etc) we should upload to.
  331. *
  332. * If <b>extrainfo_len</b> is nonzero, the first <b>payload_len</b> bytes of
  333. * <b>payload</b> hold a router descriptor, and the next <b>extrainfo_len</b>
  334. * bytes of <b>payload</b> hold an extra-info document. Upload the descriptor
  335. * to all authorities, and the extra-info document to all authorities that
  336. * support it.
  337. */
  338. void
  339. directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
  340. dirinfo_type_t type,
  341. const char *payload,
  342. size_t payload_len, size_t extrainfo_len)
  343. {
  344. const or_options_t *options = get_options();
  345. dir_indirection_t indirection;
  346. const smartlist_t *dirservers = router_get_trusted_dir_servers();
  347. int found = 0;
  348. const int exclude_self = (dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
  349. dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  350. tor_assert(dirservers);
  351. /* This tries dirservers which we believe to be down, but ultimately, that's
  352. * harmless, and we may as well err on the side of getting things uploaded.
  353. */
  354. SMARTLIST_FOREACH_BEGIN(dirservers, dir_server_t *, ds) {
  355. routerstatus_t *rs = &(ds->fake_status);
  356. size_t upload_len = payload_len;
  357. if ((type & ds->type) == 0)
  358. continue;
  359. if (exclude_self && router_digest_is_me(ds->digest)) {
  360. /* we don't upload to ourselves, but at least there's now at least
  361. * one authority of this type that has what we wanted to upload. */
  362. found = 1;
  363. continue;
  364. }
  365. if (options->StrictNodes &&
  366. routerset_contains_routerstatus(options->ExcludeNodes, rs, -1)) {
  367. log_warn(LD_DIR, "Wanted to contact authority '%s' for %s, but "
  368. "it's in our ExcludedNodes list and StrictNodes is set. "
  369. "Skipping.",
  370. ds->nickname,
  371. dir_conn_purpose_to_string(dir_purpose));
  372. continue;
  373. }
  374. found = 1; /* at least one authority of this type was listed */
  375. if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
  376. ds->has_accepted_serverdesc = 0;
  377. if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
  378. upload_len += extrainfo_len;
  379. log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
  380. (int) extrainfo_len);
  381. }
  382. if (purpose_needs_anonymity(dir_purpose, router_purpose, NULL)) {
  383. indirection = DIRIND_ANONYMOUS;
  384. } else if (!fascist_firewall_allows_dir_server(ds,
  385. FIREWALL_DIR_CONNECTION,
  386. 0)) {
  387. if (fascist_firewall_allows_dir_server(ds, FIREWALL_OR_CONNECTION, 0))
  388. indirection = DIRIND_ONEHOP;
  389. else
  390. indirection = DIRIND_ANONYMOUS;
  391. } else {
  392. indirection = DIRIND_DIRECT_CONN;
  393. }
  394. directory_request_t *req = directory_request_new(dir_purpose);
  395. directory_request_set_routerstatus(req, rs);
  396. directory_request_set_router_purpose(req, router_purpose);
  397. directory_request_set_indirection(req, indirection);
  398. directory_request_set_payload(req, payload, upload_len);
  399. directory_initiate_request(req);
  400. directory_request_free(req);
  401. } SMARTLIST_FOREACH_END(ds);
  402. if (!found) {
  403. char *s = authdir_type_to_string(type);
  404. log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
  405. "of type '%s', but no authorities of that type listed!", s);
  406. tor_free(s);
  407. }
  408. }
  409. /** Return true iff, according to the values in <b>options</b>, we should be
  410. * using directory guards for direct downloads of directory information. */
  411. STATIC int
  412. should_use_directory_guards(const or_options_t *options)
  413. {
  414. /* Public (non-bridge) servers never use directory guards. */
  415. if (public_server_mode(options))
  416. return 0;
  417. /* If guards are disabled, we can't use directory guards.
  418. */
  419. if (!options->UseEntryGuards)
  420. return 0;
  421. /* If we're configured to fetch directory info aggressively or of a
  422. * nonstandard type, don't use directory guards. */
  423. if (options->DownloadExtraInfo || options->FetchDirInfoEarly ||
  424. options->FetchDirInfoExtraEarly || options->FetchUselessDescriptors)
  425. return 0;
  426. return 1;
  427. }
  428. /** Pick an unconstrained directory server from among our guards, the latest
  429. * networkstatus, or the fallback dirservers, for use in downloading
  430. * information of type <b>type</b>, and return its routerstatus. */
  431. static const routerstatus_t *
  432. directory_pick_generic_dirserver(dirinfo_type_t type, int pds_flags,
  433. uint8_t dir_purpose,
  434. circuit_guard_state_t **guard_state_out)
  435. {
  436. const routerstatus_t *rs = NULL;
  437. const or_options_t *options = get_options();
  438. if (options->UseBridges)
  439. log_warn(LD_BUG, "Called when we have UseBridges set.");
  440. if (should_use_directory_guards(options)) {
  441. const node_t *node = guards_choose_dirguard(guard_state_out);
  442. if (node)
  443. rs = node->rs;
  444. } else {
  445. /* anybody with a non-zero dirport will do */
  446. rs = router_pick_directory_server(type, pds_flags);
  447. }
  448. if (!rs) {
  449. log_info(LD_DIR, "No router found for %s; falling back to "
  450. "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
  451. rs = router_pick_fallback_dirserver(type, pds_flags);
  452. }
  453. return rs;
  454. }
  455. /**
  456. * Set the extra fields in <b>req</b> that are used when requesting a
  457. * consensus of type <b>resource</b>.
  458. *
  459. * Right now, these fields are if-modified-since and x-or-diff-from-consensus.
  460. */
  461. static void
  462. dir_consensus_request_set_additional_headers(directory_request_t *req,
  463. const char *resource)
  464. {
  465. time_t if_modified_since = 0;
  466. uint8_t or_diff_from[DIGEST256_LEN];
  467. int or_diff_from_is_set = 0;
  468. /* DEFAULT_IF_MODIFIED_SINCE_DELAY is 1/20 of the default consensus
  469. * period of 1 hour.
  470. */
  471. const int DEFAULT_IF_MODIFIED_SINCE_DELAY = 180;
  472. const int32_t DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER = 72;
  473. const int32_t MIN_TRY_DIFF_FOR_CONSENSUS_NEWER = 0;
  474. const int32_t MAX_TRY_DIFF_FOR_CONSENSUS_NEWER = 8192;
  475. const char TRY_DIFF_FOR_CONSENSUS_NEWER_NAME[] =
  476. "try-diff-for-consensus-newer-than";
  477. int flav = FLAV_NS;
  478. if (resource)
  479. flav = networkstatus_parse_flavor_name(resource);
  480. int32_t max_age_for_diff = 3600 *
  481. networkstatus_get_param(NULL,
  482. TRY_DIFF_FOR_CONSENSUS_NEWER_NAME,
  483. DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER,
  484. MIN_TRY_DIFF_FOR_CONSENSUS_NEWER,
  485. MAX_TRY_DIFF_FOR_CONSENSUS_NEWER);
  486. if (flav != -1) {
  487. /* IF we have a parsed consensus of this type, we can do an
  488. * if-modified-time based on it. */
  489. networkstatus_t *v;
  490. v = networkstatus_get_latest_consensus_by_flavor(flav);
  491. if (v) {
  492. /* In networks with particularly short V3AuthVotingIntervals,
  493. * ask for the consensus if it's been modified since half the
  494. * V3AuthVotingInterval of the most recent consensus. */
  495. time_t ims_delay = DEFAULT_IF_MODIFIED_SINCE_DELAY;
  496. if (v->fresh_until > v->valid_after
  497. && ims_delay > (v->fresh_until - v->valid_after)/2) {
  498. ims_delay = (v->fresh_until - v->valid_after)/2;
  499. }
  500. if_modified_since = v->valid_after + ims_delay;
  501. if (v->valid_after >= approx_time() - max_age_for_diff) {
  502. memcpy(or_diff_from, v->digest_sha3_as_signed, DIGEST256_LEN);
  503. or_diff_from_is_set = 1;
  504. }
  505. }
  506. } else {
  507. /* Otherwise it might be a consensus we don't parse, but which we
  508. * do cache. Look at the cached copy, perhaps. */
  509. cached_dir_t *cd = dirserv_get_consensus(resource);
  510. /* We have no method of determining the voting interval from an
  511. * unparsed consensus, so we use the default. */
  512. if (cd) {
  513. if_modified_since = cd->published + DEFAULT_IF_MODIFIED_SINCE_DELAY;
  514. if (cd->published >= approx_time() - max_age_for_diff) {
  515. memcpy(or_diff_from, cd->digest_sha3_as_signed, DIGEST256_LEN);
  516. or_diff_from_is_set = 1;
  517. }
  518. }
  519. }
  520. if (if_modified_since > 0)
  521. directory_request_set_if_modified_since(req, if_modified_since);
  522. if (or_diff_from_is_set) {
  523. char hex[HEX_DIGEST256_LEN + 1];
  524. base16_encode(hex, sizeof(hex),
  525. (const char*)or_diff_from, sizeof(or_diff_from));
  526. directory_request_add_header(req, X_OR_DIFF_FROM_CONSENSUS_HEADER, hex);
  527. }
  528. }
  529. /** Start a connection to a random running directory server, using
  530. * connection purpose <b>dir_purpose</b>, intending to fetch descriptors
  531. * of purpose <b>router_purpose</b>, and requesting <b>resource</b>.
  532. * Use <b>pds_flags</b> as arguments to router_pick_directory_server()
  533. * or router_pick_trusteddirserver().
  534. */
  535. MOCK_IMPL(void,
  536. directory_get_from_dirserver,(
  537. uint8_t dir_purpose,
  538. uint8_t router_purpose,
  539. const char *resource,
  540. int pds_flags,
  541. download_want_authority_t want_authority))
  542. {
  543. const routerstatus_t *rs = NULL;
  544. const or_options_t *options = get_options();
  545. int prefer_authority = (directory_fetches_from_authorities(options)
  546. || want_authority == DL_WANT_AUTHORITY);
  547. int require_authority = 0;
  548. int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose,
  549. resource);
  550. dirinfo_type_t type = dir_fetch_type(dir_purpose, router_purpose, resource);
  551. if (type == NO_DIRINFO)
  552. return;
  553. if (!options->FetchServerDescriptors)
  554. return;
  555. circuit_guard_state_t *guard_state = NULL;
  556. if (!get_via_tor) {
  557. if (options->UseBridges && !(type & BRIDGE_DIRINFO)) {
  558. /* We want to ask a running bridge for which we have a descriptor.
  559. *
  560. * When we ask choose_random_entry() for a bridge, we specify what
  561. * sort of dir fetch we'll be doing, so it won't return a bridge
  562. * that can't answer our question.
  563. */
  564. const node_t *node = guards_choose_dirguard(&guard_state);
  565. if (node && node->ri) {
  566. /* every bridge has a routerinfo. */
  567. routerinfo_t *ri = node->ri;
  568. /* clients always make OR connections to bridges */
  569. tor_addr_port_t or_ap;
  570. directory_request_t *req = directory_request_new(dir_purpose);
  571. /* we are willing to use a non-preferred address if we need to */
  572. fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0,
  573. &or_ap);
  574. directory_request_set_or_addr_port(req, &or_ap);
  575. directory_request_set_directory_id_digest(req,
  576. ri->cache_info.identity_digest);
  577. directory_request_set_router_purpose(req, router_purpose);
  578. directory_request_set_resource(req, resource);
  579. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
  580. dir_consensus_request_set_additional_headers(req, resource);
  581. directory_request_set_guard_state(req, guard_state);
  582. directory_initiate_request(req);
  583. directory_request_free(req);
  584. } else {
  585. if (guard_state) {
  586. entry_guard_cancel(&guard_state);
  587. }
  588. log_notice(LD_DIR, "Ignoring directory request, since no bridge "
  589. "nodes are available yet.");
  590. }
  591. return;
  592. } else {
  593. if (prefer_authority || (type & BRIDGE_DIRINFO)) {
  594. /* only ask authdirservers, and don't ask myself */
  595. rs = router_pick_trusteddirserver(type, pds_flags);
  596. if (rs == NULL && (pds_flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  597. PDS_NO_EXISTING_MICRODESC_FETCH))) {
  598. /* We don't want to fetch from any authorities that we're currently
  599. * fetching server descriptors from, and we got no match. Did we
  600. * get no match because all the authorities have connections
  601. * fetching server descriptors (in which case we should just
  602. * return,) or because all the authorities are down or on fire or
  603. * unreachable or something (in which case we should go on with
  604. * our fallback code)? */
  605. pds_flags &= ~(PDS_NO_EXISTING_SERVERDESC_FETCH|
  606. PDS_NO_EXISTING_MICRODESC_FETCH);
  607. rs = router_pick_trusteddirserver(type, pds_flags);
  608. if (rs) {
  609. log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
  610. "are in use.");
  611. return;
  612. }
  613. }
  614. if (rs == NULL && require_authority) {
  615. log_info(LD_DIR, "No authorities were available for %s: will try "
  616. "later.", dir_conn_purpose_to_string(dir_purpose));
  617. return;
  618. }
  619. }
  620. if (!rs && !(type & BRIDGE_DIRINFO)) {
  621. rs = directory_pick_generic_dirserver(type, pds_flags,
  622. dir_purpose,
  623. &guard_state);
  624. if (!rs)
  625. get_via_tor = 1; /* last resort: try routing it via Tor */
  626. }
  627. }
  628. }
  629. if (get_via_tor) {
  630. /* Never use fascistfirewall; we're going via Tor. */
  631. pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
  632. rs = router_pick_directory_server(type, pds_flags);
  633. }
  634. /* If we have any hope of building an indirect conn, we know some router
  635. * descriptors. If (rs==NULL), we can't build circuits anyway, so
  636. * there's no point in falling back to the authorities in this case. */
  637. if (rs) {
  638. const dir_indirection_t indirection =
  639. get_via_tor ? DIRIND_ANONYMOUS : DIRIND_ONEHOP;
  640. directory_request_t *req = directory_request_new(dir_purpose);
  641. directory_request_set_routerstatus(req, rs);
  642. directory_request_set_router_purpose(req, router_purpose);
  643. directory_request_set_indirection(req, indirection);
  644. directory_request_set_resource(req, resource);
  645. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
  646. dir_consensus_request_set_additional_headers(req, resource);
  647. if (guard_state)
  648. directory_request_set_guard_state(req, guard_state);
  649. directory_initiate_request(req);
  650. directory_request_free(req);
  651. } else {
  652. log_notice(LD_DIR,
  653. "While fetching directory info, "
  654. "no running dirservers known. Will try again later. "
  655. "(purpose %d)", dir_purpose);
  656. if (!purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  657. /* remember we tried them all and failed. */
  658. directory_all_unreachable(time(NULL));
  659. }
  660. }
  661. }
  662. /** As directory_get_from_dirserver, but initiates a request to <i>every</i>
  663. * directory authority other than ourself. Only for use by authorities when
  664. * searching for missing information while voting. */
  665. void
  666. directory_get_from_all_authorities(uint8_t dir_purpose,
  667. uint8_t router_purpose,
  668. const char *resource)
  669. {
  670. tor_assert(dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  671. dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  672. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  673. dir_server_t *, ds) {
  674. if (router_digest_is_me(ds->digest))
  675. continue;
  676. if (!(ds->type & V3_DIRINFO))
  677. continue;
  678. const routerstatus_t *rs = &ds->fake_status;
  679. directory_request_t *req = directory_request_new(dir_purpose);
  680. directory_request_set_routerstatus(req, rs);
  681. directory_request_set_router_purpose(req, router_purpose);
  682. directory_request_set_resource(req, resource);
  683. directory_initiate_request(req);
  684. directory_request_free(req);
  685. } SMARTLIST_FOREACH_END(ds);
  686. }
  687. /** Return true iff <b>ind</b> requires a multihop circuit. */
  688. static int
  689. dirind_is_anon(dir_indirection_t ind)
  690. {
  691. return ind == DIRIND_ANON_DIRPORT || ind == DIRIND_ANONYMOUS;
  692. }
  693. /* Choose reachable OR and Dir addresses and ports from status, copying them
  694. * into use_or_ap and use_dir_ap. If indirection is anonymous, then we're
  695. * connecting via another relay, so choose the primary IPv4 address and ports.
  696. *
  697. * status should have at least one reachable address, if we can't choose a
  698. * reachable address, warn and return -1. Otherwise, return 0.
  699. */
  700. static int
  701. directory_choose_address_routerstatus(const routerstatus_t *status,
  702. dir_indirection_t indirection,
  703. tor_addr_port_t *use_or_ap,
  704. tor_addr_port_t *use_dir_ap)
  705. {
  706. tor_assert(status != NULL);
  707. tor_assert(use_or_ap != NULL);
  708. tor_assert(use_dir_ap != NULL);
  709. const or_options_t *options = get_options();
  710. int have_or = 0, have_dir = 0;
  711. /* We expect status to have at least one reachable address if we're
  712. * connecting to it directly.
  713. *
  714. * Therefore, we can simply use the other address if the one we want isn't
  715. * allowed by the firewall.
  716. *
  717. * (When Tor uploads and downloads a hidden service descriptor, it uses
  718. * DIRIND_ANONYMOUS, except for Tor2Web, which uses DIRIND_ONEHOP.
  719. * So this code will only modify the address for Tor2Web's HS descriptor
  720. * fetches. Even Single Onion Servers (NYI) use DIRIND_ANONYMOUS, to avoid
  721. * HSDirs denying service by rejecting descriptors.)
  722. */
  723. /* Initialise the OR / Dir addresses */
  724. tor_addr_make_null(&use_or_ap->addr, AF_UNSPEC);
  725. use_or_ap->port = 0;
  726. tor_addr_make_null(&use_dir_ap->addr, AF_UNSPEC);
  727. use_dir_ap->port = 0;
  728. /* ORPort connections */
  729. if (indirection == DIRIND_ANONYMOUS) {
  730. if (status->addr) {
  731. /* Since we're going to build a 3-hop circuit and ask the 2nd relay
  732. * to extend to this address, always use the primary (IPv4) OR address */
  733. tor_addr_from_ipv4h(&use_or_ap->addr, status->addr);
  734. use_or_ap->port = status->or_port;
  735. have_or = 1;
  736. }
  737. } else if (indirection == DIRIND_ONEHOP) {
  738. /* We use an IPv6 address if we have one and we prefer it.
  739. * Use the preferred address and port if they are reachable, otherwise,
  740. * use the alternate address and port (if any).
  741. */
  742. have_or = fascist_firewall_choose_address_rs(status,
  743. FIREWALL_OR_CONNECTION, 0,
  744. use_or_ap);
  745. }
  746. /* DirPort connections
  747. * DIRIND_ONEHOP uses ORPort, but may fall back to the DirPort on relays */
  748. if (indirection == DIRIND_DIRECT_CONN ||
  749. indirection == DIRIND_ANON_DIRPORT ||
  750. (indirection == DIRIND_ONEHOP
  751. && !directory_must_use_begindir(options))) {
  752. have_dir = fascist_firewall_choose_address_rs(status,
  753. FIREWALL_DIR_CONNECTION, 0,
  754. use_dir_ap);
  755. }
  756. /* We rejected all addresses in the relay's status. This means we can't
  757. * connect to it. */
  758. if (!have_or && !have_dir) {
  759. static int logged_backtrace = 0;
  760. log_info(LD_BUG, "Rejected all OR and Dir addresses from %s when "
  761. "launching an outgoing directory connection to: IPv4 %s OR %d "
  762. "Dir %d IPv6 %s OR %d Dir %d", routerstatus_describe(status),
  763. fmt_addr32(status->addr), status->or_port,
  764. status->dir_port, fmt_addr(&status->ipv6_addr),
  765. status->ipv6_orport, status->dir_port);
  766. if (!logged_backtrace) {
  767. log_backtrace(LOG_INFO, LD_BUG, "Addresses came from");
  768. logged_backtrace = 1;
  769. }
  770. return -1;
  771. }
  772. return 0;
  773. }
  774. /** Return true iff <b>conn</b> is the client side of a directory connection
  775. * we launched to ourself in order to determine the reachability of our
  776. * dir_port. */
  777. static int
  778. directory_conn_is_self_reachability_test(dir_connection_t *conn)
  779. {
  780. if (conn->requested_resource &&
  781. !strcmpstart(conn->requested_resource,"authority")) {
  782. const routerinfo_t *me = router_get_my_routerinfo();
  783. if (me &&
  784. router_digest_is_me(conn->identity_digest) &&
  785. tor_addr_eq_ipv4h(&conn->base_.addr, me->addr) && /*XXXX prop 118*/
  786. me->dir_port == conn->base_.port)
  787. return 1;
  788. }
  789. return 0;
  790. }
  791. /** Called when we are unable to complete the client's request to a directory
  792. * server due to a network error: Mark the router as down and try again if
  793. * possible.
  794. */
  795. static void
  796. connection_dir_request_failed(dir_connection_t *conn)
  797. {
  798. if (conn->guard_state) {
  799. /* We haven't seen a success on this guard state, so consider it to have
  800. * failed. */
  801. entry_guard_failed(&conn->guard_state);
  802. }
  803. if (directory_conn_is_self_reachability_test(conn)) {
  804. return; /* this was a test fetch. don't retry. */
  805. }
  806. if (!entry_list_is_constrained(get_options()))
  807. router_set_status(conn->identity_digest, 0); /* don't try this one again */
  808. if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  809. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  810. log_info(LD_DIR, "Giving up on serverdesc/extrainfo fetch from "
  811. "directory server at '%s'; retrying",
  812. conn->base_.address);
  813. if (conn->router_purpose == ROUTER_PURPOSE_BRIDGE)
  814. connection_dir_bridge_routerdesc_failed(conn);
  815. connection_dir_download_routerdesc_failed(conn);
  816. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  817. if (conn->requested_resource)
  818. networkstatus_consensus_download_failed(0, conn->requested_resource);
  819. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  820. log_info(LD_DIR, "Giving up on certificate fetch from directory server "
  821. "at '%s'; retrying",
  822. conn->base_.address);
  823. connection_dir_download_cert_failed(conn, 0);
  824. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  825. log_info(LD_DIR, "Giving up downloading detached signatures from '%s'",
  826. conn->base_.address);
  827. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  828. log_info(LD_DIR, "Giving up downloading votes from '%s'",
  829. conn->base_.address);
  830. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  831. log_info(LD_DIR, "Giving up on downloading microdescriptors from "
  832. "directory server at '%s'; will retry", conn->base_.address);
  833. connection_dir_download_routerdesc_failed(conn);
  834. }
  835. }
  836. /** Helper: Attempt to fetch directly the descriptors of each bridge
  837. * listed in <b>failed</b>.
  838. */
  839. static void
  840. connection_dir_retry_bridges(smartlist_t *descs)
  841. {
  842. char digest[DIGEST_LEN];
  843. SMARTLIST_FOREACH(descs, const char *, cp,
  844. {
  845. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  846. log_warn(LD_BUG, "Malformed fingerprint in list: %s",
  847. escaped(cp));
  848. continue;
  849. }
  850. retry_bridge_descriptor_fetch_directly(digest);
  851. });
  852. }
  853. /** Called when an attempt to download one or more router descriptors
  854. * or extra-info documents on connection <b>conn</b> failed.
  855. */
  856. static void
  857. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  858. {
  859. /* No need to increment the failure count for routerdescs, since
  860. * it's not their fault. */
  861. /* No need to relaunch descriptor downloads here: we already do it
  862. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  863. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  864. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  865. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  866. (void) conn;
  867. }
  868. /** Called when an attempt to download a bridge's routerdesc from
  869. * one of the authorities failed due to a network error. If
  870. * possible attempt to download descriptors from the bridge directly.
  871. */
  872. static void
  873. connection_dir_bridge_routerdesc_failed(dir_connection_t *conn)
  874. {
  875. smartlist_t *which = NULL;
  876. /* Requests for bridge descriptors are in the form 'fp/', so ignore
  877. anything else. */
  878. if (!conn->requested_resource || strcmpstart(conn->requested_resource,"fp/"))
  879. return;
  880. which = smartlist_new();
  881. dir_split_resource_into_fingerprints(conn->requested_resource
  882. + strlen("fp/"),
  883. which, NULL, 0);
  884. tor_assert(conn->base_.purpose != DIR_PURPOSE_FETCH_EXTRAINFO);
  885. if (smartlist_len(which)) {
  886. connection_dir_retry_bridges(which);
  887. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  888. }
  889. smartlist_free(which);
  890. }
  891. /** Called when an attempt to fetch a certificate fails. */
  892. static void
  893. connection_dir_download_cert_failed(dir_connection_t *conn, int status)
  894. {
  895. const char *fp_pfx = "fp/";
  896. const char *fpsk_pfx = "fp-sk/";
  897. smartlist_t *failed;
  898. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  899. if (!conn->requested_resource)
  900. return;
  901. failed = smartlist_new();
  902. /*
  903. * We have two cases download by fingerprint (resource starts
  904. * with "fp/") or download by fingerprint/signing key pair
  905. * (resource starts with "fp-sk/").
  906. */
  907. if (!strcmpstart(conn->requested_resource, fp_pfx)) {
  908. /* Download by fingerprint case */
  909. dir_split_resource_into_fingerprints(conn->requested_resource +
  910. strlen(fp_pfx),
  911. failed, NULL, DSR_HEX);
  912. SMARTLIST_FOREACH_BEGIN(failed, char *, cp) {
  913. /* Null signing key digest indicates download by fp only */
  914. authority_cert_dl_failed(cp, NULL, status);
  915. tor_free(cp);
  916. } SMARTLIST_FOREACH_END(cp);
  917. } else if (!strcmpstart(conn->requested_resource, fpsk_pfx)) {
  918. /* Download by (fp,sk) pairs */
  919. dir_split_resource_into_fingerprint_pairs(conn->requested_resource +
  920. strlen(fpsk_pfx), failed);
  921. SMARTLIST_FOREACH_BEGIN(failed, fp_pair_t *, cp) {
  922. authority_cert_dl_failed(cp->first, cp->second, status);
  923. tor_free(cp);
  924. } SMARTLIST_FOREACH_END(cp);
  925. } else {
  926. log_warn(LD_DIR,
  927. "Don't know what to do with failure for cert fetch %s",
  928. conn->requested_resource);
  929. }
  930. smartlist_free(failed);
  931. update_certificate_downloads(time(NULL));
  932. }
  933. /* Should this tor instance only use begindir for all its directory requests?
  934. */
  935. int
  936. directory_must_use_begindir(const or_options_t *options)
  937. {
  938. /* Clients, onion services, and bridges must use begindir,
  939. * relays and authorities do not have to */
  940. return !public_server_mode(options);
  941. }
  942. struct directory_request_t {
  943. /**
  944. * These fields specify which directory we're contacting. Routerstatus,
  945. * if present, overrides the other fields.
  946. *
  947. * @{ */
  948. tor_addr_port_t or_addr_port;
  949. tor_addr_port_t dir_addr_port;
  950. char digest[DIGEST_LEN];
  951. const routerstatus_t *routerstatus;
  952. /** @} */
  953. /** One of DIR_PURPOSE_* other than DIR_PURPOSE_SERVER. Describes what
  954. * kind of operation we'll be doing (upload/download), and of what kind
  955. * of document. */
  956. uint8_t dir_purpose;
  957. /** One of ROUTER_PURPOSE_*; used for uploads and downloads of routerinfo
  958. * and extrainfo docs. */
  959. uint8_t router_purpose;
  960. /** Enum: determines whether to anonymize, and whether to use dirport or
  961. * orport. */
  962. dir_indirection_t indirection;
  963. /** Alias to the variable part of the URL for this request */
  964. const char *resource;
  965. /** Alias to the payload to upload (if any) */
  966. const char *payload;
  967. /** Number of bytes to upload from payload</b> */
  968. size_t payload_len;
  969. /** Value to send in an if-modified-since header, or 0 for none. */
  970. time_t if_modified_since;
  971. /** Hidden-service-specific information v2. */
  972. const rend_data_t *rend_query;
  973. /** Extra headers to append to the request */
  974. config_line_t *additional_headers;
  975. /** Hidden-service-specific information for v3+. */
  976. const hs_ident_dir_conn_t *hs_ident;
  977. /** Used internally to directory.c: gets informed when the attempt to
  978. * connect to the directory succeeds or fails, if that attempt bears on the
  979. * directory's usability as a directory guard. */
  980. circuit_guard_state_t *guard_state;
  981. };
  982. /** Evaluate the situation and decide if we should use an encrypted
  983. * "begindir-style" connection for this directory request.
  984. * 0) If there is no DirPort, yes.
  985. * 1) If or_port is 0, or it's a direct conn and or_port is firewalled
  986. * or we're a dir mirror, no.
  987. * 2) If we prefer to avoid begindir conns, and we're not fetching or
  988. * publishing a bridge relay descriptor, no.
  989. * 3) Else yes.
  990. * If returning 0, return in *reason why we can't use begindir.
  991. * reason must not be NULL.
  992. */
  993. static int
  994. directory_command_should_use_begindir(const or_options_t *options,
  995. const directory_request_t *req,
  996. const char **reason)
  997. {
  998. const tor_addr_t *or_addr = &req->or_addr_port.addr;
  999. //const tor_addr_t *dir_addr = &req->dir_addr_port.addr;
  1000. const int or_port = req->or_addr_port.port;
  1001. const int dir_port = req->dir_addr_port.port;
  1002. const dir_indirection_t indirection = req->indirection;
  1003. tor_assert(reason);
  1004. *reason = NULL;
  1005. /* Reasons why we must use begindir */
  1006. if (!dir_port) {
  1007. *reason = "(using begindir - directory with no DirPort)";
  1008. return 1; /* We don't know a DirPort -- must begindir. */
  1009. }
  1010. /* Reasons why we can't possibly use begindir */
  1011. if (!or_port) {
  1012. *reason = "directory with unknown ORPort";
  1013. return 0; /* We don't know an ORPort -- no chance. */
  1014. }
  1015. if (indirection == DIRIND_DIRECT_CONN ||
  1016. indirection == DIRIND_ANON_DIRPORT) {
  1017. *reason = "DirPort connection";
  1018. return 0;
  1019. }
  1020. if (indirection == DIRIND_ONEHOP) {
  1021. /* We're firewalled and want a direct OR connection */
  1022. if (!fascist_firewall_allows_address_addr(or_addr, or_port,
  1023. FIREWALL_OR_CONNECTION, 0, 0)) {
  1024. *reason = "ORPort not reachable";
  1025. return 0;
  1026. }
  1027. }
  1028. /* Reasons why we want to avoid using begindir */
  1029. if (indirection == DIRIND_ONEHOP) {
  1030. if (!directory_must_use_begindir(options)) {
  1031. *reason = "in relay mode";
  1032. return 0;
  1033. }
  1034. }
  1035. /* DIRIND_ONEHOP on a client, or DIRIND_ANONYMOUS
  1036. */
  1037. *reason = "(using begindir)";
  1038. return 1;
  1039. }
  1040. /**
  1041. * Create and return a new directory_request_t with purpose
  1042. * <b>dir_purpose</b>.
  1043. */
  1044. directory_request_t *
  1045. directory_request_new(uint8_t dir_purpose)
  1046. {
  1047. tor_assert(dir_purpose >= DIR_PURPOSE_MIN_);
  1048. tor_assert(dir_purpose <= DIR_PURPOSE_MAX_);
  1049. tor_assert(dir_purpose != DIR_PURPOSE_SERVER);
  1050. tor_assert(dir_purpose != DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2);
  1051. tor_assert(dir_purpose != DIR_PURPOSE_HAS_FETCHED_HSDESC);
  1052. directory_request_t *result = tor_malloc_zero(sizeof(*result));
  1053. tor_addr_make_null(&result->or_addr_port.addr, AF_INET);
  1054. result->or_addr_port.port = 0;
  1055. tor_addr_make_null(&result->dir_addr_port.addr, AF_INET);
  1056. result->dir_addr_port.port = 0;
  1057. result->dir_purpose = dir_purpose;
  1058. result->router_purpose = ROUTER_PURPOSE_GENERAL;
  1059. result->indirection = DIRIND_ONEHOP;
  1060. return result;
  1061. }
  1062. /**
  1063. * Release all resources held by <b>req</b>.
  1064. */
  1065. void
  1066. directory_request_free(directory_request_t *req)
  1067. {
  1068. if (req == NULL)
  1069. return;
  1070. config_free_lines(req->additional_headers);
  1071. tor_free(req);
  1072. }
  1073. /**
  1074. * Set the address and OR port to use for this directory request. If there is
  1075. * no OR port, we'll have to connect over the dirport. (If there are both,
  1076. * the indirection setting determins which to use.)
  1077. */
  1078. void
  1079. directory_request_set_or_addr_port(directory_request_t *req,
  1080. const tor_addr_port_t *p)
  1081. {
  1082. memcpy(&req->or_addr_port, p, sizeof(*p));
  1083. }
  1084. /**
  1085. * Set the address and dirport to use for this directory request. If there
  1086. * is no dirport, we'll have to connect over the OR port. (If there are both,
  1087. * the indirection setting determins which to use.)
  1088. */
  1089. void
  1090. directory_request_set_dir_addr_port(directory_request_t *req,
  1091. const tor_addr_port_t *p)
  1092. {
  1093. memcpy(&req->dir_addr_port, p, sizeof(*p));
  1094. }
  1095. /**
  1096. * Set the RSA identity digest of the directory to use for this directory
  1097. * request.
  1098. */
  1099. void
  1100. directory_request_set_directory_id_digest(directory_request_t *req,
  1101. const char *digest)
  1102. {
  1103. memcpy(req->digest, digest, DIGEST_LEN);
  1104. }
  1105. /**
  1106. * Set the router purpose associated with uploaded and downloaded router
  1107. * descriptors and extrainfo documents in this directory request. The purpose
  1108. * must be one of ROUTER_PURPOSE_GENERAL (the default) or
  1109. * ROUTER_PURPOSE_BRIDGE.
  1110. */
  1111. void
  1112. directory_request_set_router_purpose(directory_request_t *req,
  1113. uint8_t router_purpose)
  1114. {
  1115. tor_assert(router_purpose == ROUTER_PURPOSE_GENERAL ||
  1116. router_purpose == ROUTER_PURPOSE_BRIDGE);
  1117. // assert that it actually makes sense to set this purpose, given
  1118. // the dir_purpose.
  1119. req->router_purpose = router_purpose;
  1120. }
  1121. /**
  1122. * Set the indirection to be used for the directory request. The indirection
  1123. * parameter configures whether to connect to a DirPort or ORPort, and whether
  1124. * to anonymize the connection. DIRIND_ONEHOP (use ORPort, don't anonymize)
  1125. * is the default. See dir_indirection_t for more information.
  1126. */
  1127. void
  1128. directory_request_set_indirection(directory_request_t *req,
  1129. dir_indirection_t indirection)
  1130. {
  1131. req->indirection = indirection;
  1132. }
  1133. /**
  1134. * Set a pointer to the resource to request from a directory. Different
  1135. * request types use resources to indicate different components of their URL.
  1136. * Note that only an alias to <b>resource</b> is stored, so the
  1137. * <b>resource</b> must outlive the request.
  1138. */
  1139. void
  1140. directory_request_set_resource(directory_request_t *req,
  1141. const char *resource)
  1142. {
  1143. req->resource = resource;
  1144. }
  1145. /**
  1146. * Set a pointer to the payload to include with this directory request, along
  1147. * with its length. Note that only an alias to <b>payload</b> is stored, so
  1148. * the <b>payload</b> must outlive the request.
  1149. */
  1150. void
  1151. directory_request_set_payload(directory_request_t *req,
  1152. const char *payload,
  1153. size_t payload_len)
  1154. {
  1155. tor_assert(DIR_PURPOSE_IS_UPLOAD(req->dir_purpose));
  1156. req->payload = payload;
  1157. req->payload_len = payload_len;
  1158. }
  1159. /**
  1160. * Set an if-modified-since date to send along with the request. The
  1161. * default is 0 (meaning, send no if-modified-since header).
  1162. */
  1163. void
  1164. directory_request_set_if_modified_since(directory_request_t *req,
  1165. time_t if_modified_since)
  1166. {
  1167. req->if_modified_since = if_modified_since;
  1168. }
  1169. /** Include a header of name <b>key</b> with content <b>val</b> in the
  1170. * request. Neither may include newlines or other odd characters. Their
  1171. * ordering is not currently guaranteed.
  1172. *
  1173. * Note that, as elsewhere in this module, header keys include a trailing
  1174. * colon and space.
  1175. */
  1176. void
  1177. directory_request_add_header(directory_request_t *req,
  1178. const char *key,
  1179. const char *val)
  1180. {
  1181. config_line_prepend(&req->additional_headers, key, val);
  1182. }
  1183. /**
  1184. * Set an object containing HS data to be associated with this request. Note
  1185. * that only an alias to <b>query</b> is stored, so the <b>query</b> object
  1186. * must outlive the request.
  1187. */
  1188. void
  1189. directory_request_set_rend_query(directory_request_t *req,
  1190. const rend_data_t *query)
  1191. {
  1192. if (query) {
  1193. tor_assert(req->dir_purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 ||
  1194. req->dir_purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2);
  1195. }
  1196. req->rend_query = query;
  1197. }
  1198. /**
  1199. * Set an object containing HS connection identifier to be associated with
  1200. * this request. Note that only an alias to <b>ident</b> is stored, so the
  1201. * <b>ident</b> object must outlive the request.
  1202. */
  1203. void
  1204. directory_request_upload_set_hs_ident(directory_request_t *req,
  1205. const hs_ident_dir_conn_t *ident)
  1206. {
  1207. if (ident) {
  1208. tor_assert(req->dir_purpose == DIR_PURPOSE_UPLOAD_HSDESC);
  1209. }
  1210. req->hs_ident = ident;
  1211. }
  1212. /**
  1213. * Set an object containing HS connection identifier to be associated with
  1214. * this fetch request. Note that only an alias to <b>ident</b> is stored, so
  1215. * the <b>ident</b> object must outlive the request.
  1216. */
  1217. void
  1218. directory_request_fetch_set_hs_ident(directory_request_t *req,
  1219. const hs_ident_dir_conn_t *ident)
  1220. {
  1221. if (ident) {
  1222. tor_assert(req->dir_purpose == DIR_PURPOSE_FETCH_HSDESC);
  1223. }
  1224. req->hs_ident = ident;
  1225. }
  1226. /** Set a static circuit_guard_state_t object to affliate with the request in
  1227. * <b>req</b>. This object will receive notification when the attempt to
  1228. * connect to the guard either succeeds or fails. */
  1229. void
  1230. directory_request_set_guard_state(directory_request_t *req,
  1231. circuit_guard_state_t *state)
  1232. {
  1233. req->guard_state = state;
  1234. }
  1235. /**
  1236. * Internal: Return true if any information for contacting the directory in
  1237. * <b>req</b> has been set, other than by the routerstatus. */
  1238. static int
  1239. directory_request_dir_contact_info_specified(const directory_request_t *req)
  1240. {
  1241. /* We only check for ports here, since we don't use an addr unless the port
  1242. * is set */
  1243. return (req->or_addr_port.port ||
  1244. req->dir_addr_port.port ||
  1245. ! tor_digest_is_zero(req->digest));
  1246. }
  1247. /**
  1248. * Set the routerstatus to use for the directory associated with this
  1249. * request. If this option is set, then no other function to set the
  1250. * directory's address or identity should be called.
  1251. */
  1252. void
  1253. directory_request_set_routerstatus(directory_request_t *req,
  1254. const routerstatus_t *status)
  1255. {
  1256. req->routerstatus = status;
  1257. }
  1258. /**
  1259. * Helper: update the addresses, ports, and identities in <b>req</b>
  1260. * from the routerstatus object in <b>req</b>. Return 0 on success.
  1261. * On failure, warn and return -1.
  1262. */
  1263. static int
  1264. directory_request_set_dir_from_routerstatus(directory_request_t *req)
  1265. {
  1266. const routerstatus_t *status = req->routerstatus;
  1267. if (BUG(status == NULL))
  1268. return -1;
  1269. const or_options_t *options = get_options();
  1270. const node_t *node;
  1271. tor_addr_port_t use_or_ap, use_dir_ap;
  1272. const int anonymized_connection = dirind_is_anon(req->indirection);
  1273. tor_assert(status != NULL);
  1274. node = node_get_by_id(status->identity_digest);
  1275. /* XXX The below check is wrong: !node means it's not in the consensus,
  1276. * but we haven't checked if we have a descriptor for it -- and also,
  1277. * we only care about the descriptor if it's a begindir-style anonymized
  1278. * connection. */
  1279. if (!node && anonymized_connection) {
  1280. log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
  1281. "don't have its router descriptor.",
  1282. routerstatus_describe(status));
  1283. return -1;
  1284. }
  1285. if (options->ExcludeNodes && options->StrictNodes &&
  1286. routerset_contains_routerstatus(options->ExcludeNodes, status, -1)) {
  1287. log_warn(LD_DIR, "Wanted to contact directory mirror %s for %s, but "
  1288. "it's in our ExcludedNodes list and StrictNodes is set. "
  1289. "Skipping. This choice might make your Tor not work.",
  1290. routerstatus_describe(status),
  1291. dir_conn_purpose_to_string(req->dir_purpose));
  1292. return -1;
  1293. }
  1294. /* At this point, if we are a client making a direct connection to a
  1295. * directory server, we have selected a server that has at least one address
  1296. * allowed by ClientUseIPv4/6 and Reachable{"",OR,Dir}Addresses. This
  1297. * selection uses the preference in ClientPreferIPv6{OR,Dir}Port, if
  1298. * possible. (If UseBridges is set, clients always use IPv6, and prefer it
  1299. * by default.)
  1300. *
  1301. * Now choose an address that we can use to connect to the directory server.
  1302. */
  1303. if (directory_choose_address_routerstatus(status,
  1304. req->indirection, &use_or_ap,
  1305. &use_dir_ap) < 0) {
  1306. return -1;
  1307. }
  1308. directory_request_set_or_addr_port(req, &use_or_ap);
  1309. directory_request_set_dir_addr_port(req, &use_dir_ap);
  1310. directory_request_set_directory_id_digest(req, status->identity_digest);
  1311. return 0;
  1312. }
  1313. /**
  1314. * Launch the provided directory request, configured in <b>request</b>.
  1315. * After this function is called, you can free <b>request</b>.
  1316. */
  1317. MOCK_IMPL(void,
  1318. directory_initiate_request,(directory_request_t *request))
  1319. {
  1320. tor_assert(request);
  1321. if (request->routerstatus) {
  1322. tor_assert_nonfatal(
  1323. ! directory_request_dir_contact_info_specified(request));
  1324. if (directory_request_set_dir_from_routerstatus(request) < 0) {
  1325. return;
  1326. }
  1327. }
  1328. const tor_addr_port_t *or_addr_port = &request->or_addr_port;
  1329. const tor_addr_port_t *dir_addr_port = &request->dir_addr_port;
  1330. const char *digest = request->digest;
  1331. const uint8_t dir_purpose = request->dir_purpose;
  1332. const uint8_t router_purpose = request->router_purpose;
  1333. const dir_indirection_t indirection = request->indirection;
  1334. const char *resource = request->resource;
  1335. const rend_data_t *rend_query = request->rend_query;
  1336. const hs_ident_dir_conn_t *hs_ident = request->hs_ident;
  1337. circuit_guard_state_t *guard_state = request->guard_state;
  1338. tor_assert(or_addr_port->port || dir_addr_port->port);
  1339. tor_assert(digest);
  1340. dir_connection_t *conn;
  1341. const or_options_t *options = get_options();
  1342. int socket_error = 0;
  1343. const char *begindir_reason = NULL;
  1344. /* Should the connection be to a relay's OR port (and inside that we will
  1345. * send our directory request)? */
  1346. const int use_begindir =
  1347. directory_command_should_use_begindir(options, request, &begindir_reason);
  1348. /* Will the connection go via a three-hop Tor circuit? Note that this
  1349. * is separate from whether it will use_begindir. */
  1350. const int anonymized_connection = dirind_is_anon(indirection);
  1351. /* What is the address we want to make the directory request to? If
  1352. * we're making a begindir request this is the ORPort of the relay
  1353. * we're contacting; if not a begindir request, this is its DirPort.
  1354. * Note that if anonymized_connection is true, we won't be initiating
  1355. * a connection directly to this address. */
  1356. tor_addr_t addr;
  1357. tor_addr_copy(&addr, &(use_begindir ? or_addr_port : dir_addr_port)->addr);
  1358. uint16_t port = (use_begindir ? or_addr_port : dir_addr_port)->port;
  1359. log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
  1360. anonymized_connection, use_begindir);
  1361. log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
  1362. if (purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  1363. tor_assert(anonymized_connection ||
  1364. rend_non_anonymous_mode_enabled(options));
  1365. }
  1366. /* use encrypted begindir connections for everything except relays
  1367. * this provides better protection for directory fetches */
  1368. if (!use_begindir && directory_must_use_begindir(options)) {
  1369. log_warn(LD_BUG, "Client could not use begindir connection: %s",
  1370. begindir_reason ? begindir_reason : "(NULL)");
  1371. return;
  1372. }
  1373. /* ensure that we don't make direct connections when a SOCKS server is
  1374. * configured. */
  1375. if (!anonymized_connection && !use_begindir && !options->HTTPProxy &&
  1376. (options->Socks4Proxy || options->Socks5Proxy)) {
  1377. log_warn(LD_DIR, "Cannot connect to a directory server through a "
  1378. "SOCKS proxy!");
  1379. return;
  1380. }
  1381. /* Make sure that the destination addr and port we picked is viable. */
  1382. if (!port || tor_addr_is_null(&addr)) {
  1383. static int logged_backtrace = 0;
  1384. log_warn(LD_DIR,
  1385. "Cannot make an outgoing %sconnection without a remote %sPort.",
  1386. use_begindir ? "begindir " : "",
  1387. use_begindir ? "OR" : "Dir");
  1388. if (!logged_backtrace) {
  1389. log_backtrace(LOG_INFO, LD_BUG, "Address came from");
  1390. logged_backtrace = 1;
  1391. }
  1392. return;
  1393. }
  1394. conn = dir_connection_new(tor_addr_family(&addr));
  1395. /* set up conn so it's got all the data we need to remember */
  1396. tor_addr_copy(&conn->base_.addr, &addr);
  1397. conn->base_.port = port;
  1398. conn->base_.address = tor_addr_to_str_dup(&addr);
  1399. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  1400. conn->base_.purpose = dir_purpose;
  1401. conn->router_purpose = router_purpose;
  1402. /* give it an initial state */
  1403. conn->base_.state = DIR_CONN_STATE_CONNECTING;
  1404. /* decide whether we can learn our IP address from this conn */
  1405. /* XXXX This is a bad name for this field now. */
  1406. conn->dirconn_direct = !anonymized_connection;
  1407. /* copy rendezvous data, if any */
  1408. if (rend_query) {
  1409. /* We can't have both v2 and v3+ identifier. */
  1410. tor_assert_nonfatal(!hs_ident);
  1411. conn->rend_data = rend_data_dup(rend_query);
  1412. }
  1413. if (hs_ident) {
  1414. /* We can't have both v2 and v3+ identifier. */
  1415. tor_assert_nonfatal(!rend_query);
  1416. conn->hs_ident = hs_ident_dir_conn_dup(hs_ident);
  1417. }
  1418. if (!anonymized_connection && !use_begindir) {
  1419. /* then we want to connect to dirport directly */
  1420. if (options->HTTPProxy) {
  1421. tor_addr_copy(&addr, &options->HTTPProxyAddr);
  1422. port = options->HTTPProxyPort;
  1423. }
  1424. // In this case we should not have picked a directory guard.
  1425. if (BUG(guard_state)) {
  1426. entry_guard_cancel(&guard_state);
  1427. }
  1428. switch (connection_connect(TO_CONN(conn), conn->base_.address, &addr,
  1429. port, &socket_error)) {
  1430. case -1:
  1431. connection_mark_for_close(TO_CONN(conn));
  1432. return;
  1433. case 1:
  1434. /* start flushing conn */
  1435. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1436. /* fall through */
  1437. case 0:
  1438. /* queue the command on the outbuf */
  1439. directory_send_command(conn, 1, request);
  1440. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  1441. /* writable indicates finish, readable indicates broken link,
  1442. error indicates broken link in windowsland. */
  1443. }
  1444. } else {
  1445. /* We will use a Tor circuit (maybe 1-hop, maybe 3-hop, maybe with
  1446. * begindir, maybe not with begindir) */
  1447. entry_connection_t *linked_conn;
  1448. /* Anonymized tunneled connections can never share a circuit.
  1449. * One-hop directory connections can share circuits with each other
  1450. * but nothing else. */
  1451. int iso_flags = anonymized_connection ? ISO_STREAM : ISO_SESSIONGRP;
  1452. /* If it's an anonymized connection, remember the fact that we
  1453. * wanted it for later: maybe we'll want it again soon. */
  1454. if (anonymized_connection && use_begindir)
  1455. rep_hist_note_used_internal(time(NULL), 0, 1);
  1456. else if (anonymized_connection && !use_begindir)
  1457. rep_hist_note_used_port(time(NULL), conn->base_.port);
  1458. // In this case we should not have a directory guard; we'll
  1459. // get a regular guard later when we build the circuit.
  1460. if (BUG(anonymized_connection && guard_state)) {
  1461. entry_guard_cancel(&guard_state);
  1462. }
  1463. conn->guard_state = guard_state;
  1464. /* make an AP connection
  1465. * populate it and add it at the right state
  1466. * hook up both sides
  1467. */
  1468. linked_conn =
  1469. connection_ap_make_link(TO_CONN(conn),
  1470. conn->base_.address, conn->base_.port,
  1471. digest,
  1472. SESSION_GROUP_DIRCONN, iso_flags,
  1473. use_begindir, !anonymized_connection);
  1474. if (!linked_conn) {
  1475. log_warn(LD_NET,"Making tunnel to dirserver failed.");
  1476. connection_mark_for_close(TO_CONN(conn));
  1477. return;
  1478. }
  1479. if (connection_add(TO_CONN(conn)) < 0) {
  1480. log_warn(LD_NET,"Unable to add connection for link to dirserver.");
  1481. connection_mark_for_close(TO_CONN(conn));
  1482. return;
  1483. }
  1484. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1485. /* queue the command on the outbuf */
  1486. directory_send_command(conn, 0, request);
  1487. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1488. connection_start_reading(ENTRY_TO_CONN(linked_conn));
  1489. }
  1490. }
  1491. /** Return true iff anything we say on <b>conn</b> is being encrypted before
  1492. * we send it to the client/server. */
  1493. int
  1494. connection_dir_is_encrypted(const dir_connection_t *conn)
  1495. {
  1496. /* Right now it's sufficient to see if conn is or has been linked, since
  1497. * the only thing it could be linked to is an edge connection on a
  1498. * circuit, and the only way it could have been unlinked is at the edge
  1499. * connection getting closed.
  1500. */
  1501. return TO_CONN(conn)->linked;
  1502. }
  1503. /** Helper for sorting
  1504. *
  1505. * sort strings alphabetically
  1506. */
  1507. static int
  1508. compare_strs_(const void **a, const void **b)
  1509. {
  1510. const char *s1 = *a, *s2 = *b;
  1511. return strcmp(s1, s2);
  1512. }
  1513. #define CONDITIONAL_CONSENSUS_FPR_LEN 3
  1514. #if (CONDITIONAL_CONSENSUS_FPR_LEN > DIGEST_LEN)
  1515. #error "conditional consensus fingerprint length is larger than digest length"
  1516. #endif
  1517. /** Return the URL we should use for a consensus download.
  1518. *
  1519. * Use the "conditional consensus downloading" feature described in
  1520. * dir-spec.txt, i.e.
  1521. * GET .../consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>
  1522. *
  1523. * If 'resource' is provided, it is the name of a consensus flavor to request.
  1524. */
  1525. static char *
  1526. directory_get_consensus_url(const char *resource)
  1527. {
  1528. char *url = NULL;
  1529. const char *hyphen, *flavor;
  1530. if (resource==NULL || strcmp(resource, "ns")==0) {
  1531. flavor = ""; /* Request ns consensuses as "", so older servers will work*/
  1532. hyphen = "";
  1533. } else {
  1534. flavor = resource;
  1535. hyphen = "-";
  1536. }
  1537. {
  1538. char *authority_id_list;
  1539. smartlist_t *authority_digests = smartlist_new();
  1540. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  1541. dir_server_t *, ds) {
  1542. char *hex;
  1543. if (!(ds->type & V3_DIRINFO))
  1544. continue;
  1545. hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
  1546. base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
  1547. ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
  1548. smartlist_add(authority_digests, hex);
  1549. } SMARTLIST_FOREACH_END(ds);
  1550. smartlist_sort(authority_digests, compare_strs_);
  1551. authority_id_list = smartlist_join_strings(authority_digests,
  1552. "+", 0, NULL);
  1553. tor_asprintf(&url, "/tor/status-vote/current/consensus%s%s/%s.z",
  1554. hyphen, flavor, authority_id_list);
  1555. SMARTLIST_FOREACH(authority_digests, char *, cp, tor_free(cp));
  1556. smartlist_free(authority_digests);
  1557. tor_free(authority_id_list);
  1558. }
  1559. return url;
  1560. }
  1561. /**
  1562. * Copies the ipv6 from source to destination, subject to buffer size limit
  1563. * size. If decorate is true, makes sure the copied address is decorated.
  1564. */
  1565. static void
  1566. copy_ipv6_address(char* destination, const char* source, size_t len,
  1567. int decorate) {
  1568. tor_assert(destination);
  1569. tor_assert(source);
  1570. if (decorate && source[0] != '[') {
  1571. tor_snprintf(destination, len, "[%s]", source);
  1572. } else {
  1573. strlcpy(destination, source, len);
  1574. }
  1575. }
  1576. /** Queue an appropriate HTTP command for <b>request</b> on
  1577. * <b>conn</b>-\>outbuf. If <b>direct</b> is true, we're making a
  1578. * non-anonymized connection to the dirport.
  1579. */
  1580. static void
  1581. directory_send_command(dir_connection_t *conn,
  1582. const int direct,
  1583. const directory_request_t *req)
  1584. {
  1585. tor_assert(req);
  1586. const int purpose = req->dir_purpose;
  1587. const char *resource = req->resource;
  1588. const char *payload = req->payload;
  1589. const size_t payload_len = req->payload_len;
  1590. const time_t if_modified_since = req->if_modified_since;
  1591. const int anonymized_connection = dirind_is_anon(req->indirection);
  1592. char proxystring[256];
  1593. char hoststring[128];
  1594. /* NEEDS to be the same size hoststring.
  1595. Will be decorated with brackets around it if it is ipv6. */
  1596. char decorated_address[128];
  1597. smartlist_t *headers = smartlist_new();
  1598. char *url;
  1599. char *accept_encoding;
  1600. size_t url_len;
  1601. char request[8192];
  1602. size_t request_len, total_request_len = 0;
  1603. const char *httpcommand = NULL;
  1604. tor_assert(conn);
  1605. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  1606. tor_free(conn->requested_resource);
  1607. if (resource)
  1608. conn->requested_resource = tor_strdup(resource);
  1609. /* decorate the ip address if it is ipv6 */
  1610. if (strchr(conn->base_.address, ':')) {
  1611. copy_ipv6_address(decorated_address, conn->base_.address,
  1612. sizeof(decorated_address), 1);
  1613. } else {
  1614. strlcpy(decorated_address, conn->base_.address, sizeof(decorated_address));
  1615. }
  1616. /* come up with a string for which Host: we want */
  1617. if (conn->base_.port == 80) {
  1618. strlcpy(hoststring, decorated_address, sizeof(hoststring));
  1619. } else {
  1620. tor_snprintf(hoststring, sizeof(hoststring), "%s:%d",
  1621. decorated_address, conn->base_.port);
  1622. }
  1623. /* Format if-modified-since */
  1624. if (if_modified_since) {
  1625. char b[RFC1123_TIME_LEN+1];
  1626. format_rfc1123_time(b, if_modified_since);
  1627. smartlist_add_asprintf(headers, "If-Modified-Since: %s\r\n", b);
  1628. }
  1629. /* come up with some proxy lines, if we're using one. */
  1630. if (direct && get_options()->HTTPProxy) {
  1631. char *base64_authenticator=NULL;
  1632. const char *authenticator = get_options()->HTTPProxyAuthenticator;
  1633. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  1634. if (authenticator) {
  1635. base64_authenticator = alloc_http_authenticator(authenticator);
  1636. if (!base64_authenticator)
  1637. log_warn(LD_BUG, "Encoding http authenticator failed");
  1638. }
  1639. if (base64_authenticator) {
  1640. smartlist_add_asprintf(headers,
  1641. "Proxy-Authorization: Basic %s\r\n",
  1642. base64_authenticator);
  1643. tor_free(base64_authenticator);
  1644. }
  1645. } else {
  1646. proxystring[0] = 0;
  1647. }
  1648. if (! anonymized_connection) {
  1649. /* Add Accept-Encoding. */
  1650. accept_encoding = accept_encoding_header();
  1651. smartlist_add_asprintf(headers, "Accept-Encoding: %s\r\n",
  1652. accept_encoding);
  1653. tor_free(accept_encoding);
  1654. }
  1655. /* Add additional headers, if any */
  1656. {
  1657. config_line_t *h;
  1658. for (h = req->additional_headers; h; h = h->next) {
  1659. smartlist_add_asprintf(headers, "%s%s\r\n", h->key, h->value);
  1660. }
  1661. }
  1662. switch (purpose) {
  1663. case DIR_PURPOSE_FETCH_CONSENSUS:
  1664. /* resource is optional. If present, it's a flavor name */
  1665. tor_assert(!payload);
  1666. httpcommand = "GET";
  1667. url = directory_get_consensus_url(resource);
  1668. log_info(LD_DIR, "Downloading consensus from %s using %s",
  1669. hoststring, url);
  1670. break;
  1671. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1672. tor_assert(resource);
  1673. tor_assert(!payload);
  1674. httpcommand = "GET";
  1675. tor_asprintf(&url, "/tor/keys/%s", resource);
  1676. break;
  1677. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  1678. tor_assert(resource);
  1679. tor_assert(!payload);
  1680. httpcommand = "GET";
  1681. tor_asprintf(&url, "/tor/status-vote/next/%s.z", resource);
  1682. break;
  1683. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  1684. tor_assert(!resource);
  1685. tor_assert(!payload);
  1686. httpcommand = "GET";
  1687. url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
  1688. break;
  1689. case DIR_PURPOSE_FETCH_SERVERDESC:
  1690. tor_assert(resource);
  1691. httpcommand = "GET";
  1692. tor_asprintf(&url, "/tor/server/%s", resource);
  1693. break;
  1694. case DIR_PURPOSE_FETCH_EXTRAINFO:
  1695. tor_assert(resource);
  1696. httpcommand = "GET";
  1697. tor_asprintf(&url, "/tor/extra/%s", resource);
  1698. break;
  1699. case DIR_PURPOSE_FETCH_MICRODESC:
  1700. tor_assert(resource);
  1701. httpcommand = "GET";
  1702. tor_asprintf(&url, "/tor/micro/%s", resource);
  1703. break;
  1704. case DIR_PURPOSE_UPLOAD_DIR: {
  1705. const char *why = router_get_descriptor_gen_reason();
  1706. tor_assert(!resource);
  1707. tor_assert(payload);
  1708. httpcommand = "POST";
  1709. url = tor_strdup("/tor/");
  1710. if (why) {
  1711. smartlist_add_asprintf(headers, "X-Desc-Gen-Reason: %s\r\n", why);
  1712. }
  1713. break;
  1714. }
  1715. case DIR_PURPOSE_UPLOAD_VOTE:
  1716. tor_assert(!resource);
  1717. tor_assert(payload);
  1718. httpcommand = "POST";
  1719. url = tor_strdup("/tor/post/vote");
  1720. break;
  1721. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  1722. tor_assert(!resource);
  1723. tor_assert(payload);
  1724. httpcommand = "POST";
  1725. url = tor_strdup("/tor/post/consensus-signature");
  1726. break;
  1727. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  1728. tor_assert(resource);
  1729. tor_assert(strlen(resource) <= REND_DESC_ID_V2_LEN_BASE32);
  1730. tor_assert(!payload);
  1731. httpcommand = "GET";
  1732. tor_asprintf(&url, "/tor/rendezvous2/%s", resource);
  1733. break;
  1734. case DIR_PURPOSE_FETCH_HSDESC:
  1735. tor_assert(resource);
  1736. tor_assert(strlen(resource) <= ED25519_BASE64_LEN);
  1737. tor_assert(!payload);
  1738. httpcommand = "GET";
  1739. tor_asprintf(&url, "/tor/hs/3/%s", resource);
  1740. break;
  1741. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  1742. tor_assert(!resource);
  1743. tor_assert(payload);
  1744. httpcommand = "POST";
  1745. url = tor_strdup("/tor/rendezvous2/publish");
  1746. break;
  1747. case DIR_PURPOSE_UPLOAD_HSDESC:
  1748. tor_assert(resource);
  1749. tor_assert(payload);
  1750. httpcommand = "POST";
  1751. tor_asprintf(&url, "/tor/hs/%s/publish", resource);
  1752. break;
  1753. default:
  1754. tor_assert(0);
  1755. return;
  1756. }
  1757. /* warn in the non-tunneled case */
  1758. if (direct && (strlen(proxystring) + strlen(url) >= 4096)) {
  1759. log_warn(LD_BUG,
  1760. "Squid does not like URLs longer than 4095 bytes, and this "
  1761. "one is %d bytes long: %s%s",
  1762. (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  1763. }
  1764. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  1765. request_len = strlen(request);
  1766. total_request_len += request_len;
  1767. connection_write_to_buf(request, request_len, TO_CONN(conn));
  1768. url_len = strlen(url);
  1769. total_request_len += url_len;
  1770. connection_write_to_buf(url, url_len, TO_CONN(conn));
  1771. tor_free(url);
  1772. if (!strcmp(httpcommand, "POST") || payload) {
  1773. smartlist_add_asprintf(headers, "Content-Length: %lu\r\n",
  1774. payload ? (unsigned long)payload_len : 0);
  1775. }
  1776. {
  1777. char *header = smartlist_join_strings(headers, "", 0, NULL);
  1778. tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nHost: %s\r\n%s\r\n",
  1779. hoststring, header);
  1780. tor_free(header);
  1781. }
  1782. request_len = strlen(request);
  1783. total_request_len += request_len;
  1784. connection_write_to_buf(request, request_len, TO_CONN(conn));
  1785. if (payload) {
  1786. /* then send the payload afterwards too */
  1787. connection_write_to_buf(payload, payload_len, TO_CONN(conn));
  1788. total_request_len += payload_len;
  1789. }
  1790. SMARTLIST_FOREACH(headers, char *, h, tor_free(h));
  1791. smartlist_free(headers);
  1792. log_debug(LD_DIR,
  1793. "Sent request to directory server '%s:%d': "
  1794. "(purpose: %d, request size: " U64_FORMAT ", "
  1795. "payload size: " U64_FORMAT ")",
  1796. conn->base_.address, conn->base_.port,
  1797. conn->base_.purpose,
  1798. U64_PRINTF_ARG(total_request_len),
  1799. U64_PRINTF_ARG(payload ? payload_len : 0));
  1800. }
  1801. /** Parse an HTTP request string <b>headers</b> of the form
  1802. * \verbatim
  1803. * "\%s [http[s]://]\%s HTTP/1..."
  1804. * \endverbatim
  1805. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  1806. * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  1807. * so it does. Return 0.
  1808. * Otherwise, return -1.
  1809. */
  1810. STATIC int
  1811. parse_http_url(const char *headers, char **url)
  1812. {
  1813. char *s, *start, *tmp;
  1814. s = (char *)eat_whitespace_no_nl(headers);
  1815. if (!*s) return -1;
  1816. s = (char *)find_whitespace(s); /* get past GET/POST */
  1817. if (!*s) return -1;
  1818. s = (char *)eat_whitespace_no_nl(s);
  1819. if (!*s) return -1;
  1820. start = s; /* this is it, assuming it's valid */
  1821. s = (char *)find_whitespace(start);
  1822. if (!*s) return -1;
  1823. /* tolerate the http[s] proxy style of putting the hostname in the url */
  1824. if (s-start >= 4 && !strcmpstart(start,"http")) {
  1825. tmp = start + 4;
  1826. if (*tmp == 's')
  1827. tmp++;
  1828. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  1829. tmp = strchr(tmp+3, '/');
  1830. if (tmp && tmp < s) {
  1831. log_debug(LD_DIR,"Skipping over 'http[s]://hostname/' string");
  1832. start = tmp;
  1833. }
  1834. }
  1835. }
  1836. /* Check if the header is well formed (next sequence
  1837. * should be HTTP/1.X\r\n). Assumes we're supporting 1.0? */
  1838. {
  1839. unsigned minor_ver;
  1840. char ch;
  1841. char *e = (char *)eat_whitespace_no_nl(s);
  1842. if (2 != tor_sscanf(e, "HTTP/1.%u%c", &minor_ver, &ch)) {
  1843. return -1;
  1844. }
  1845. if (ch != '\r')
  1846. return -1;
  1847. }
  1848. if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  1849. *url = tor_malloc(s - start + 5);
  1850. strlcpy(*url,"/tor", s-start+5);
  1851. strlcat((*url)+4, start, s-start+1);
  1852. } else {
  1853. *url = tor_strndup(start, s-start);
  1854. }
  1855. return 0;
  1856. }
  1857. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  1858. * <b>which</b>. The key should be given with a terminating colon and space;
  1859. * this function copies everything after, up to but not including the
  1860. * following \\r\\n. */
  1861. static char *
  1862. http_get_header(const char *headers, const char *which)
  1863. {
  1864. const char *cp = headers;
  1865. while (cp) {
  1866. if (!strcasecmpstart(cp, which)) {
  1867. char *eos;
  1868. cp += strlen(which);
  1869. if ((eos = strchr(cp,'\r')))
  1870. return tor_strndup(cp, eos-cp);
  1871. else
  1872. return tor_strdup(cp);
  1873. }
  1874. cp = strchr(cp, '\n');
  1875. if (cp)
  1876. ++cp;
  1877. }
  1878. return NULL;
  1879. }
  1880. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  1881. * <b>conn</b>-\>address to describe our best guess of the address that
  1882. * originated this HTTP request. */
  1883. static void
  1884. http_set_address_origin(const char *headers, connection_t *conn)
  1885. {
  1886. char *fwd;
  1887. fwd = http_get_header(headers, "Forwarded-For: ");
  1888. if (!fwd)
  1889. fwd = http_get_header(headers, "X-Forwarded-For: ");
  1890. if (fwd) {
  1891. tor_addr_t toraddr;
  1892. if (tor_addr_parse(&toraddr,fwd) == -1 ||
  1893. tor_addr_is_internal(&toraddr,0)) {
  1894. log_debug(LD_DIR, "Ignoring local/internal IP %s", escaped(fwd));
  1895. tor_free(fwd);
  1896. return;
  1897. }
  1898. tor_free(conn->address);
  1899. conn->address = tor_strdup(fwd);
  1900. tor_free(fwd);
  1901. }
  1902. }
  1903. /** Parse an HTTP response string <b>headers</b> of the form
  1904. * \verbatim
  1905. * "HTTP/1.\%d \%d\%s\r\n...".
  1906. * \endverbatim
  1907. *
  1908. * If it's well-formed, assign the status code to *<b>code</b> and
  1909. * return 0. Otherwise, return -1.
  1910. *
  1911. * On success: If <b>date</b> is provided, set *date to the Date
  1912. * header in the http headers, or 0 if no such header is found. If
  1913. * <b>compression</b> is provided, set *<b>compression</b> to the
  1914. * compression method given in the Content-Encoding header, or 0 if no
  1915. * such header is found, or -1 if the value of the header is not
  1916. * recognized. If <b>reason</b> is provided, strdup the reason string
  1917. * into it.
  1918. */
  1919. int
  1920. parse_http_response(const char *headers, int *code, time_t *date,
  1921. compress_method_t *compression, char **reason)
  1922. {
  1923. unsigned n1, n2;
  1924. char datestr[RFC1123_TIME_LEN+1];
  1925. smartlist_t *parsed_headers;
  1926. tor_assert(headers);
  1927. tor_assert(code);
  1928. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  1929. if (tor_sscanf(headers, "HTTP/1.%u %u", &n1, &n2) < 2 ||
  1930. (n1 != 0 && n1 != 1) ||
  1931. (n2 < 100 || n2 >= 600)) {
  1932. log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  1933. return -1;
  1934. }
  1935. *code = n2;
  1936. parsed_headers = smartlist_new();
  1937. smartlist_split_string(parsed_headers, headers, "\n",
  1938. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  1939. if (reason) {
  1940. smartlist_t *status_line_elements = smartlist_new();
  1941. tor_assert(smartlist_len(parsed_headers));
  1942. smartlist_split_string(status_line_elements,
  1943. smartlist_get(parsed_headers, 0),
  1944. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1945. tor_assert(smartlist_len(status_line_elements) <= 3);
  1946. if (smartlist_len(status_line_elements) == 3) {
  1947. *reason = smartlist_get(status_line_elements, 2);
  1948. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  1949. }
  1950. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  1951. smartlist_free(status_line_elements);
  1952. }
  1953. if (date) {
  1954. *date = 0;
  1955. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1956. if (!strcmpstart(s, "Date: ")) {
  1957. strlcpy(datestr, s+6, sizeof(datestr));
  1958. /* This will do nothing on failure, so we don't need to check
  1959. the result. We shouldn't warn, since there are many other valid
  1960. date formats besides the one we use. */
  1961. parse_rfc1123_time(datestr, date);
  1962. break;
  1963. });
  1964. }
  1965. if (compression) {
  1966. const char *enc = NULL;
  1967. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1968. if (!strcmpstart(s, "Content-Encoding: ")) {
  1969. enc = s+18; break;
  1970. });
  1971. if (enc == NULL)
  1972. *compression = NO_METHOD;
  1973. else {
  1974. *compression = compression_method_get_by_name(enc);
  1975. if (*compression == UNKNOWN_METHOD)
  1976. log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  1977. escaped(enc));
  1978. }
  1979. }
  1980. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  1981. smartlist_free(parsed_headers);
  1982. return 0;
  1983. }
  1984. /** Return true iff <b>body</b> doesn't start with a plausible router or
  1985. * network-status or microdescriptor opening. This is a sign of possible
  1986. * compression. */
  1987. static int
  1988. body_is_plausible(const char *body, size_t len, int purpose)
  1989. {
  1990. int i;
  1991. if (len == 0)
  1992. return 1; /* empty bodies don't need decompression */
  1993. if (len < 32)
  1994. return 0;
  1995. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  1996. return (!strcmpstart(body,"onion-key"));
  1997. }
  1998. if (!strcmpstart(body,"router") ||
  1999. !strcmpstart(body,"network-status"))
  2000. return 1;
  2001. for (i=0;i<32;++i) {
  2002. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  2003. return 0;
  2004. }
  2005. return 1;
  2006. }
  2007. /** Called when we've just fetched a bunch of router descriptors in
  2008. * <b>body</b>. The list <b>which</b>, if present, holds digests for
  2009. * descriptors we requested: descriptor digests if <b>descriptor_digests</b>
  2010. * is true, or identity digests otherwise. Parse the descriptors, validate
  2011. * them, and annotate them as having purpose <b>purpose</b> and as having been
  2012. * downloaded from <b>source</b>.
  2013. *
  2014. * Return the number of routers actually added. */
  2015. static int
  2016. load_downloaded_routers(const char *body, smartlist_t *which,
  2017. int descriptor_digests,
  2018. int router_purpose,
  2019. const char *source)
  2020. {
  2021. char buf[256];
  2022. char time_buf[ISO_TIME_LEN+1];
  2023. int added = 0;
  2024. int general = router_purpose == ROUTER_PURPOSE_GENERAL;
  2025. format_iso_time(time_buf, time(NULL));
  2026. tor_assert(source);
  2027. if (tor_snprintf(buf, sizeof(buf),
  2028. "@downloaded-at %s\n"
  2029. "@source %s\n"
  2030. "%s%s%s", time_buf, escaped(source),
  2031. !general ? "@purpose " : "",
  2032. !general ? router_purpose_to_string(router_purpose) : "",
  2033. !general ? "\n" : "")<0)
  2034. return added;
  2035. added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  2036. descriptor_digests, buf);
  2037. if (added && general)
  2038. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  2039. count_loading_descriptors_progress());
  2040. return added;
  2041. }
  2042. static int handle_response_fetch_consensus(dir_connection_t *,
  2043. const response_handler_args_t *);
  2044. static int handle_response_fetch_certificate(dir_connection_t *,
  2045. const response_handler_args_t *);
  2046. static int handle_response_fetch_status_vote(dir_connection_t *,
  2047. const response_handler_args_t *);
  2048. static int handle_response_fetch_detached_signatures(dir_connection_t *,
  2049. const response_handler_args_t *);
  2050. static int handle_response_fetch_desc(dir_connection_t *,
  2051. const response_handler_args_t *);
  2052. static int handle_response_fetch_microdesc(dir_connection_t *,
  2053. const response_handler_args_t *);
  2054. static int handle_response_upload_dir(dir_connection_t *,
  2055. const response_handler_args_t *);
  2056. static int handle_response_upload_vote(dir_connection_t *,
  2057. const response_handler_args_t *);
  2058. static int handle_response_upload_signatures(dir_connection_t *,
  2059. const response_handler_args_t *);
  2060. static int handle_response_fetch_renddesc_v2(dir_connection_t *,
  2061. const response_handler_args_t *);
  2062. static int handle_response_upload_renddesc_v2(dir_connection_t *,
  2063. const response_handler_args_t *);
  2064. static int handle_response_upload_hsdesc(dir_connection_t *,
  2065. const response_handler_args_t *);
  2066. static int
  2067. dir_client_decompress_response_body(char **bodyp, size_t *bodylenp,
  2068. dir_connection_t *conn,
  2069. compress_method_t compression,
  2070. int anonymized_connection)
  2071. {
  2072. int rv = 0;
  2073. const char *body = *bodyp;
  2074. size_t body_len = *bodylenp;
  2075. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2076. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  2077. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2078. int plausible = body_is_plausible(body, body_len, conn->base_.purpose);
  2079. if (plausible && compression == NO_METHOD) {
  2080. return 0;
  2081. }
  2082. int severity = LOG_DEBUG;
  2083. char *new_body = NULL;
  2084. size_t new_len = 0;
  2085. const char *description1, *description2;
  2086. int want_to_try_both = 0;
  2087. int tried_both = 0;
  2088. compress_method_t guessed = detect_compression_method(body, body_len);
  2089. description1 = compression_method_get_human_name(compression);
  2090. if (BUG(description1 == NULL))
  2091. description1 = compression_method_get_human_name(UNKNOWN_METHOD);
  2092. if (guessed == UNKNOWN_METHOD && !plausible)
  2093. description2 = "confusing binary junk";
  2094. else
  2095. description2 = compression_method_get_human_name(guessed);
  2096. /* Tell the user if we don't believe what we're told about compression.*/
  2097. want_to_try_both = (compression == UNKNOWN_METHOD ||
  2098. guessed != compression);
  2099. if (want_to_try_both) {
  2100. severity = LOG_PROTOCOL_WARN;
  2101. }
  2102. tor_log(severity, LD_HTTP,
  2103. "HTTP body from server '%s:%d' was labeled as %s, "
  2104. "%s it seems to be %s.%s",
  2105. conn->base_.address, conn->base_.port, description1,
  2106. guessed != compression?"but":"and",
  2107. description2,
  2108. (compression>0 && guessed>0 && want_to_try_both)?
  2109. " Trying both.":"");
  2110. /* Try declared compression first if we can.
  2111. * tor_compress_supports_method() also returns true for NO_METHOD.
  2112. * Ensure that the server is not sending us data compressed using a
  2113. * compression method that is not allowed for anonymous connections. */
  2114. if (anonymized_connection &&
  2115. ! allowed_anonymous_connection_compression_method(compression)) {
  2116. warn_disallowed_anonymous_compression_method(compression);
  2117. rv = -1;
  2118. goto done;
  2119. }
  2120. if (tor_compress_supports_method(compression)) {
  2121. tor_uncompress(&new_body, &new_len, body, body_len, compression,
  2122. !allow_partial, LOG_PROTOCOL_WARN);
  2123. if (new_body) {
  2124. /* We succeeded with the declared compression method. Great! */
  2125. rv = 0;
  2126. goto done;
  2127. }
  2128. }
  2129. /* Okay, if that didn't work, and we think that it was compressed
  2130. * differently, try that. */
  2131. if (anonymized_connection &&
  2132. ! allowed_anonymous_connection_compression_method(guessed)) {
  2133. warn_disallowed_anonymous_compression_method(guessed);
  2134. rv = -1;
  2135. goto done;
  2136. }
  2137. if (tor_compress_supports_method(guessed) &&
  2138. compression != guessed) {
  2139. tor_uncompress(&new_body, &new_len, body, body_len, guessed,
  2140. !allow_partial, LOG_INFO);
  2141. tried_both = 1;
  2142. }
  2143. /* If we're pretty sure that we have a compressed directory, and
  2144. * we didn't manage to uncompress it, then warn and bail. */
  2145. if (!plausible && !new_body) {
  2146. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  2147. "Unable to decompress HTTP body (tried %s%s%s, server '%s:%d').",
  2148. description1,
  2149. tried_both?" and ":"",
  2150. tried_both?description2:"",
  2151. conn->base_.address, conn->base_.port);
  2152. rv = -1;
  2153. goto done;
  2154. }
  2155. done:
  2156. if (new_body) {
  2157. if (rv == 0) {
  2158. /* success! */
  2159. tor_free(*bodyp);
  2160. *bodyp = new_body;
  2161. *bodylenp = new_len;
  2162. } else {
  2163. tor_free(new_body);
  2164. }
  2165. }
  2166. return rv;
  2167. }
  2168. /** We are a client, and we've finished reading the server's
  2169. * response. Parse it and act appropriately.
  2170. *
  2171. * If we're still happy with using this directory server in the future, return
  2172. * 0. Otherwise return -1; and the caller should consider trying the request
  2173. * again.
  2174. *
  2175. * The caller will take care of marking the connection for close.
  2176. */
  2177. static int
  2178. connection_dir_client_reached_eof(dir_connection_t *conn)
  2179. {
  2180. char *body = NULL;
  2181. char *headers = NULL;
  2182. char *reason = NULL;
  2183. size_t body_len = 0;
  2184. int status_code;
  2185. time_t date_header = 0;
  2186. long apparent_skew;
  2187. compress_method_t compression;
  2188. int skewed = 0;
  2189. int rv;
  2190. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2191. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  2192. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2193. size_t received_bytes;
  2194. const int anonymized_connection =
  2195. purpose_needs_anonymity(conn->base_.purpose,
  2196. conn->router_purpose,
  2197. conn->requested_resource);
  2198. received_bytes = connection_get_inbuf_len(TO_CONN(conn));
  2199. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  2200. &headers, MAX_HEADERS_SIZE,
  2201. &body, &body_len, MAX_DIR_DL_SIZE,
  2202. allow_partial)) {
  2203. case -1: /* overflow */
  2204. log_warn(LD_PROTOCOL,
  2205. "'fetch' response too large (server '%s:%d'). Closing.",
  2206. conn->base_.address, conn->base_.port);
  2207. return -1;
  2208. case 0:
  2209. log_info(LD_HTTP,
  2210. "'fetch' response not all here, but we're at eof. Closing.");
  2211. return -1;
  2212. /* case 1, fall through */
  2213. }
  2214. if (parse_http_response(headers, &status_code, &date_header,
  2215. &compression, &reason) < 0) {
  2216. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  2217. conn->base_.address, conn->base_.port);
  2218. rv = -1;
  2219. goto done;
  2220. }
  2221. if (!reason) reason = tor_strdup("[no reason given]");
  2222. tor_log(LOG_DEBUG, LD_DIR,
  2223. "Received response from directory server '%s:%d': %d %s "
  2224. "(purpose: %d, response size: " U64_FORMAT
  2225. #ifdef MEASUREMENTS_21206
  2226. ", data cells received: %d, data cells sent: %d"
  2227. #endif
  2228. ", compression: %d)",
  2229. conn->base_.address, conn->base_.port, status_code,
  2230. escaped(reason), conn->base_.purpose,
  2231. U64_PRINTF_ARG(received_bytes),
  2232. #ifdef MEASUREMENTS_21206
  2233. conn->data_cells_received, conn->data_cells_sent,
  2234. #endif
  2235. compression);
  2236. if (conn->guard_state) {
  2237. /* we count the connection as successful once we can read from it. We do
  2238. * not, however, delay use of the circuit here, since it's just for a
  2239. * one-hop directory request. */
  2240. /* XXXXprop271 note that this will not do the right thing for other
  2241. * waiting circuits that would be triggered by this circuit becoming
  2242. * complete/usable. But that's ok, I think.
  2243. */
  2244. entry_guard_succeeded(&conn->guard_state);
  2245. circuit_guard_state_free(conn->guard_state);
  2246. conn->guard_state = NULL;
  2247. }
  2248. /* now check if it's got any hints for us about our IP address. */
  2249. if (conn->dirconn_direct) {
  2250. char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  2251. if (guess) {
  2252. router_new_address_suggestion(guess, conn);
  2253. tor_free(guess);
  2254. }
  2255. }
  2256. if (date_header > 0) {
  2257. /* The date header was written very soon after we sent our request,
  2258. * so compute the skew as the difference between sending the request
  2259. * and the date header. (We used to check now-date_header, but that's
  2260. * inaccurate if we spend a lot of time downloading.)
  2261. */
  2262. apparent_skew = conn->base_.timestamp_lastwritten - date_header;
  2263. if (labs(apparent_skew)>ALLOW_DIRECTORY_TIME_SKEW) {
  2264. int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  2265. clock_skew_warning(TO_CONN(conn), apparent_skew, trusted, LD_HTTP,
  2266. "directory", "DIRSERV");
  2267. skewed = 1; /* don't check the recommended-versions line */
  2268. } else {
  2269. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  2270. "we are %ld seconds skewed. (That's okay.)", apparent_skew);
  2271. }
  2272. }
  2273. (void) skewed; /* skewed isn't used yet. */
  2274. if (status_code == 503) {
  2275. routerstatus_t *rs;
  2276. dir_server_t *ds;
  2277. const char *id_digest = conn->identity_digest;
  2278. log_info(LD_DIR,"Received http status code %d (%s) from server "
  2279. "'%s:%d'. I'll try again soon.",
  2280. status_code, escaped(reason), conn->base_.address,
  2281. conn->base_.port);
  2282. time_t now = approx_time();
  2283. if ((rs = router_get_mutable_consensus_status_by_id(id_digest)))
  2284. rs->last_dir_503_at = now;
  2285. if ((ds = router_get_fallback_dirserver_by_digest(id_digest)))
  2286. ds->fake_status.last_dir_503_at = now;
  2287. rv = -1;
  2288. goto done;
  2289. }
  2290. if (dir_client_decompress_response_body(&body, &body_len,
  2291. conn, compression, anonymized_connection) < 0) {
  2292. rv = -1;
  2293. goto done;
  2294. }
  2295. response_handler_args_t args;
  2296. memset(&args, 0, sizeof(args));
  2297. args.status_code = status_code;
  2298. args.reason = reason;
  2299. args.body = body;
  2300. args.body_len = body_len;
  2301. args.headers = headers;
  2302. switch (conn->base_.purpose) {
  2303. case DIR_PURPOSE_FETCH_CONSENSUS:
  2304. rv = handle_response_fetch_consensus(conn, &args);
  2305. break;
  2306. case DIR_PURPOSE_FETCH_CERTIFICATE:
  2307. rv = handle_response_fetch_certificate(conn, &args);
  2308. break;
  2309. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  2310. rv = handle_response_fetch_status_vote(conn, &args);
  2311. break;
  2312. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  2313. rv = handle_response_fetch_detached_signatures(conn, &args);
  2314. break;
  2315. case DIR_PURPOSE_FETCH_SERVERDESC:
  2316. case DIR_PURPOSE_FETCH_EXTRAINFO:
  2317. rv = handle_response_fetch_desc(conn, &args);
  2318. break;
  2319. case DIR_PURPOSE_FETCH_MICRODESC:
  2320. rv = handle_response_fetch_microdesc(conn, &args);
  2321. break;
  2322. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  2323. rv = handle_response_fetch_renddesc_v2(conn, &args);
  2324. break;
  2325. case DIR_PURPOSE_UPLOAD_DIR:
  2326. rv = handle_response_upload_dir(conn, &args);
  2327. break;
  2328. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  2329. rv = handle_response_upload_signatures(conn, &args);
  2330. break;
  2331. case DIR_PURPOSE_UPLOAD_VOTE:
  2332. rv = handle_response_upload_vote(conn, &args);
  2333. break;
  2334. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  2335. rv = handle_response_upload_renddesc_v2(conn, &args);
  2336. break;
  2337. case DIR_PURPOSE_UPLOAD_HSDESC:
  2338. rv = handle_response_upload_hsdesc(conn, &args);
  2339. break;
  2340. case DIR_PURPOSE_FETCH_HSDESC:
  2341. rv = handle_response_fetch_hsdesc_v3(conn, &args);
  2342. break;
  2343. default:
  2344. tor_assert_nonfatal_unreached();
  2345. rv = -1;
  2346. break;
  2347. }
  2348. done:
  2349. tor_free(body);
  2350. tor_free(headers);
  2351. tor_free(reason);
  2352. return rv;
  2353. }
  2354. /**
  2355. * Handler function: processes a response to a request for a networkstatus
  2356. * consensus document by checking the consensus, storing it, and marking
  2357. * router requests as reachable.
  2358. **/
  2359. static int
  2360. handle_response_fetch_consensus(dir_connection_t *conn,
  2361. const response_handler_args_t *args)
  2362. {
  2363. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS);
  2364. const int status_code = args->status_code;
  2365. const char *body = args->body;
  2366. const size_t body_len = args->body_len;
  2367. const char *reason = args->reason;
  2368. const time_t now = approx_time();
  2369. const char *consensus;
  2370. char *new_consensus = NULL;
  2371. const char *sourcename;
  2372. int r;
  2373. const char *flavname = conn->requested_resource;
  2374. if (status_code != 200) {
  2375. int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
  2376. tor_log(severity, LD_DIR,
  2377. "Received http status code %d (%s) from server "
  2378. "'%s:%d' while fetching consensus directory.",
  2379. status_code, escaped(reason), conn->base_.address,
  2380. conn->base_.port);
  2381. networkstatus_consensus_download_failed(status_code, flavname);
  2382. return -1;
  2383. }
  2384. if (looks_like_a_consensus_diff(body, body_len)) {
  2385. /* First find our previous consensus. Maybe it's in ram, maybe not. */
  2386. cached_dir_t *cd = dirserv_get_consensus(flavname);
  2387. const char *consensus_body;
  2388. char *owned_consensus = NULL;
  2389. if (cd) {
  2390. consensus_body = cd->dir;
  2391. } else {
  2392. owned_consensus = networkstatus_read_cached_consensus(flavname);
  2393. consensus_body = owned_consensus;
  2394. }
  2395. if (!consensus_body) {
  2396. log_warn(LD_DIR, "Received a consensus diff, but we can't find "
  2397. "any %s-flavored consensus in our current cache.",flavname);
  2398. networkstatus_consensus_download_failed(0, flavname);
  2399. // XXXX if this happens too much, see below
  2400. return -1;
  2401. }
  2402. new_consensus = consensus_diff_apply(consensus_body, body);
  2403. tor_free(owned_consensus);
  2404. if (new_consensus == NULL) {
  2405. log_warn(LD_DIR, "Could not apply consensus diff received from server "
  2406. "'%s:%d'", conn->base_.address, conn->base_.port);
  2407. // XXXX If this happens too many times, we should maybe not use
  2408. // XXXX this directory for diffs any more?
  2409. networkstatus_consensus_download_failed(0, flavname);
  2410. return -1;
  2411. }
  2412. log_info(LD_DIR, "Applied consensus diff (size %d) from server "
  2413. "'%s:%d', resulting in a new consensus document (size %d).",
  2414. (int)body_len, conn->base_.address, conn->base_.port,
  2415. (int)strlen(new_consensus));
  2416. consensus = new_consensus;
  2417. sourcename = "generated based on a diff";
  2418. } else {
  2419. log_info(LD_DIR,"Received consensus directory (body size %d) from server "
  2420. "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
  2421. consensus = body;
  2422. sourcename = "downloaded";
  2423. }
  2424. if ((r=networkstatus_set_current_consensus(consensus, flavname, 0,
  2425. conn->identity_digest))<0) {
  2426. log_fn(r<-1?LOG_WARN:LOG_INFO, LD_DIR,
  2427. "Unable to load %s consensus directory %s from "
  2428. "server '%s:%d'. I'll try again soon.",
  2429. flavname, sourcename, conn->base_.address, conn->base_.port);
  2430. networkstatus_consensus_download_failed(0, flavname);
  2431. tor_free(new_consensus);
  2432. return -1;
  2433. }
  2434. /* If we launched other fetches for this consensus, cancel them. */
  2435. connection_dir_close_consensus_fetches(conn, flavname);
  2436. /* launches router downloads as needed */
  2437. routers_update_all_from_networkstatus(now, 3);
  2438. update_microdescs_from_networkstatus(now);
  2439. update_microdesc_downloads(now);
  2440. directory_info_has_arrived(now, 0, 0);
  2441. if (authdir_mode_v3(get_options())) {
  2442. sr_act_post_consensus(
  2443. networkstatus_get_latest_consensus_by_flavor(FLAV_NS));
  2444. }
  2445. log_info(LD_DIR, "Successfully loaded consensus.");
  2446. tor_free(new_consensus);
  2447. return 0;
  2448. }
  2449. /**
  2450. * Handler function: processes a response to a request for one or more
  2451. * authority certificates
  2452. **/
  2453. static int
  2454. handle_response_fetch_certificate(dir_connection_t *conn,
  2455. const response_handler_args_t *args)
  2456. {
  2457. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  2458. const int status_code = args->status_code;
  2459. const char *reason = args->reason;
  2460. const char *body = args->body;
  2461. const size_t body_len = args->body_len;
  2462. if (status_code != 200) {
  2463. log_warn(LD_DIR,
  2464. "Received http status code %d (%s) from server "
  2465. "'%s:%d' while fetching \"/tor/keys/%s\".",
  2466. status_code, escaped(reason), conn->base_.address,
  2467. conn->base_.port, conn->requested_resource);
  2468. connection_dir_download_cert_failed(conn, status_code);
  2469. return -1;
  2470. }
  2471. log_info(LD_DIR,"Received authority certificates (body size %d) from "
  2472. "server '%s:%d'",
  2473. (int)body_len, conn->base_.address, conn->base_.port);
  2474. /*
  2475. * Tell trusted_dirs_load_certs_from_string() whether it was by fp
  2476. * or fp-sk pair.
  2477. */
  2478. int src_code = -1;
  2479. if (!strcmpstart(conn->requested_resource, "fp/")) {
  2480. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST;
  2481. } else if (!strcmpstart(conn->requested_resource, "fp-sk/")) {
  2482. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST;
  2483. }
  2484. if (src_code != -1) {
  2485. if (trusted_dirs_load_certs_from_string(body, src_code, 1,
  2486. conn->identity_digest)<0) {
  2487. log_warn(LD_DIR, "Unable to parse fetched certificates");
  2488. /* if we fetched more than one and only some failed, the successful
  2489. * ones got flushed to disk so it's safe to call this on them */
  2490. connection_dir_download_cert_failed(conn, status_code);
  2491. } else {
  2492. time_t now = approx_time();
  2493. directory_info_has_arrived(now, 0, 0);
  2494. log_info(LD_DIR, "Successfully loaded certificates from fetch.");
  2495. }
  2496. } else {
  2497. log_warn(LD_DIR,
  2498. "Couldn't figure out what to do with fetched certificates for "
  2499. "unknown resource %s",
  2500. conn->requested_resource);
  2501. connection_dir_download_cert_failed(conn, status_code);
  2502. }
  2503. return 0;
  2504. }
  2505. /**
  2506. * Handler function: processes a response to a request for an authority's
  2507. * current networkstatus vote.
  2508. **/
  2509. static int
  2510. handle_response_fetch_status_vote(dir_connection_t *conn,
  2511. const response_handler_args_t *args)
  2512. {
  2513. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE);
  2514. const int status_code = args->status_code;
  2515. const char *reason = args->reason;
  2516. const char *body = args->body;
  2517. const size_t body_len = args->body_len;
  2518. const char *msg;
  2519. int st;
  2520. log_info(LD_DIR,"Got votes (body size %d) from server %s:%d",
  2521. (int)body_len, conn->base_.address, conn->base_.port);
  2522. if (status_code != 200) {
  2523. log_warn(LD_DIR,
  2524. "Received http status code %d (%s) from server "
  2525. "'%s:%d' while fetching \"/tor/status-vote/next/%s.z\".",
  2526. status_code, escaped(reason), conn->base_.address,
  2527. conn->base_.port, conn->requested_resource);
  2528. return -1;
  2529. }
  2530. dirvote_add_vote(body, &msg, &st);
  2531. if (st > 299) {
  2532. log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
  2533. } else {
  2534. log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
  2535. }
  2536. return 0;
  2537. }
  2538. /**
  2539. * Handler function: processes a response to a request for the signatures
  2540. * that an authority knows about on a given consensus.
  2541. **/
  2542. static int
  2543. handle_response_fetch_detached_signatures(dir_connection_t *conn,
  2544. const response_handler_args_t *args)
  2545. {
  2546. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  2547. const int status_code = args->status_code;
  2548. const char *reason = args->reason;
  2549. const char *body = args->body;
  2550. const size_t body_len = args->body_len;
  2551. const char *msg = NULL;
  2552. log_info(LD_DIR,"Got detached signatures (body size %d) from server %s:%d",
  2553. (int)body_len, conn->base_.address, conn->base_.port);
  2554. if (status_code != 200) {
  2555. log_warn(LD_DIR,
  2556. "Received http status code %d (%s) from server '%s:%d' while fetching "
  2557. "\"/tor/status-vote/next/consensus-signatures.z\".",
  2558. status_code, escaped(reason), conn->base_.address,
  2559. conn->base_.port);
  2560. return -1;
  2561. }
  2562. if (dirvote_add_signatures(body, conn->base_.address, &msg)<0) {
  2563. log_warn(LD_DIR, "Problem adding detached signatures from %s:%d: %s",
  2564. conn->base_.address, conn->base_.port, msg?msg:"???");
  2565. }
  2566. return 0;
  2567. }
  2568. /**
  2569. * Handler function: processes a response to a request for a group of server
  2570. * descriptors or an extrainfo documents.
  2571. **/
  2572. static int
  2573. handle_response_fetch_desc(dir_connection_t *conn,
  2574. const response_handler_args_t *args)
  2575. {
  2576. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2577. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO);
  2578. const int status_code = args->status_code;
  2579. const char *reason = args->reason;
  2580. const char *body = args->body;
  2581. const size_t body_len = args->body_len;
  2582. int was_ei = conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
  2583. smartlist_t *which = NULL;
  2584. int n_asked_for = 0;
  2585. int descriptor_digests = conn->requested_resource &&
  2586. !strcmpstart(conn->requested_resource,"d/");
  2587. log_info(LD_DIR,"Received %s (body size %d) from server '%s:%d'",
  2588. was_ei ? "extra server info" : "server info",
  2589. (int)body_len, conn->base_.address, conn->base_.port);
  2590. if (conn->requested_resource &&
  2591. (!strcmpstart(conn->requested_resource,"d/") ||
  2592. !strcmpstart(conn->requested_resource,"fp/"))) {
  2593. which = smartlist_new();
  2594. dir_split_resource_into_fingerprints(conn->requested_resource +
  2595. (descriptor_digests ? 2 : 3),
  2596. which, NULL, 0);
  2597. n_asked_for = smartlist_len(which);
  2598. }
  2599. if (status_code != 200) {
  2600. int dir_okay = status_code == 404 ||
  2601. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  2602. /* 404 means that it didn't have them; no big deal.
  2603. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  2604. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  2605. "Received http status code %d (%s) from server '%s:%d' "
  2606. "while fetching \"/tor/server/%s\". I'll try again soon.",
  2607. status_code, escaped(reason), conn->base_.address,
  2608. conn->base_.port, conn->requested_resource);
  2609. if (!which) {
  2610. connection_dir_download_routerdesc_failed(conn);
  2611. } else {
  2612. dir_routerdesc_download_failed(which, status_code,
  2613. conn->router_purpose,
  2614. was_ei, descriptor_digests);
  2615. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2616. smartlist_free(which);
  2617. }
  2618. return dir_okay ? 0 : -1;
  2619. }
  2620. /* Learn the routers, assuming we requested by fingerprint or "all"
  2621. * or "authority".
  2622. *
  2623. * We use "authority" to fetch our own descriptor for
  2624. * testing, and to fetch bridge descriptors for bootstrapping. Ignore
  2625. * the output of "authority" requests unless we are using bridges,
  2626. * since otherwise they'll be the response from reachability tests,
  2627. * and we don't really want to add that to our routerlist. */
  2628. if (which || (conn->requested_resource &&
  2629. (!strcmpstart(conn->requested_resource, "all") ||
  2630. (!strcmpstart(conn->requested_resource, "authority") &&
  2631. get_options()->UseBridges)))) {
  2632. /* as we learn from them, we remove them from 'which' */
  2633. if (was_ei) {
  2634. router_load_extrainfo_from_string(body, NULL, SAVED_NOWHERE, which,
  2635. descriptor_digests);
  2636. } else {
  2637. //router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  2638. // descriptor_digests, conn->router_purpose);
  2639. if (load_downloaded_routers(body, which, descriptor_digests,
  2640. conn->router_purpose,
  2641. conn->base_.address)) {
  2642. time_t now = approx_time();
  2643. directory_info_has_arrived(now, 0, 0);
  2644. }
  2645. }
  2646. }
  2647. if (which) { /* mark remaining ones as failed */
  2648. log_info(LD_DIR, "Received %d/%d %s requested from %s:%d",
  2649. n_asked_for-smartlist_len(which), n_asked_for,
  2650. was_ei ? "extra-info documents" : "router descriptors",
  2651. conn->base_.address, (int)conn->base_.port);
  2652. if (smartlist_len(which)) {
  2653. dir_routerdesc_download_failed(which, status_code,
  2654. conn->router_purpose,
  2655. was_ei, descriptor_digests);
  2656. }
  2657. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2658. smartlist_free(which);
  2659. }
  2660. if (directory_conn_is_self_reachability_test(conn))
  2661. router_dirport_found_reachable();
  2662. return 0;
  2663. }
  2664. /**
  2665. * Handler function: processes a response to a request for a group of
  2666. * microdescriptors
  2667. **/
  2668. static int
  2669. handle_response_fetch_microdesc(dir_connection_t *conn,
  2670. const response_handler_args_t *args)
  2671. {
  2672. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2673. const int status_code = args->status_code;
  2674. const char *reason = args->reason;
  2675. const char *body = args->body;
  2676. const size_t body_len = args->body_len;
  2677. smartlist_t *which = NULL;
  2678. log_info(LD_DIR,"Received answer to microdescriptor request (status %d, "
  2679. "body size %d) from server '%s:%d'",
  2680. status_code, (int)body_len, conn->base_.address,
  2681. conn->base_.port);
  2682. tor_assert(conn->requested_resource &&
  2683. !strcmpstart(conn->requested_resource, "d/"));
  2684. which = smartlist_new();
  2685. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  2686. which, NULL,
  2687. DSR_DIGEST256|DSR_BASE64);
  2688. if (status_code != 200) {
  2689. log_info(LD_DIR, "Received status code %d (%s) from server "
  2690. "'%s:%d' while fetching \"/tor/micro/%s\". I'll try again "
  2691. "soon.",
  2692. status_code, escaped(reason), conn->base_.address,
  2693. (int)conn->base_.port, conn->requested_resource);
  2694. dir_microdesc_download_failed(which, status_code);
  2695. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2696. smartlist_free(which);
  2697. return 0;
  2698. } else {
  2699. smartlist_t *mds;
  2700. time_t now = approx_time();
  2701. mds = microdescs_add_to_cache(get_microdesc_cache(),
  2702. body, body+body_len, SAVED_NOWHERE, 0,
  2703. now, which);
  2704. if (smartlist_len(which)) {
  2705. /* Mark remaining ones as failed. */
  2706. dir_microdesc_download_failed(which, status_code);
  2707. }
  2708. if (mds && smartlist_len(mds)) {
  2709. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  2710. count_loading_descriptors_progress());
  2711. directory_info_has_arrived(now, 0, 1);
  2712. }
  2713. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2714. smartlist_free(which);
  2715. smartlist_free(mds);
  2716. }
  2717. return 0;
  2718. }
  2719. /**
  2720. * Handler function: processes a response to a POST request to upload our
  2721. * router descriptor.
  2722. **/
  2723. static int
  2724. handle_response_upload_dir(dir_connection_t *conn,
  2725. const response_handler_args_t *args)
  2726. {
  2727. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_DIR);
  2728. const int status_code = args->status_code;
  2729. const char *reason = args->reason;
  2730. const char *headers = args->headers;
  2731. switch (status_code) {
  2732. case 200: {
  2733. dir_server_t *ds =
  2734. router_get_trusteddirserver_by_digest(conn->identity_digest);
  2735. char *rejected_hdr = http_get_header(headers,
  2736. "X-Descriptor-Not-New: ");
  2737. if (rejected_hdr) {
  2738. if (!strcmp(rejected_hdr, "Yes")) {
  2739. log_info(LD_GENERAL,
  2740. "Authority '%s' declined our descriptor (not new)",
  2741. ds->nickname);
  2742. /* XXXX use this information; be sure to upload next one
  2743. * sooner. -NM */
  2744. /* XXXX++ On further thought, the task above implies that we're
  2745. * basing our regenerate-descriptor time on when we uploaded the
  2746. * last descriptor, not on the published time of the last
  2747. * descriptor. If those are different, that's a bad thing to
  2748. * do. -NM */
  2749. }
  2750. tor_free(rejected_hdr);
  2751. }
  2752. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  2753. "descriptor: finished.");
  2754. control_event_server_status(
  2755. LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
  2756. conn->base_.address, conn->base_.port);
  2757. ds->has_accepted_serverdesc = 1;
  2758. if (directories_have_accepted_server_descriptor())
  2759. control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
  2760. }
  2761. break;
  2762. case 400:
  2763. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  2764. "dirserver '%s:%d'. Please correct.",
  2765. escaped(reason), conn->base_.address, conn->base_.port);
  2766. control_event_server_status(LOG_WARN,
  2767. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  2768. conn->base_.address, conn->base_.port, escaped(reason));
  2769. break;
  2770. default:
  2771. log_warn(LD_GENERAL,
  2772. "HTTP status %d (%s) was unexpected while uploading "
  2773. "descriptor to server '%s:%d'. Possibly the server is "
  2774. "misconfigured?",
  2775. status_code, escaped(reason), conn->base_.address,
  2776. conn->base_.port);
  2777. break;
  2778. }
  2779. /* return 0 in all cases, since we don't want to mark any
  2780. * dirservers down just because they don't like us. */
  2781. return 0;
  2782. }
  2783. /**
  2784. * Handler function: processes a response to POST request to upload our
  2785. * own networkstatus vote.
  2786. **/
  2787. static int
  2788. handle_response_upload_vote(dir_connection_t *conn,
  2789. const response_handler_args_t *args)
  2790. {
  2791. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_VOTE);
  2792. const int status_code = args->status_code;
  2793. const char *reason = args->reason;
  2794. switch (status_code) {
  2795. case 200: {
  2796. log_notice(LD_DIR,"Uploaded a vote to dirserver %s:%d",
  2797. conn->base_.address, conn->base_.port);
  2798. }
  2799. break;
  2800. case 400:
  2801. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2802. "vote to dirserver '%s:%d'. Please correct.",
  2803. escaped(reason), conn->base_.address, conn->base_.port);
  2804. break;
  2805. default:
  2806. log_warn(LD_GENERAL,
  2807. "HTTP status %d (%s) was unexpected while uploading "
  2808. "vote to server '%s:%d'.",
  2809. status_code, escaped(reason), conn->base_.address,
  2810. conn->base_.port);
  2811. break;
  2812. }
  2813. /* return 0 in all cases, since we don't want to mark any
  2814. * dirservers down just because they don't like us. */
  2815. return 0;
  2816. }
  2817. /**
  2818. * Handler function: processes a response to POST request to upload our
  2819. * view of the signatures on the current consensus.
  2820. **/
  2821. static int
  2822. handle_response_upload_signatures(dir_connection_t *conn,
  2823. const response_handler_args_t *args)
  2824. {
  2825. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  2826. const int status_code = args->status_code;
  2827. const char *reason = args->reason;
  2828. switch (status_code) {
  2829. case 200: {
  2830. log_notice(LD_DIR,"Uploaded signature(s) to dirserver %s:%d",
  2831. conn->base_.address, conn->base_.port);
  2832. }
  2833. break;
  2834. case 400:
  2835. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2836. "signatures to dirserver '%s:%d'. Please correct.",
  2837. escaped(reason), conn->base_.address, conn->base_.port);
  2838. break;
  2839. default:
  2840. log_warn(LD_GENERAL,
  2841. "HTTP status %d (%s) was unexpected while uploading "
  2842. "signatures to server '%s:%d'.",
  2843. status_code, escaped(reason), conn->base_.address,
  2844. conn->base_.port);
  2845. break;
  2846. }
  2847. /* return 0 in all cases, since we don't want to mark any
  2848. * dirservers down just because they don't like us. */
  2849. return 0;
  2850. }
  2851. /**
  2852. * Handler function: processes a response to a request for a v3 hidden service
  2853. * descriptor.
  2854. **/
  2855. STATIC int
  2856. handle_response_fetch_hsdesc_v3(dir_connection_t *conn,
  2857. const response_handler_args_t *args)
  2858. {
  2859. const int status_code = args->status_code;
  2860. const char *reason = args->reason;
  2861. const char *body = args->body;
  2862. const size_t body_len = args->body_len;
  2863. tor_assert(conn->hs_ident);
  2864. log_info(LD_REND,"Received v3 hsdesc (body size %d, status %d (%s))",
  2865. (int)body_len, status_code, escaped(reason));
  2866. switch (status_code) {
  2867. case 200:
  2868. /* We got something: Try storing it in the cache. */
  2869. if (hs_cache_store_as_client(body, &conn->hs_ident->identity_pk) < 0) {
  2870. log_warn(LD_REND, "Failed to store hidden service descriptor");
  2871. } else {
  2872. log_info(LD_REND, "Stored hidden service descriptor successfully.");
  2873. TO_CONN(conn)->purpose = DIR_PURPOSE_HAS_FETCHED_HSDESC;
  2874. hs_client_desc_has_arrived(conn->hs_ident);
  2875. }
  2876. break;
  2877. case 404:
  2878. /* Not there. We'll retry when connection_about_to_close_connection()
  2879. * tries to clean this conn up. */
  2880. log_info(LD_REND, "Fetching hidden service v3 descriptor not found: "
  2881. "Retrying at another directory.");
  2882. /* TODO: Inform the control port */
  2883. break;
  2884. case 400:
  2885. log_warn(LD_REND, "Fetching v3 hidden service descriptor failed: "
  2886. "http status 400 (%s). Dirserver didn't like our "
  2887. "query? Retrying at another directory.",
  2888. escaped(reason));
  2889. break;
  2890. default:
  2891. log_warn(LD_REND, "Fetching v3 hidden service descriptor failed: "
  2892. "http status %d (%s) response unexpected from HSDir server "
  2893. "'%s:%d'. Retrying at another directory.",
  2894. status_code, escaped(reason), TO_CONN(conn)->address,
  2895. TO_CONN(conn)->port);
  2896. break;
  2897. }
  2898. return 0;
  2899. }
  2900. /**
  2901. * Handler function: processes a response to a request for a v2 hidden service
  2902. * descriptor.
  2903. **/
  2904. static int
  2905. handle_response_fetch_renddesc_v2(dir_connection_t *conn,
  2906. const response_handler_args_t *args)
  2907. {
  2908. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_RENDDESC_V2);
  2909. const int status_code = args->status_code;
  2910. const char *reason = args->reason;
  2911. const char *body = args->body;
  2912. const size_t body_len = args->body_len;
  2913. #define SEND_HS_DESC_FAILED_EVENT(reason) \
  2914. (control_event_hs_descriptor_failed(conn->rend_data, \
  2915. conn->identity_digest, \
  2916. reason))
  2917. #define SEND_HS_DESC_FAILED_CONTENT() \
  2918. (control_event_hs_descriptor_content( \
  2919. rend_data_get_address(conn->rend_data), \
  2920. conn->requested_resource, \
  2921. conn->identity_digest, \
  2922. NULL))
  2923. tor_assert(conn->rend_data);
  2924. log_info(LD_REND,"Received rendezvous descriptor (body size %d, status %d "
  2925. "(%s))",
  2926. (int)body_len, status_code, escaped(reason));
  2927. switch (status_code) {
  2928. case 200:
  2929. {
  2930. rend_cache_entry_t *entry = NULL;
  2931. if (rend_cache_store_v2_desc_as_client(body,
  2932. conn->requested_resource,
  2933. conn->rend_data, &entry) < 0) {
  2934. log_warn(LD_REND,"Fetching v2 rendezvous descriptor failed. "
  2935. "Retrying at another directory.");
  2936. /* We'll retry when connection_about_to_close_connection()
  2937. * cleans this dir conn up. */
  2938. SEND_HS_DESC_FAILED_EVENT("BAD_DESC");
  2939. SEND_HS_DESC_FAILED_CONTENT();
  2940. } else {
  2941. char service_id[REND_SERVICE_ID_LEN_BASE32 + 1];
  2942. /* Should never be NULL here if we found the descriptor. */
  2943. tor_assert(entry);
  2944. rend_get_service_id(entry->parsed->pk, service_id);
  2945. /* success. notify pending connections about this. */
  2946. log_info(LD_REND, "Successfully fetched v2 rendezvous "
  2947. "descriptor.");
  2948. control_event_hs_descriptor_received(service_id,
  2949. conn->rend_data,
  2950. conn->identity_digest);
  2951. control_event_hs_descriptor_content(service_id,
  2952. conn->requested_resource,
  2953. conn->identity_digest,
  2954. body);
  2955. conn->base_.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2;
  2956. rend_client_desc_trynow(service_id);
  2957. memwipe(service_id, 0, sizeof(service_id));
  2958. }
  2959. break;
  2960. }
  2961. case 404:
  2962. /* Not there. We'll retry when
  2963. * connection_about_to_close_connection() cleans this conn up. */
  2964. log_info(LD_REND,"Fetching v2 rendezvous descriptor failed: "
  2965. "Retrying at another directory.");
  2966. SEND_HS_DESC_FAILED_EVENT("NOT_FOUND");
  2967. SEND_HS_DESC_FAILED_CONTENT();
  2968. break;
  2969. case 400:
  2970. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2971. "http status 400 (%s). Dirserver didn't like our "
  2972. "v2 rendezvous query? Retrying at another directory.",
  2973. escaped(reason));
  2974. SEND_HS_DESC_FAILED_EVENT("QUERY_REJECTED");
  2975. SEND_HS_DESC_FAILED_CONTENT();
  2976. break;
  2977. default:
  2978. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2979. "http status %d (%s) response unexpected while "
  2980. "fetching v2 hidden service descriptor (server '%s:%d'). "
  2981. "Retrying at another directory.",
  2982. status_code, escaped(reason), conn->base_.address,
  2983. conn->base_.port);
  2984. SEND_HS_DESC_FAILED_EVENT("UNEXPECTED");
  2985. SEND_HS_DESC_FAILED_CONTENT();
  2986. break;
  2987. }
  2988. return 0;
  2989. }
  2990. /**
  2991. * Handler function: processes a response to a POST request to upload a v2
  2992. * hidden service descriptor.
  2993. **/
  2994. static int
  2995. handle_response_upload_renddesc_v2(dir_connection_t *conn,
  2996. const response_handler_args_t *args)
  2997. {
  2998. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2);
  2999. const int status_code = args->status_code;
  3000. const char *reason = args->reason;
  3001. #define SEND_HS_DESC_UPLOAD_FAILED_EVENT(reason) \
  3002. (control_event_hs_descriptor_upload_failed( \
  3003. conn->identity_digest, \
  3004. rend_data_get_address(conn->rend_data), \
  3005. reason))
  3006. log_info(LD_REND,"Uploaded rendezvous descriptor (status %d "
  3007. "(%s))",
  3008. status_code, escaped(reason));
  3009. /* Without the rend data, we'll have a problem identifying what has been
  3010. * uploaded for which service. */
  3011. tor_assert(conn->rend_data);
  3012. switch (status_code) {
  3013. case 200:
  3014. log_info(LD_REND,
  3015. "Uploading rendezvous descriptor: finished with status "
  3016. "200 (%s)", escaped(reason));
  3017. control_event_hs_descriptor_uploaded(conn->identity_digest,
  3018. rend_data_get_address(conn->rend_data));
  3019. rend_service_desc_has_uploaded(conn->rend_data);
  3020. break;
  3021. case 400:
  3022. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  3023. "'%s:%d'. Malformed rendezvous descriptor?",
  3024. escaped(reason), conn->base_.address, conn->base_.port);
  3025. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UPLOAD_REJECTED");
  3026. break;
  3027. default:
  3028. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  3029. "'%s:%d').",
  3030. status_code, escaped(reason), conn->base_.address,
  3031. conn->base_.port);
  3032. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UNEXPECTED");
  3033. break;
  3034. }
  3035. return 0;
  3036. }
  3037. /**
  3038. * Handler function: processes a response to a POST request to upload an
  3039. * hidden service descriptor.
  3040. **/
  3041. static int
  3042. handle_response_upload_hsdesc(dir_connection_t *conn,
  3043. const response_handler_args_t *args)
  3044. {
  3045. const int status_code = args->status_code;
  3046. const char *reason = args->reason;
  3047. tor_assert(conn);
  3048. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_HSDESC);
  3049. log_info(LD_REND, "Uploaded hidden service descriptor (status %d "
  3050. "(%s))",
  3051. status_code, escaped(reason));
  3052. /* For this directory response, it MUST have an hidden service identifier on
  3053. * this connection. */
  3054. tor_assert(conn->hs_ident);
  3055. switch (status_code) {
  3056. case 200:
  3057. log_info(LD_REND, "Uploading hidden service descriptor: "
  3058. "finished with status 200 (%s)", escaped(reason));
  3059. /* XXX: Trigger control event. */
  3060. break;
  3061. case 400:
  3062. log_warn(LD_REND, "Uploading hidden service descriptor: http "
  3063. "status 400 (%s) response from dirserver "
  3064. "'%s:%d'. Malformed hidden service descriptor?",
  3065. escaped(reason), conn->base_.address, conn->base_.port);
  3066. /* XXX: Trigger control event. */
  3067. break;
  3068. default:
  3069. log_warn(LD_REND, "Uploading hidden service descriptor: http "
  3070. "status %d (%s) response unexpected (server "
  3071. "'%s:%d').",
  3072. status_code, escaped(reason), conn->base_.address,
  3073. conn->base_.port);
  3074. /* XXX: Trigger control event. */
  3075. break;
  3076. }
  3077. return 0;
  3078. }
  3079. /** Called when a directory connection reaches EOF. */
  3080. int
  3081. connection_dir_reached_eof(dir_connection_t *conn)
  3082. {
  3083. int retval;
  3084. if (conn->base_.state != DIR_CONN_STATE_CLIENT_READING) {
  3085. log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
  3086. conn->base_.state);
  3087. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  3088. connection_mark_for_close(TO_CONN(conn));
  3089. return -1;
  3090. }
  3091. retval = connection_dir_client_reached_eof(conn);
  3092. if (retval == 0) /* success */
  3093. conn->base_.state = DIR_CONN_STATE_CLIENT_FINISHED;
  3094. connection_mark_for_close(TO_CONN(conn));
  3095. return retval;
  3096. }
  3097. /** If any directory object is arriving, and it's over 10MB large, we're
  3098. * getting DoS'd. (As of 0.1.2.x, raw directories are about 1MB, and we never
  3099. * ask for more than 96 router descriptors at a time.)
  3100. */
  3101. #define MAX_DIRECTORY_OBJECT_SIZE (10*(1<<20))
  3102. #define MAX_VOTE_DL_SIZE (MAX_DIRECTORY_OBJECT_SIZE * 5)
  3103. /** Read handler for directory connections. (That's connections <em>to</em>
  3104. * directory servers and connections <em>at</em> directory servers.)
  3105. */
  3106. int
  3107. connection_dir_process_inbuf(dir_connection_t *conn)
  3108. {
  3109. size_t max_size;
  3110. tor_assert(conn);
  3111. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3112. /* Directory clients write, then read data until they receive EOF;
  3113. * directory servers read data until they get an HTTP command, then
  3114. * write their response (when it's finished flushing, they mark for
  3115. * close).
  3116. */
  3117. /* If we're on the dirserver side, look for a command. */
  3118. if (conn->base_.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  3119. if (directory_handle_command(conn) < 0) {
  3120. connection_mark_for_close(TO_CONN(conn));
  3121. return -1;
  3122. }
  3123. return 0;
  3124. }
  3125. max_size =
  3126. (TO_CONN(conn)->purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) ?
  3127. MAX_VOTE_DL_SIZE : MAX_DIRECTORY_OBJECT_SIZE;
  3128. if (connection_get_inbuf_len(TO_CONN(conn)) > max_size) {
  3129. log_warn(LD_HTTP,
  3130. "Too much data received from directory connection (%s): "
  3131. "denial of service attempt, or you need to upgrade?",
  3132. conn->base_.address);
  3133. connection_mark_for_close(TO_CONN(conn));
  3134. return -1;
  3135. }
  3136. if (!conn->base_.inbuf_reached_eof)
  3137. log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
  3138. return 0;
  3139. }
  3140. /** We are closing a dir connection: If <b>dir_conn</b> is a dir connection
  3141. * that tried to fetch an HS descriptor, check if it successfuly fetched it,
  3142. * or if we need to try again. */
  3143. static void
  3144. refetch_hsdesc_if_needed(dir_connection_t *dir_conn)
  3145. {
  3146. connection_t *conn = TO_CONN(dir_conn);
  3147. /* If we were trying to fetch a v2 rend desc and did not succeed, retry as
  3148. * needed. (If a fetch is successful, the connection state is changed to
  3149. * DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2 or DIR_PURPOSE_HAS_FETCHED_HSDESC to
  3150. * mark that refetching is unnecessary.) */
  3151. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
  3152. dir_conn->rend_data &&
  3153. rend_valid_v2_service_id(
  3154. rend_data_get_address(dir_conn->rend_data))) {
  3155. rend_client_refetch_v2_renddesc(dir_conn->rend_data);
  3156. }
  3157. /* Check for v3 rend desc fetch */
  3158. if (conn->purpose == DIR_PURPOSE_FETCH_HSDESC &&
  3159. dir_conn->hs_ident &&
  3160. !ed25519_public_key_is_zero(&dir_conn->hs_ident->identity_pk)) {
  3161. hs_client_refetch_hsdesc(&dir_conn->hs_ident->identity_pk);
  3162. }
  3163. }
  3164. /** Called when we're about to finally unlink and free a directory connection:
  3165. * perform necessary accounting and cleanup */
  3166. void
  3167. connection_dir_about_to_close(dir_connection_t *dir_conn)
  3168. {
  3169. connection_t *conn = TO_CONN(dir_conn);
  3170. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  3171. /* It's a directory connection and connecting or fetching
  3172. * failed: forget about this router, and maybe try again. */
  3173. connection_dir_request_failed(dir_conn);
  3174. }
  3175. refetch_hsdesc_if_needed(dir_conn);
  3176. }
  3177. /** Create an http response for the client <b>conn</b> out of
  3178. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  3179. */
  3180. static void
  3181. write_http_status_line(dir_connection_t *conn, int status,
  3182. const char *reason_phrase)
  3183. {
  3184. char buf[256];
  3185. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  3186. status, reason_phrase ? reason_phrase : "OK") < 0) {
  3187. log_warn(LD_BUG,"status line too long.");
  3188. return;
  3189. }
  3190. log_debug(LD_DIRSERV,"Wrote status 'HTTP/1.0 %d %s'", status, reason_phrase);
  3191. connection_write_to_buf(buf, strlen(buf), TO_CONN(conn));
  3192. }
  3193. /** Write the header for an HTTP/1.0 response onto <b>conn</b>-\>outbuf,
  3194. * with <b>type</b> as the Content-Type.
  3195. *
  3196. * If <b>length</b> is nonnegative, it is the Content-Length.
  3197. * If <b>encoding</b> is provided, it is the Content-Encoding.
  3198. * If <b>cache_lifetime</b> is greater than 0, the content may be cached for
  3199. * up to cache_lifetime seconds. Otherwise, the content may not be cached. */
  3200. static void
  3201. write_http_response_header_impl(dir_connection_t *conn, ssize_t length,
  3202. const char *type, const char *encoding,
  3203. const char *extra_headers,
  3204. long cache_lifetime)
  3205. {
  3206. char date[RFC1123_TIME_LEN+1];
  3207. char tmp[1024];
  3208. char *cp;
  3209. time_t now = time(NULL);
  3210. tor_assert(conn);
  3211. format_rfc1123_time(date, now);
  3212. cp = tmp;
  3213. tor_snprintf(cp, sizeof(tmp),
  3214. "HTTP/1.0 200 OK\r\nDate: %s\r\n",
  3215. date);
  3216. cp += strlen(tmp);
  3217. if (type) {
  3218. tor_snprintf(cp, sizeof(tmp)-(cp-tmp), "Content-Type: %s\r\n", type);
  3219. cp += strlen(cp);
  3220. }
  3221. if (!is_local_addr(&conn->base_.addr)) {
  3222. /* Don't report the source address for a nearby/private connection.
  3223. * Otherwise we tend to mis-report in cases where incoming ports are
  3224. * being forwarded to a Tor server running behind the firewall. */
  3225. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3226. X_ADDRESS_HEADER "%s\r\n", conn->base_.address);
  3227. cp += strlen(cp);
  3228. }
  3229. if (encoding) {
  3230. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3231. "Content-Encoding: %s\r\n", encoding);
  3232. cp += strlen(cp);
  3233. }
  3234. if (length >= 0) {
  3235. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3236. "Content-Length: %ld\r\n", (long)length);
  3237. cp += strlen(cp);
  3238. }
  3239. if (cache_lifetime > 0) {
  3240. char expbuf[RFC1123_TIME_LEN+1];
  3241. format_rfc1123_time(expbuf, (time_t)(now + cache_lifetime));
  3242. /* We could say 'Cache-control: max-age=%d' here if we start doing
  3243. * http/1.1 */
  3244. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3245. "Expires: %s\r\n", expbuf);
  3246. cp += strlen(cp);
  3247. } else if (cache_lifetime == 0) {
  3248. /* We could say 'Cache-control: no-cache' here if we start doing
  3249. * http/1.1 */
  3250. strlcpy(cp, "Pragma: no-cache\r\n", sizeof(tmp)-(cp-tmp));
  3251. cp += strlen(cp);
  3252. }
  3253. if (extra_headers) {
  3254. strlcpy(cp, extra_headers, sizeof(tmp)-(cp-tmp));
  3255. cp += strlen(cp);
  3256. }
  3257. if (sizeof(tmp)-(cp-tmp) > 3)
  3258. memcpy(cp, "\r\n", 3);
  3259. else
  3260. tor_assert(0);
  3261. connection_write_to_buf(tmp, strlen(tmp), TO_CONN(conn));
  3262. }
  3263. /** As write_http_response_header_impl, but sets encoding and content-typed
  3264. * based on whether the response will be <b>compressed</b> or not. */
  3265. static void
  3266. write_http_response_headers(dir_connection_t *conn, ssize_t length,
  3267. compress_method_t method,
  3268. const char *extra_headers, long cache_lifetime)
  3269. {
  3270. const char *methodname = compression_method_get_name(method);
  3271. const char *doctype;
  3272. if (method == NO_METHOD)
  3273. doctype = "text/plain";
  3274. else
  3275. doctype = "application/octet-stream";
  3276. write_http_response_header_impl(conn, length,
  3277. doctype,
  3278. methodname,
  3279. extra_headers,
  3280. cache_lifetime);
  3281. }
  3282. /** As write_http_response_headers, but assumes extra_headers is NULL */
  3283. static void
  3284. write_http_response_header(dir_connection_t *conn, ssize_t length,
  3285. compress_method_t method,
  3286. long cache_lifetime)
  3287. {
  3288. write_http_response_headers(conn, length, method, NULL, cache_lifetime);
  3289. }
  3290. /** Array of compression methods to use (if supported) for serving
  3291. * precompressed data, ordered from best to worst. */
  3292. static compress_method_t srv_meth_pref_precompressed[] = {
  3293. LZMA_METHOD,
  3294. ZSTD_METHOD,
  3295. ZLIB_METHOD,
  3296. GZIP_METHOD,
  3297. NO_METHOD
  3298. };
  3299. /** Array of compression methods to use (if supported) for serving
  3300. * streamed data, ordered from best to worst. */
  3301. static compress_method_t srv_meth_pref_streaming_compression[] = {
  3302. ZSTD_METHOD,
  3303. ZLIB_METHOD,
  3304. GZIP_METHOD,
  3305. NO_METHOD
  3306. };
  3307. /** Array of allowed compression methods to use (if supported) when receiving a
  3308. * response from a request that was required to be anonymous. */
  3309. static compress_method_t client_meth_allowed_anonymous_compression[] = {
  3310. ZLIB_METHOD,
  3311. GZIP_METHOD,
  3312. NO_METHOD
  3313. };
  3314. /** Parse the compression methods listed in an Accept-Encoding header <b>h</b>,
  3315. * and convert them to a bitfield where compression method x is supported if
  3316. * and only if 1 &lt;&lt; x is set in the bitfield. */
  3317. STATIC unsigned
  3318. parse_accept_encoding_header(const char *h)
  3319. {
  3320. unsigned result = (1u << NO_METHOD);
  3321. smartlist_t *methods = smartlist_new();
  3322. smartlist_split_string(methods, h, ",",
  3323. SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3324. SMARTLIST_FOREACH_BEGIN(methods, const char *, m) {
  3325. compress_method_t method = compression_method_get_by_name(m);
  3326. if (method != UNKNOWN_METHOD) {
  3327. tor_assert(((unsigned)method) < 8*sizeof(unsigned));
  3328. result |= (1u << method);
  3329. }
  3330. } SMARTLIST_FOREACH_END(m);
  3331. SMARTLIST_FOREACH_BEGIN(methods, char *, m) {
  3332. tor_free(m);
  3333. } SMARTLIST_FOREACH_END(m);
  3334. smartlist_free(methods);
  3335. return result;
  3336. }
  3337. /** Array of compression methods to use (if supported) for requesting
  3338. * compressed data, ordered from best to worst. */
  3339. static compress_method_t client_meth_pref[] = {
  3340. LZMA_METHOD,
  3341. ZSTD_METHOD,
  3342. ZLIB_METHOD,
  3343. GZIP_METHOD,
  3344. NO_METHOD
  3345. };
  3346. /** Return a newly allocated string containing a comma separated list of
  3347. * supported encodings. */
  3348. STATIC char *
  3349. accept_encoding_header(void)
  3350. {
  3351. smartlist_t *methods = smartlist_new();
  3352. char *header = NULL;
  3353. compress_method_t method;
  3354. unsigned i;
  3355. for (i = 0; i < ARRAY_LENGTH(client_meth_pref); ++i) {
  3356. method = client_meth_pref[i];
  3357. if (tor_compress_supports_method(method))
  3358. smartlist_add(methods, (char *)compression_method_get_name(method));
  3359. }
  3360. header = smartlist_join_strings(methods, ", ", 0, NULL);
  3361. smartlist_free(methods);
  3362. return header;
  3363. }
  3364. /** Decide whether a client would accept the consensus we have.
  3365. *
  3366. * Clients can say they only want a consensus if it's signed by more
  3367. * than half the authorities in a list. They pass this list in
  3368. * the url as "...consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>".
  3369. *
  3370. * <b>fpr</b> may be an abbreviated fingerprint, i.e. only a left substring
  3371. * of the full authority identity digest. (Only strings of even length,
  3372. * i.e. encodings of full bytes, are handled correctly. In the case
  3373. * of an odd number of hex digits the last one is silently ignored.)
  3374. *
  3375. * Returns 1 if more than half of the requested authorities signed the
  3376. * consensus, 0 otherwise.
  3377. */
  3378. int
  3379. client_likes_consensus(const struct consensus_cache_entry_t *ent,
  3380. const char *want_url)
  3381. {
  3382. smartlist_t *voters = smartlist_new();
  3383. int need_at_least;
  3384. int have = 0;
  3385. if (consensus_cache_entry_get_voter_id_digests(ent, voters) != 0) {
  3386. return 1; // We don't know the voters; assume the client won't mind. */
  3387. }
  3388. smartlist_t *want_authorities = smartlist_new();
  3389. dir_split_resource_into_fingerprints(want_url, want_authorities, NULL, 0);
  3390. need_at_least = smartlist_len(want_authorities)/2+1;
  3391. SMARTLIST_FOREACH_BEGIN(want_authorities, const char *, want_digest) {
  3392. SMARTLIST_FOREACH_BEGIN(voters, const char *, digest) {
  3393. if (!strcasecmpstart(digest, want_digest)) {
  3394. have++;
  3395. break;
  3396. };
  3397. } SMARTLIST_FOREACH_END(digest);
  3398. /* early exit, if we already have enough */
  3399. if (have >= need_at_least)
  3400. break;
  3401. } SMARTLIST_FOREACH_END(want_digest);
  3402. SMARTLIST_FOREACH(want_authorities, char *, d, tor_free(d));
  3403. smartlist_free(want_authorities);
  3404. SMARTLIST_FOREACH(voters, char *, cp, tor_free(cp));
  3405. smartlist_free(voters);
  3406. return (have >= need_at_least);
  3407. }
  3408. /** Return the compression level we should use for sending a compressed
  3409. * response of size <b>n_bytes</b>. */
  3410. STATIC compression_level_t
  3411. choose_compression_level(ssize_t n_bytes)
  3412. {
  3413. if (! have_been_under_memory_pressure()) {
  3414. return HIGH_COMPRESSION; /* we have plenty of RAM. */
  3415. } else if (n_bytes < 0) {
  3416. return HIGH_COMPRESSION; /* unknown; might be big. */
  3417. } else if (n_bytes < 1024) {
  3418. return LOW_COMPRESSION;
  3419. } else if (n_bytes < 2048) {
  3420. return MEDIUM_COMPRESSION;
  3421. } else {
  3422. return HIGH_COMPRESSION;
  3423. }
  3424. }
  3425. /** Information passed to handle a GET request. */
  3426. typedef struct get_handler_args_t {
  3427. /** Bitmask of compression methods that the client said (or implied) it
  3428. * supported. */
  3429. unsigned compression_supported;
  3430. /** If nonzero, the time included an if-modified-since header with this
  3431. * value. */
  3432. time_t if_modified_since;
  3433. /** String containing the requested URL or resource. */
  3434. const char *url;
  3435. /** String containing the HTTP headers */
  3436. const char *headers;
  3437. } get_handler_args_t;
  3438. /** Entry for handling an HTTP GET request.
  3439. *
  3440. * This entry matches a request if "string" is equal to the requested
  3441. * resource, or if "is_prefix" is true and "string" is a prefix of the
  3442. * requested resource.
  3443. *
  3444. * The 'handler' function is called to handle the request. It receives
  3445. * an arguments structure, and must return 0 on success or -1 if we should
  3446. * close the connection.
  3447. **/
  3448. typedef struct url_table_ent_s {
  3449. const char *string;
  3450. int is_prefix;
  3451. int (*handler)(dir_connection_t *conn, const get_handler_args_t *args);
  3452. } url_table_ent_t;
  3453. static int handle_get_frontpage(dir_connection_t *conn,
  3454. const get_handler_args_t *args);
  3455. static int handle_get_current_consensus(dir_connection_t *conn,
  3456. const get_handler_args_t *args);
  3457. static int handle_get_status_vote(dir_connection_t *conn,
  3458. const get_handler_args_t *args);
  3459. static int handle_get_microdesc(dir_connection_t *conn,
  3460. const get_handler_args_t *args);
  3461. static int handle_get_descriptor(dir_connection_t *conn,
  3462. const get_handler_args_t *args);
  3463. static int handle_get_keys(dir_connection_t *conn,
  3464. const get_handler_args_t *args);
  3465. static int handle_get_hs_descriptor_v2(dir_connection_t *conn,
  3466. const get_handler_args_t *args);
  3467. static int handle_get_robots(dir_connection_t *conn,
  3468. const get_handler_args_t *args);
  3469. static int handle_get_networkstatus_bridges(dir_connection_t *conn,
  3470. const get_handler_args_t *args);
  3471. /** Table for handling GET requests. */
  3472. static const url_table_ent_t url_table[] = {
  3473. { "/tor/", 0, handle_get_frontpage },
  3474. { "/tor/status-vote/current/consensus", 1, handle_get_current_consensus },
  3475. { "/tor/status-vote/current/", 1, handle_get_status_vote },
  3476. { "/tor/status-vote/next/", 1, handle_get_status_vote },
  3477. { "/tor/micro/d/", 1, handle_get_microdesc },
  3478. { "/tor/server/", 1, handle_get_descriptor },
  3479. { "/tor/extra/", 1, handle_get_descriptor },
  3480. { "/tor/keys/", 1, handle_get_keys },
  3481. { "/tor/rendezvous2/", 1, handle_get_hs_descriptor_v2 },
  3482. { "/tor/hs/3/", 1, handle_get_hs_descriptor_v3 },
  3483. { "/tor/robots.txt", 0, handle_get_robots },
  3484. { "/tor/networkstatus-bridges", 0, handle_get_networkstatus_bridges },
  3485. { NULL, 0, NULL },
  3486. };
  3487. /** Helper function: called when a dirserver gets a complete HTTP GET
  3488. * request. Look for a request for a directory or for a rendezvous
  3489. * service descriptor. On finding one, write a response into
  3490. * conn-\>outbuf. If the request is unrecognized, send a 404.
  3491. * Return 0 if we handled this successfully, or -1 if we need to close
  3492. * the connection. */
  3493. MOCK_IMPL(STATIC int,
  3494. directory_handle_command_get,(dir_connection_t *conn, const char *headers,
  3495. const char *req_body, size_t req_body_len))
  3496. {
  3497. char *url, *url_mem, *header;
  3498. time_t if_modified_since = 0;
  3499. int zlib_compressed_in_url;
  3500. size_t url_len;
  3501. unsigned compression_methods_supported;
  3502. /* We ignore the body of a GET request. */
  3503. (void)req_body;
  3504. (void)req_body_len;
  3505. log_debug(LD_DIRSERV,"Received GET command.");
  3506. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  3507. if (parse_http_url(headers, &url) < 0) {
  3508. write_http_status_line(conn, 400, "Bad request");
  3509. return 0;
  3510. }
  3511. if ((header = http_get_header(headers, "If-Modified-Since: "))) {
  3512. struct tm tm;
  3513. if (parse_http_time(header, &tm) == 0) {
  3514. if (tor_timegm(&tm, &if_modified_since)<0) {
  3515. if_modified_since = 0;
  3516. } else {
  3517. log_debug(LD_DIRSERV, "If-Modified-Since is '%s'.", escaped(header));
  3518. }
  3519. }
  3520. /* The correct behavior on a malformed If-Modified-Since header is to
  3521. * act as if no If-Modified-Since header had been given. */
  3522. tor_free(header);
  3523. }
  3524. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  3525. url_mem = url;
  3526. url_len = strlen(url);
  3527. zlib_compressed_in_url = url_len > 2 && !strcmp(url+url_len-2, ".z");
  3528. if (zlib_compressed_in_url) {
  3529. url[url_len-2] = '\0';
  3530. url_len -= 2;
  3531. }
  3532. if ((header = http_get_header(headers, "Accept-Encoding: "))) {
  3533. compression_methods_supported = parse_accept_encoding_header(header);
  3534. tor_free(header);
  3535. } else {
  3536. compression_methods_supported = (1u << NO_METHOD);
  3537. }
  3538. if (zlib_compressed_in_url) {
  3539. compression_methods_supported |= (1u << ZLIB_METHOD);
  3540. }
  3541. /* Remove all methods that we don't both support. */
  3542. compression_methods_supported &= tor_compress_get_supported_method_bitmask();
  3543. get_handler_args_t args;
  3544. args.url = url;
  3545. args.headers = headers;
  3546. args.if_modified_since = if_modified_since;
  3547. args.compression_supported = compression_methods_supported;
  3548. int i, result = -1;
  3549. for (i = 0; url_table[i].string; ++i) {
  3550. int match;
  3551. if (url_table[i].is_prefix) {
  3552. match = !strcmpstart(url, url_table[i].string);
  3553. } else {
  3554. match = !strcmp(url, url_table[i].string);
  3555. }
  3556. if (match) {
  3557. result = url_table[i].handler(conn, &args);
  3558. goto done;
  3559. }
  3560. }
  3561. /* we didn't recognize the url */
  3562. write_http_status_line(conn, 404, "Not found");
  3563. result = 0;
  3564. done:
  3565. tor_free(url_mem);
  3566. return result;
  3567. }
  3568. /** Helper function for GET / or GET /tor/
  3569. */
  3570. static int
  3571. handle_get_frontpage(dir_connection_t *conn, const get_handler_args_t *args)
  3572. {
  3573. (void) args; /* unused */
  3574. const char *frontpage = get_dirportfrontpage();
  3575. if (frontpage) {
  3576. size_t dlen;
  3577. dlen = strlen(frontpage);
  3578. /* Let's return a disclaimer page (users shouldn't use V1 anymore,
  3579. and caches don't fetch '/', so this is safe). */
  3580. /* [We don't check for write_bucket_low here, since we want to serve
  3581. * this page no matter what.] */
  3582. write_http_response_header_impl(conn, dlen, "text/html", "identity",
  3583. NULL, DIRPORTFRONTPAGE_CACHE_LIFETIME);
  3584. connection_write_to_buf(frontpage, dlen, TO_CONN(conn));
  3585. } else {
  3586. write_http_status_line(conn, 404, "Not found");
  3587. }
  3588. return 0;
  3589. }
  3590. /** Warn that the cached consensus <b>consensus</b> of type
  3591. * <b>flavor</b> is too old and will not be served to clients. Rate-limit the
  3592. * warning to avoid logging an entry on every request.
  3593. */
  3594. static void
  3595. warn_consensus_is_too_old(const struct consensus_cache_entry_t *consensus,
  3596. const char *flavor, time_t now)
  3597. {
  3598. #define TOO_OLD_WARNING_INTERVAL (60*60)
  3599. static ratelim_t warned = RATELIM_INIT(TOO_OLD_WARNING_INTERVAL);
  3600. char timestamp[ISO_TIME_LEN+1];
  3601. time_t valid_until;
  3602. char *dupes;
  3603. if (consensus_cache_entry_get_valid_until(consensus, &valid_until))
  3604. return;
  3605. if ((dupes = rate_limit_log(&warned, now))) {
  3606. format_local_iso_time(timestamp, valid_until);
  3607. log_warn(LD_DIRSERV, "Our %s%sconsensus is too old, so we will not "
  3608. "serve it to clients. It was valid until %s local time and we "
  3609. "continued to serve it for up to 24 hours after it expired.%s",
  3610. flavor ? flavor : "", flavor ? " " : "", timestamp, dupes);
  3611. tor_free(dupes);
  3612. }
  3613. }
  3614. /**
  3615. * Parse a single hex-encoded sha3-256 digest from <b>hex</b> into
  3616. * <b>digest</b>. Return 0 on success. On failure, report that the hash came
  3617. * from <b>location</b>, report that we are taking <b>action</b> with it, and
  3618. * return -1.
  3619. */
  3620. static int
  3621. parse_one_diff_hash(uint8_t *digest, const char *hex, const char *location,
  3622. const char *action)
  3623. {
  3624. if (base16_decode((char*)digest, DIGEST256_LEN, hex, strlen(hex)) ==
  3625. DIGEST256_LEN) {
  3626. return 0;
  3627. } else {
  3628. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  3629. "%s contained bogus digest %s; %s.",
  3630. location, escaped(hex), action);
  3631. return -1;
  3632. }
  3633. }
  3634. /** If there is an X-Or-Diff-From-Consensus header included in <b>headers</b>,
  3635. * set <b>digest_out<b> to a new smartlist containing every 256-bit
  3636. * hex-encoded digest listed in that header and return 0. Otherwise return
  3637. * -1. */
  3638. static int
  3639. parse_or_diff_from_header(smartlist_t **digests_out, const char *headers)
  3640. {
  3641. char *hdr = http_get_header(headers, X_OR_DIFF_FROM_CONSENSUS_HEADER);
  3642. if (hdr == NULL) {
  3643. return -1;
  3644. }
  3645. smartlist_t *hex_digests = smartlist_new();
  3646. *digests_out = smartlist_new();
  3647. smartlist_split_string(hex_digests, hdr, " ",
  3648. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3649. SMARTLIST_FOREACH_BEGIN(hex_digests, const char *, hex) {
  3650. uint8_t digest[DIGEST256_LEN];
  3651. if (!parse_one_diff_hash(digest, hex, "X-Or-Diff-From-Consensus header",
  3652. "ignoring")) {
  3653. smartlist_add(*digests_out, tor_memdup(digest, sizeof(digest)));
  3654. }
  3655. } SMARTLIST_FOREACH_END(hex);
  3656. SMARTLIST_FOREACH(hex_digests, char *, cp, tor_free(cp));
  3657. smartlist_free(hex_digests);
  3658. tor_free(hdr);
  3659. return 0;
  3660. }
  3661. /** Fallback compression method. The fallback compression method is used in
  3662. * case a client requests a non-compressed document. We only store compressed
  3663. * documents, so we use this compression method to fetch the document and let
  3664. * the spooling system do the streaming decompression.
  3665. */
  3666. #define FALLBACK_COMPRESS_METHOD ZLIB_METHOD
  3667. /**
  3668. * Try to find the best consensus diff possible in order to serve a client
  3669. * request for a diff from one of the consensuses in <b>digests</b> to the
  3670. * current consensus of flavor <b>flav</b>. The client supports the
  3671. * compression methods listed in the <b>compression_methods</b> bitfield:
  3672. * place the method chosen (if any) into <b>compression_used_out</b>.
  3673. */
  3674. static struct consensus_cache_entry_t *
  3675. find_best_diff(const smartlist_t *digests, int flav,
  3676. unsigned compression_methods,
  3677. compress_method_t *compression_used_out)
  3678. {
  3679. struct consensus_cache_entry_t *result = NULL;
  3680. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, diff_from) {
  3681. unsigned u;
  3682. for (u = 0; u < ARRAY_LENGTH(srv_meth_pref_precompressed); ++u) {
  3683. compress_method_t method = srv_meth_pref_precompressed[u];
  3684. if (0 == (compression_methods & (1u<<method)))
  3685. continue; // client doesn't like this one, or we don't have it.
  3686. if (consdiffmgr_find_diff_from(&result, flav, DIGEST_SHA3_256,
  3687. diff_from, DIGEST256_LEN,
  3688. method) == CONSDIFF_AVAILABLE) {
  3689. tor_assert_nonfatal(result);
  3690. *compression_used_out = method;
  3691. return result;
  3692. }
  3693. }
  3694. } SMARTLIST_FOREACH_END(diff_from);
  3695. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, diff_from) {
  3696. if (consdiffmgr_find_diff_from(&result, flav, DIGEST_SHA3_256, diff_from,
  3697. DIGEST256_LEN, FALLBACK_COMPRESS_METHOD) == CONSDIFF_AVAILABLE) {
  3698. tor_assert_nonfatal(result);
  3699. *compression_used_out = FALLBACK_COMPRESS_METHOD;
  3700. return result;
  3701. }
  3702. } SMARTLIST_FOREACH_END(diff_from);
  3703. return NULL;
  3704. }
  3705. /** Lookup the cached consensus document by the flavor found in <b>flav</b>.
  3706. * The prefered set of compression methods should be listed in the
  3707. * <b>compression_methods</b> bitfield. The compression method chosen (if any)
  3708. * is stored in <b>compression_used_out</b>. */
  3709. static struct consensus_cache_entry_t *
  3710. find_best_consensus(int flav,
  3711. unsigned compression_methods,
  3712. compress_method_t *compression_used_out)
  3713. {
  3714. struct consensus_cache_entry_t *result = NULL;
  3715. unsigned u;
  3716. for (u = 0; u < ARRAY_LENGTH(srv_meth_pref_precompressed); ++u) {
  3717. compress_method_t method = srv_meth_pref_precompressed[u];
  3718. if (0 == (compression_methods & (1u<<method)))
  3719. continue;
  3720. if (consdiffmgr_find_consensus(&result, flav,
  3721. method) == CONSDIFF_AVAILABLE) {
  3722. tor_assert_nonfatal(result);
  3723. *compression_used_out = method;
  3724. return result;
  3725. }
  3726. }
  3727. if (consdiffmgr_find_consensus(&result, flav,
  3728. FALLBACK_COMPRESS_METHOD) == CONSDIFF_AVAILABLE) {
  3729. tor_assert_nonfatal(result);
  3730. *compression_used_out = FALLBACK_COMPRESS_METHOD;
  3731. return result;
  3732. }
  3733. return NULL;
  3734. }
  3735. /** Try to find the best supported compression method possible from a given
  3736. * <b>compression_methods</b>. Return NO_METHOD if no mutually supported
  3737. * compression method could be found. */
  3738. static compress_method_t
  3739. find_best_compression_method(unsigned compression_methods, int stream)
  3740. {
  3741. unsigned u;
  3742. compress_method_t *methods;
  3743. size_t length;
  3744. if (stream) {
  3745. methods = srv_meth_pref_streaming_compression;
  3746. length = ARRAY_LENGTH(srv_meth_pref_streaming_compression);
  3747. } else {
  3748. methods = srv_meth_pref_precompressed;
  3749. length = ARRAY_LENGTH(srv_meth_pref_precompressed);
  3750. }
  3751. for (u = 0; u < length; ++u) {
  3752. compress_method_t method = methods[u];
  3753. if (compression_methods & (1u<<method))
  3754. return method;
  3755. }
  3756. return NO_METHOD;
  3757. }
  3758. /** Check if any of the digests in <b>digests</b> matches the latest consensus
  3759. * flavor (given in <b>flavor</b>) that we have available. */
  3760. static int
  3761. digest_list_contains_best_consensus(consensus_flavor_t flavor,
  3762. const smartlist_t *digests)
  3763. {
  3764. const networkstatus_t *ns = NULL;
  3765. if (digests == NULL)
  3766. return 0;
  3767. ns = networkstatus_get_latest_consensus_by_flavor(flavor);
  3768. if (ns == NULL)
  3769. return 0;
  3770. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, digest) {
  3771. if (tor_memeq(ns->digest_sha3_as_signed, digest, DIGEST256_LEN))
  3772. return 1;
  3773. } SMARTLIST_FOREACH_END(digest);
  3774. return 0;
  3775. }
  3776. /** Check if the given compression method is allowed for a connection that is
  3777. * supposed to be anonymous. Returns 1 if the compression method is allowed,
  3778. * otherwise 0. */
  3779. STATIC int
  3780. allowed_anonymous_connection_compression_method(compress_method_t method)
  3781. {
  3782. unsigned u;
  3783. for (u = 0; u < ARRAY_LENGTH(client_meth_allowed_anonymous_compression);
  3784. ++u) {
  3785. compress_method_t allowed_method =
  3786. client_meth_allowed_anonymous_compression[u];
  3787. if (! tor_compress_supports_method(allowed_method))
  3788. continue;
  3789. if (method == allowed_method)
  3790. return 1;
  3791. }
  3792. return 0;
  3793. }
  3794. /** Log a warning when a remote server has sent us a document using a
  3795. * compression method that is not allowed for anonymous directory requests. */
  3796. STATIC void
  3797. warn_disallowed_anonymous_compression_method(compress_method_t method)
  3798. {
  3799. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  3800. "Received a %s HTTP response, which is not "
  3801. "allowed for anonymous directory requests.",
  3802. compression_method_get_human_name(method));
  3803. }
  3804. /** Encodes the results of parsing a consensus request to figure out what
  3805. * consensus, and possibly what diffs, the user asked for. */
  3806. typedef struct {
  3807. /** name of the flavor to retrieve. */
  3808. char *flavor;
  3809. /** flavor to retrive, as enum. */
  3810. consensus_flavor_t flav;
  3811. /** plus-separated list of authority fingerprints; see
  3812. * client_likes_consensus(). Aliases the URL in the request passed to
  3813. * parse_consensus_request(). */
  3814. const char *want_fps;
  3815. /** Optionally, a smartlist of sha3 digests-as-signed of the consensuses
  3816. * to return a diff from. */
  3817. smartlist_t *diff_from_digests;
  3818. /** If true, never send a full consensus. If there is no diff, send
  3819. * a 404 instead. */
  3820. int diff_only;
  3821. } parsed_consensus_request_t;
  3822. /** Remove all data held in <b>req</b>. Do not free <b>req</b> itself, since
  3823. * it is stack-allocated. */
  3824. static void
  3825. parsed_consensus_request_clear(parsed_consensus_request_t *req)
  3826. {
  3827. if (!req)
  3828. return;
  3829. tor_free(req->flavor);
  3830. if (req->diff_from_digests) {
  3831. SMARTLIST_FOREACH(req->diff_from_digests, uint8_t *, d, tor_free(d));
  3832. smartlist_free(req->diff_from_digests);
  3833. }
  3834. memset(req, 0, sizeof(parsed_consensus_request_t));
  3835. }
  3836. /**
  3837. * Parse the URL and relevant headers of <b>args</b> for a current-consensus
  3838. * request to learn what flavor of consensus we want, what keys it must be
  3839. * signed with, and what diffs we would accept (or demand) instead. Return 0
  3840. * on success and -1 on failure.
  3841. */
  3842. static int
  3843. parse_consensus_request(parsed_consensus_request_t *out,
  3844. const get_handler_args_t *args)
  3845. {
  3846. const char *url = args->url;
  3847. memset(out, 0, sizeof(parsed_consensus_request_t));
  3848. out->flav = FLAV_NS;
  3849. const char CONSENSUS_URL_PREFIX[] = "/tor/status-vote/current/consensus/";
  3850. const char CONSENSUS_FLAVORED_PREFIX[] =
  3851. "/tor/status-vote/current/consensus-";
  3852. /* figure out the flavor if any, and who we wanted to sign the thing */
  3853. const char *after_flavor = NULL;
  3854. if (!strcmpstart(url, CONSENSUS_FLAVORED_PREFIX)) {
  3855. const char *f, *cp;
  3856. f = url + strlen(CONSENSUS_FLAVORED_PREFIX);
  3857. cp = strchr(f, '/');
  3858. if (cp) {
  3859. after_flavor = cp+1;
  3860. out->flavor = tor_strndup(f, cp-f);
  3861. } else {
  3862. out->flavor = tor_strdup(f);
  3863. }
  3864. int flav = networkstatus_parse_flavor_name(out->flavor);
  3865. if (flav < 0)
  3866. flav = FLAV_NS;
  3867. out->flav = flav;
  3868. } else {
  3869. if (!strcmpstart(url, CONSENSUS_URL_PREFIX))
  3870. after_flavor = url+strlen(CONSENSUS_URL_PREFIX);
  3871. }
  3872. /* see whether we've been asked explicitly for a diff from an older
  3873. * consensus. (The user might also have said that a diff would be okay,
  3874. * via X-Or-Diff-From-Consensus */
  3875. const char DIFF_COMPONENT[] = "diff/";
  3876. char *diff_hash_in_url = NULL;
  3877. if (after_flavor && !strcmpstart(after_flavor, DIFF_COMPONENT)) {
  3878. after_flavor += strlen(DIFF_COMPONENT);
  3879. const char *cp = strchr(after_flavor, '/');
  3880. if (cp) {
  3881. diff_hash_in_url = tor_strndup(after_flavor, cp-after_flavor);
  3882. out->want_fps = cp+1;
  3883. } else {
  3884. diff_hash_in_url = tor_strdup(after_flavor);
  3885. out->want_fps = NULL;
  3886. }
  3887. } else {
  3888. out->want_fps = after_flavor;
  3889. }
  3890. if (diff_hash_in_url) {
  3891. uint8_t diff_from[DIGEST256_LEN];
  3892. out->diff_from_digests = smartlist_new();
  3893. out->diff_only = 1;
  3894. int ok = !parse_one_diff_hash(diff_from, diff_hash_in_url, "URL",
  3895. "rejecting");
  3896. tor_free(diff_hash_in_url);
  3897. if (ok) {
  3898. smartlist_add(out->diff_from_digests,
  3899. tor_memdup(diff_from, DIGEST256_LEN));
  3900. } else {
  3901. return -1;
  3902. }
  3903. } else {
  3904. parse_or_diff_from_header(&out->diff_from_digests, args->headers);
  3905. }
  3906. return 0;
  3907. }
  3908. /** Helper function for GET /tor/status-vote/current/consensus
  3909. */
  3910. static int
  3911. handle_get_current_consensus(dir_connection_t *conn,
  3912. const get_handler_args_t *args)
  3913. {
  3914. const compress_method_t compress_method =
  3915. find_best_compression_method(args->compression_supported, 0);
  3916. const time_t if_modified_since = args->if_modified_since;
  3917. int clear_spool = 0;
  3918. /* v3 network status fetch. */
  3919. long lifetime = NETWORKSTATUS_CACHE_LIFETIME;
  3920. time_t now = time(NULL);
  3921. parsed_consensus_request_t req;
  3922. if (parse_consensus_request(&req, args) < 0) {
  3923. write_http_status_line(conn, 404, "Couldn't parse request");
  3924. goto done;
  3925. }
  3926. if (digest_list_contains_best_consensus(req.flav,
  3927. req.diff_from_digests)) {
  3928. write_http_status_line(conn, 304, "Not modified");
  3929. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  3930. goto done;
  3931. }
  3932. struct consensus_cache_entry_t *cached_consensus = NULL;
  3933. compress_method_t compression_used = NO_METHOD;
  3934. if (req.diff_from_digests) {
  3935. cached_consensus = find_best_diff(req.diff_from_digests, req.flav,
  3936. args->compression_supported,
  3937. &compression_used);
  3938. }
  3939. if (req.diff_only && !cached_consensus) {
  3940. write_http_status_line(conn, 404, "No such diff available");
  3941. // XXXX warn_consensus_is_too_old(v, req.flavor, now);
  3942. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  3943. goto done;
  3944. }
  3945. if (! cached_consensus) {
  3946. cached_consensus = find_best_consensus(req.flav,
  3947. args->compression_supported,
  3948. &compression_used);
  3949. }
  3950. time_t fresh_until, valid_until;
  3951. int have_fresh_until = 0, have_valid_until = 0;
  3952. if (cached_consensus) {
  3953. have_fresh_until =
  3954. !consensus_cache_entry_get_fresh_until(cached_consensus, &fresh_until);
  3955. have_valid_until =
  3956. !consensus_cache_entry_get_valid_until(cached_consensus, &valid_until);
  3957. }
  3958. if (cached_consensus && have_valid_until &&
  3959. !networkstatus_valid_until_is_reasonably_live(valid_until, now)) {
  3960. write_http_status_line(conn, 404, "Consensus is too old");
  3961. warn_consensus_is_too_old(cached_consensus, req.flavor, now);
  3962. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  3963. goto done;
  3964. }
  3965. if (cached_consensus && req.want_fps &&
  3966. !client_likes_consensus(cached_consensus, req.want_fps)) {
  3967. write_http_status_line(conn, 404, "Consensus not signed by sufficient "
  3968. "number of requested authorities");
  3969. geoip_note_ns_response(GEOIP_REJECT_NOT_ENOUGH_SIGS);
  3970. goto done;
  3971. }
  3972. conn->spool = smartlist_new();
  3973. clear_spool = 1;
  3974. {
  3975. spooled_resource_t *spooled;
  3976. if (cached_consensus) {
  3977. spooled = spooled_resource_new_from_cache_entry(cached_consensus);
  3978. smartlist_add(conn->spool, spooled);
  3979. }
  3980. }
  3981. lifetime = (have_fresh_until && fresh_until > now) ? fresh_until - now : 0;
  3982. size_t size_guess = 0;
  3983. int n_expired = 0;
  3984. dirserv_spool_remove_missing_and_guess_size(conn, if_modified_since,
  3985. compress_method != NO_METHOD,
  3986. &size_guess,
  3987. &n_expired);
  3988. if (!smartlist_len(conn->spool) && !n_expired) {
  3989. write_http_status_line(conn, 404, "Not found");
  3990. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  3991. goto done;
  3992. } else if (!smartlist_len(conn->spool)) {
  3993. write_http_status_line(conn, 304, "Not modified");
  3994. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  3995. goto done;
  3996. }
  3997. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  3998. log_debug(LD_DIRSERV,
  3999. "Client asked for network status lists, but we've been "
  4000. "writing too many bytes lately. Sending 503 Dir busy.");
  4001. write_http_status_line(conn, 503, "Directory busy, try again later");
  4002. geoip_note_ns_response(GEOIP_REJECT_BUSY);
  4003. goto done;
  4004. }
  4005. tor_addr_t addr;
  4006. if (tor_addr_parse(&addr, (TO_CONN(conn))->address) >= 0) {
  4007. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS,
  4008. &addr, NULL,
  4009. time(NULL));
  4010. geoip_note_ns_response(GEOIP_SUCCESS);
  4011. /* Note that a request for a network status has started, so that we
  4012. * can measure the download time later on. */
  4013. if (conn->dirreq_id)
  4014. geoip_start_dirreq(conn->dirreq_id, size_guess, DIRREQ_TUNNELED);
  4015. else
  4016. geoip_start_dirreq(TO_CONN(conn)->global_identifier, size_guess,
  4017. DIRREQ_DIRECT);
  4018. }
  4019. /* Use this header to tell caches that the response depends on the
  4020. * X-Or-Diff-From-Consensus header (or lack thereof). */
  4021. const char vary_header[] = "Vary: X-Or-Diff-From-Consensus\r\n";
  4022. clear_spool = 0;
  4023. // The compress_method might have been NO_METHOD, but we store the data
  4024. // compressed. Decompress them using `compression_used`. See fallback code in
  4025. // find_best_consensus() and find_best_diff().
  4026. write_http_response_headers(conn, -1,
  4027. compress_method == NO_METHOD ?
  4028. NO_METHOD : compression_used,
  4029. vary_header,
  4030. smartlist_len(conn->spool) == 1 ? lifetime : 0);
  4031. if (compress_method == NO_METHOD && smartlist_len(conn->spool))
  4032. conn->compress_state = tor_compress_new(0, compression_used,
  4033. HIGH_COMPRESSION);
  4034. /* Prime the connection with some data. */
  4035. const int initial_flush_result = connection_dirserv_flushed_some(conn);
  4036. tor_assert_nonfatal(initial_flush_result == 0);
  4037. goto done;
  4038. done:
  4039. parsed_consensus_request_clear(&req);
  4040. if (clear_spool) {
  4041. dir_conn_clear_spool(conn);
  4042. }
  4043. return 0;
  4044. }
  4045. /** Helper function for GET /tor/status-vote/{current,next}/...
  4046. */
  4047. static int
  4048. handle_get_status_vote(dir_connection_t *conn, const get_handler_args_t *args)
  4049. {
  4050. const char *url = args->url;
  4051. {
  4052. int current;
  4053. ssize_t body_len = 0;
  4054. ssize_t estimated_len = 0;
  4055. /* This smartlist holds strings that we can compress on the fly. */
  4056. smartlist_t *items = smartlist_new();
  4057. /* This smartlist holds cached_dir_t objects that have a precompressed
  4058. * deflated version. */
  4059. smartlist_t *dir_items = smartlist_new();
  4060. int lifetime = 60; /* XXXX?? should actually use vote intervals. */
  4061. url += strlen("/tor/status-vote/");
  4062. current = !strcmpstart(url, "current/");
  4063. url = strchr(url, '/');
  4064. tor_assert(url);
  4065. ++url;
  4066. if (!strcmp(url, "consensus")) {
  4067. const char *item;
  4068. tor_assert(!current); /* we handle current consensus specially above,
  4069. * since it wants to be spooled. */
  4070. if ((item = dirvote_get_pending_consensus(FLAV_NS)))
  4071. smartlist_add(items, (char*)item);
  4072. } else if (!current && !strcmp(url, "consensus-signatures")) {
  4073. /* XXXX the spec says that we should implement
  4074. * current/consensus-signatures too. It doesn't seem to be needed,
  4075. * though. */
  4076. const char *item;
  4077. if ((item=dirvote_get_pending_detached_signatures()))
  4078. smartlist_add(items, (char*)item);
  4079. } else if (!strcmp(url, "authority")) {
  4080. const cached_dir_t *d;
  4081. int flags = DGV_BY_ID |
  4082. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  4083. if ((d=dirvote_get_vote(NULL, flags)))
  4084. smartlist_add(dir_items, (cached_dir_t*)d);
  4085. } else {
  4086. const cached_dir_t *d;
  4087. smartlist_t *fps = smartlist_new();
  4088. int flags;
  4089. if (!strcmpstart(url, "d/")) {
  4090. url += 2;
  4091. flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
  4092. } else {
  4093. flags = DGV_BY_ID |
  4094. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  4095. }
  4096. dir_split_resource_into_fingerprints(url, fps, NULL,
  4097. DSR_HEX|DSR_SORT_UNIQ);
  4098. SMARTLIST_FOREACH(fps, char *, fp, {
  4099. if ((d = dirvote_get_vote(fp, flags)))
  4100. smartlist_add(dir_items, (cached_dir_t*)d);
  4101. tor_free(fp);
  4102. });
  4103. smartlist_free(fps);
  4104. }
  4105. if (!smartlist_len(dir_items) && !smartlist_len(items)) {
  4106. write_http_status_line(conn, 404, "Not found");
  4107. goto vote_done;
  4108. }
  4109. /* We're sending items from at most one kind of source */
  4110. tor_assert_nonfatal(smartlist_len(items) == 0 ||
  4111. smartlist_len(dir_items) == 0);
  4112. int streaming;
  4113. unsigned mask;
  4114. if (smartlist_len(items)) {
  4115. /* We're taking strings and compressing them on the fly. */
  4116. streaming = 1;
  4117. mask = ~0u;
  4118. } else {
  4119. /* We're taking cached_dir_t objects. We only have them uncompressed
  4120. * or deflated. */
  4121. streaming = 0;
  4122. mask = (1u<<NO_METHOD) | (1u<<ZLIB_METHOD);
  4123. }
  4124. const compress_method_t compress_method = find_best_compression_method(
  4125. args->compression_supported&mask, streaming);
  4126. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  4127. body_len += compress_method != NO_METHOD ?
  4128. d->dir_compressed_len : d->dir_len);
  4129. estimated_len += body_len;
  4130. SMARTLIST_FOREACH(items, const char *, item, {
  4131. size_t ln = strlen(item);
  4132. if (compress_method != NO_METHOD) {
  4133. estimated_len += ln/2;
  4134. } else {
  4135. body_len += ln; estimated_len += ln;
  4136. }
  4137. });
  4138. if (global_write_bucket_low(TO_CONN(conn), estimated_len, 2)) {
  4139. write_http_status_line(conn, 503, "Directory busy, try again later");
  4140. goto vote_done;
  4141. }
  4142. write_http_response_header(conn, body_len ? body_len : -1,
  4143. compress_method,
  4144. lifetime);
  4145. if (smartlist_len(items)) {
  4146. if (compress_method != NO_METHOD) {
  4147. conn->compress_state = tor_compress_new(1, compress_method,
  4148. choose_compression_level(estimated_len));
  4149. SMARTLIST_FOREACH(items, const char *, c,
  4150. connection_write_to_buf_compress(c, strlen(c), conn, 0));
  4151. connection_write_to_buf_compress("", 0, conn, 1);
  4152. } else {
  4153. SMARTLIST_FOREACH(items, const char *, c,
  4154. connection_write_to_buf(c, strlen(c), TO_CONN(conn)));
  4155. }
  4156. } else {
  4157. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  4158. connection_write_to_buf(compress_method != NO_METHOD ?
  4159. d->dir_compressed : d->dir,
  4160. compress_method != NO_METHOD ?
  4161. d->dir_compressed_len : d->dir_len,
  4162. TO_CONN(conn)));
  4163. }
  4164. vote_done:
  4165. smartlist_free(items);
  4166. smartlist_free(dir_items);
  4167. goto done;
  4168. }
  4169. done:
  4170. return 0;
  4171. }
  4172. /** Helper function for GET /tor/micro/d/...
  4173. */
  4174. static int
  4175. handle_get_microdesc(dir_connection_t *conn, const get_handler_args_t *args)
  4176. {
  4177. const char *url = args->url;
  4178. const compress_method_t compress_method =
  4179. find_best_compression_method(args->compression_supported, 1);
  4180. int clear_spool = 1;
  4181. {
  4182. conn->spool = smartlist_new();
  4183. dir_split_resource_into_spoolable(url+strlen("/tor/micro/d/"),
  4184. DIR_SPOOL_MICRODESC,
  4185. conn->spool, NULL,
  4186. DSR_DIGEST256|DSR_BASE64|DSR_SORT_UNIQ);
  4187. size_t size_guess = 0;
  4188. dirserv_spool_remove_missing_and_guess_size(conn, 0,
  4189. compress_method != NO_METHOD,
  4190. &size_guess, NULL);
  4191. if (smartlist_len(conn->spool) == 0) {
  4192. write_http_status_line(conn, 404, "Not found");
  4193. goto done;
  4194. }
  4195. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  4196. log_info(LD_DIRSERV,
  4197. "Client asked for server descriptors, but we've been "
  4198. "writing too many bytes lately. Sending 503 Dir busy.");
  4199. write_http_status_line(conn, 503, "Directory busy, try again later");
  4200. goto done;
  4201. }
  4202. clear_spool = 0;
  4203. write_http_response_header(conn, -1,
  4204. compress_method,
  4205. MICRODESC_CACHE_LIFETIME);
  4206. if (compress_method != NO_METHOD)
  4207. conn->compress_state = tor_compress_new(1, compress_method,
  4208. choose_compression_level(size_guess));
  4209. const int initial_flush_result = connection_dirserv_flushed_some(conn);
  4210. tor_assert_nonfatal(initial_flush_result == 0);
  4211. goto done;
  4212. }
  4213. done:
  4214. if (clear_spool) {
  4215. dir_conn_clear_spool(conn);
  4216. }
  4217. return 0;
  4218. }
  4219. /** Helper function for GET /tor/{server,extra}/...
  4220. */
  4221. static int
  4222. handle_get_descriptor(dir_connection_t *conn, const get_handler_args_t *args)
  4223. {
  4224. const char *url = args->url;
  4225. const compress_method_t compress_method =
  4226. find_best_compression_method(args->compression_supported, 1);
  4227. const or_options_t *options = get_options();
  4228. int clear_spool = 1;
  4229. if (!strcmpstart(url,"/tor/server/") ||
  4230. (!options->BridgeAuthoritativeDir &&
  4231. !options->BridgeRelay && !strcmpstart(url,"/tor/extra/"))) {
  4232. int res;
  4233. const char *msg = NULL;
  4234. int cache_lifetime = 0;
  4235. int is_extra = !strcmpstart(url,"/tor/extra/");
  4236. url += is_extra ? strlen("/tor/extra/") : strlen("/tor/server/");
  4237. dir_spool_source_t source;
  4238. time_t publish_cutoff = 0;
  4239. if (!strcmpstart(url, "d/")) {
  4240. source =
  4241. is_extra ? DIR_SPOOL_EXTRA_BY_DIGEST : DIR_SPOOL_SERVER_BY_DIGEST;
  4242. } else {
  4243. source =
  4244. is_extra ? DIR_SPOOL_EXTRA_BY_FP : DIR_SPOOL_SERVER_BY_FP;
  4245. /* We only want to apply a publish cutoff when we're requesting
  4246. * resources by fingerprint. */
  4247. publish_cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
  4248. }
  4249. conn->spool = smartlist_new();
  4250. res = dirserv_get_routerdesc_spool(conn->spool, url,
  4251. source,
  4252. connection_dir_is_encrypted(conn),
  4253. &msg);
  4254. if (!strcmpstart(url, "all")) {
  4255. cache_lifetime = FULL_DIR_CACHE_LIFETIME;
  4256. } else if (smartlist_len(conn->spool) == 1) {
  4257. cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
  4258. }
  4259. size_t size_guess = 0;
  4260. int n_expired = 0;
  4261. dirserv_spool_remove_missing_and_guess_size(conn, publish_cutoff,
  4262. compress_method != NO_METHOD,
  4263. &size_guess, &n_expired);
  4264. /* If we are the bridge authority and the descriptor is a bridge
  4265. * descriptor, remember that we served this descriptor for desc stats. */
  4266. /* XXXX it's a bit of a kludge to have this here. */
  4267. if (get_options()->BridgeAuthoritativeDir &&
  4268. source == DIR_SPOOL_SERVER_BY_FP) {
  4269. SMARTLIST_FOREACH_BEGIN(conn->spool, spooled_resource_t *, spooled) {
  4270. const routerinfo_t *router =
  4271. router_get_by_id_digest((const char *)spooled->digest);
  4272. /* router can be NULL here when the bridge auth is asked for its own
  4273. * descriptor. */
  4274. if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
  4275. rep_hist_note_desc_served(router->cache_info.identity_digest);
  4276. } SMARTLIST_FOREACH_END(spooled);
  4277. }
  4278. if (res < 0 || size_guess == 0 || smartlist_len(conn->spool) == 0) {
  4279. if (msg == NULL)
  4280. msg = "Not found";
  4281. write_http_status_line(conn, 404, msg);
  4282. } else {
  4283. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  4284. log_info(LD_DIRSERV,
  4285. "Client asked for server descriptors, but we've been "
  4286. "writing too many bytes lately. Sending 503 Dir busy.");
  4287. write_http_status_line(conn, 503, "Directory busy, try again later");
  4288. dir_conn_clear_spool(conn);
  4289. goto done;
  4290. }
  4291. write_http_response_header(conn, -1, compress_method, cache_lifetime);
  4292. if (compress_method != NO_METHOD)
  4293. conn->compress_state = tor_compress_new(1, compress_method,
  4294. choose_compression_level(size_guess));
  4295. clear_spool = 0;
  4296. /* Prime the connection with some data. */
  4297. int initial_flush_result = connection_dirserv_flushed_some(conn);
  4298. tor_assert_nonfatal(initial_flush_result == 0);
  4299. }
  4300. goto done;
  4301. }
  4302. done:
  4303. if (clear_spool)
  4304. dir_conn_clear_spool(conn);
  4305. return 0;
  4306. }
  4307. /** Helper function for GET /tor/keys/...
  4308. */
  4309. static int
  4310. handle_get_keys(dir_connection_t *conn, const get_handler_args_t *args)
  4311. {
  4312. const char *url = args->url;
  4313. const compress_method_t compress_method =
  4314. find_best_compression_method(args->compression_supported, 1);
  4315. const time_t if_modified_since = args->if_modified_since;
  4316. {
  4317. smartlist_t *certs = smartlist_new();
  4318. ssize_t len = -1;
  4319. if (!strcmp(url, "/tor/keys/all")) {
  4320. authority_cert_get_all(certs);
  4321. } else if (!strcmp(url, "/tor/keys/authority")) {
  4322. authority_cert_t *cert = get_my_v3_authority_cert();
  4323. if (cert)
  4324. smartlist_add(certs, cert);
  4325. } else if (!strcmpstart(url, "/tor/keys/fp/")) {
  4326. smartlist_t *fps = smartlist_new();
  4327. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/fp/"),
  4328. fps, NULL,
  4329. DSR_HEX|DSR_SORT_UNIQ);
  4330. SMARTLIST_FOREACH(fps, char *, d, {
  4331. authority_cert_t *c = authority_cert_get_newest_by_id(d);
  4332. if (c) smartlist_add(certs, c);
  4333. tor_free(d);
  4334. });
  4335. smartlist_free(fps);
  4336. } else if (!strcmpstart(url, "/tor/keys/sk/")) {
  4337. smartlist_t *fps = smartlist_new();
  4338. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/sk/"),
  4339. fps, NULL,
  4340. DSR_HEX|DSR_SORT_UNIQ);
  4341. SMARTLIST_FOREACH(fps, char *, d, {
  4342. authority_cert_t *c = authority_cert_get_by_sk_digest(d);
  4343. if (c) smartlist_add(certs, c);
  4344. tor_free(d);
  4345. });
  4346. smartlist_free(fps);
  4347. } else if (!strcmpstart(url, "/tor/keys/fp-sk/")) {
  4348. smartlist_t *fp_sks = smartlist_new();
  4349. dir_split_resource_into_fingerprint_pairs(url+strlen("/tor/keys/fp-sk/"),
  4350. fp_sks);
  4351. SMARTLIST_FOREACH(fp_sks, fp_pair_t *, pair, {
  4352. authority_cert_t *c = authority_cert_get_by_digests(pair->first,
  4353. pair->second);
  4354. if (c) smartlist_add(certs, c);
  4355. tor_free(pair);
  4356. });
  4357. smartlist_free(fp_sks);
  4358. } else {
  4359. write_http_status_line(conn, 400, "Bad request");
  4360. goto keys_done;
  4361. }
  4362. if (!smartlist_len(certs)) {
  4363. write_http_status_line(conn, 404, "Not found");
  4364. goto keys_done;
  4365. }
  4366. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4367. if (c->cache_info.published_on < if_modified_since)
  4368. SMARTLIST_DEL_CURRENT(certs, c));
  4369. if (!smartlist_len(certs)) {
  4370. write_http_status_line(conn, 304, "Not modified");
  4371. goto keys_done;
  4372. }
  4373. len = 0;
  4374. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4375. len += c->cache_info.signed_descriptor_len);
  4376. if (global_write_bucket_low(TO_CONN(conn),
  4377. compress_method != NO_METHOD ? len/2 : len,
  4378. 2)) {
  4379. write_http_status_line(conn, 503, "Directory busy, try again later");
  4380. goto keys_done;
  4381. }
  4382. write_http_response_header(conn,
  4383. compress_method != NO_METHOD ? -1 : len,
  4384. compress_method,
  4385. 60*60);
  4386. if (compress_method != NO_METHOD) {
  4387. conn->compress_state = tor_compress_new(1, compress_method,
  4388. choose_compression_level(len));
  4389. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4390. connection_write_to_buf_compress(
  4391. c->cache_info.signed_descriptor_body,
  4392. c->cache_info.signed_descriptor_len,
  4393. conn, 0));
  4394. connection_write_to_buf_compress("", 0, conn, 1);
  4395. } else {
  4396. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4397. connection_write_to_buf(c->cache_info.signed_descriptor_body,
  4398. c->cache_info.signed_descriptor_len,
  4399. TO_CONN(conn)));
  4400. }
  4401. keys_done:
  4402. smartlist_free(certs);
  4403. goto done;
  4404. }
  4405. done:
  4406. return 0;
  4407. }
  4408. /** Helper function for GET /tor/rendezvous2/
  4409. */
  4410. static int
  4411. handle_get_hs_descriptor_v2(dir_connection_t *conn,
  4412. const get_handler_args_t *args)
  4413. {
  4414. const char *url = args->url;
  4415. if (connection_dir_is_encrypted(conn)) {
  4416. /* Handle v2 rendezvous descriptor fetch request. */
  4417. const char *descp;
  4418. const char *query = url + strlen("/tor/rendezvous2/");
  4419. if (rend_valid_descriptor_id(query)) {
  4420. log_info(LD_REND, "Got a v2 rendezvous descriptor request for ID '%s'",
  4421. safe_str(escaped(query)));
  4422. switch (rend_cache_lookup_v2_desc_as_dir(query, &descp)) {
  4423. case 1: /* valid */
  4424. write_http_response_header(conn, strlen(descp), NO_METHOD, 0);
  4425. connection_write_to_buf(descp, strlen(descp), TO_CONN(conn));
  4426. break;
  4427. case 0: /* well-formed but not present */
  4428. write_http_status_line(conn, 404, "Not found");
  4429. break;
  4430. case -1: /* not well-formed */
  4431. write_http_status_line(conn, 400, "Bad request");
  4432. break;
  4433. }
  4434. } else { /* not well-formed */
  4435. write_http_status_line(conn, 400, "Bad request");
  4436. }
  4437. goto done;
  4438. } else {
  4439. /* Not encrypted! */
  4440. write_http_status_line(conn, 404, "Not found");
  4441. }
  4442. done:
  4443. return 0;
  4444. }
  4445. /** Helper function for GET /tor/hs/3/<z>. Only for version 3.
  4446. */
  4447. STATIC int
  4448. handle_get_hs_descriptor_v3(dir_connection_t *conn,
  4449. const get_handler_args_t *args)
  4450. {
  4451. int retval;
  4452. const char *desc_str = NULL;
  4453. const char *pubkey_str = NULL;
  4454. const char *url = args->url;
  4455. /* Reject unencrypted dir connections */
  4456. if (!connection_dir_is_encrypted(conn)) {
  4457. write_http_status_line(conn, 404, "Not found");
  4458. goto done;
  4459. }
  4460. /* After the path prefix follows the base64 encoded blinded pubkey which we
  4461. * use to get the descriptor from the cache. Skip the prefix and get the
  4462. * pubkey. */
  4463. tor_assert(!strcmpstart(url, "/tor/hs/3/"));
  4464. pubkey_str = url + strlen("/tor/hs/3/");
  4465. retval = hs_cache_lookup_as_dir(HS_VERSION_THREE,
  4466. pubkey_str, &desc_str);
  4467. if (retval <= 0 || desc_str == NULL) {
  4468. write_http_status_line(conn, 404, "Not found");
  4469. goto done;
  4470. }
  4471. /* Found requested descriptor! Pass it to this nice client. */
  4472. write_http_response_header(conn, strlen(desc_str), NO_METHOD, 0);
  4473. connection_write_to_buf(desc_str, strlen(desc_str), TO_CONN(conn));
  4474. done:
  4475. return 0;
  4476. }
  4477. /** Helper function for GET /tor/networkstatus-bridges
  4478. */
  4479. static int
  4480. handle_get_networkstatus_bridges(dir_connection_t *conn,
  4481. const get_handler_args_t *args)
  4482. {
  4483. const char *headers = args->headers;
  4484. const or_options_t *options = get_options();
  4485. if (options->BridgeAuthoritativeDir &&
  4486. options->BridgePassword_AuthDigest_ &&
  4487. connection_dir_is_encrypted(conn)) {
  4488. char *status;
  4489. char digest[DIGEST256_LEN];
  4490. char *header = http_get_header(headers, "Authorization: Basic ");
  4491. if (header)
  4492. crypto_digest256(digest, header, strlen(header), DIGEST_SHA256);
  4493. /* now make sure the password is there and right */
  4494. if (!header ||
  4495. tor_memneq(digest,
  4496. options->BridgePassword_AuthDigest_, DIGEST256_LEN)) {
  4497. write_http_status_line(conn, 404, "Not found");
  4498. tor_free(header);
  4499. goto done;
  4500. }
  4501. tor_free(header);
  4502. /* all happy now. send an answer. */
  4503. status = networkstatus_getinfo_by_purpose("bridge", time(NULL));
  4504. size_t dlen = strlen(status);
  4505. write_http_response_header(conn, dlen, NO_METHOD, 0);
  4506. connection_write_to_buf(status, dlen, TO_CONN(conn));
  4507. tor_free(status);
  4508. goto done;
  4509. }
  4510. done:
  4511. return 0;
  4512. }
  4513. /** Helper function for GET robots.txt or /tor/robots.txt */
  4514. static int
  4515. handle_get_robots(dir_connection_t *conn, const get_handler_args_t *args)
  4516. {
  4517. (void)args;
  4518. {
  4519. const char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  4520. size_t len = strlen(robots);
  4521. write_http_response_header(conn, len, NO_METHOD, ROBOTS_CACHE_LIFETIME);
  4522. connection_write_to_buf(robots, len, TO_CONN(conn));
  4523. }
  4524. return 0;
  4525. }
  4526. /* Given the <b>url</b> from a POST request, try to extract the version number
  4527. * using the provided <b>prefix</b>. The version should be after the prefix and
  4528. * ending with the seperator "/". For instance:
  4529. * /tor/hs/3/publish
  4530. *
  4531. * On success, <b>end_pos</b> points to the position right after the version
  4532. * was found. On error, it is set to NULL.
  4533. *
  4534. * Return version on success else negative value. */
  4535. STATIC int
  4536. parse_hs_version_from_post(const char *url, const char *prefix,
  4537. const char **end_pos)
  4538. {
  4539. int ok;
  4540. unsigned long version;
  4541. const char *start;
  4542. char *end = NULL;
  4543. tor_assert(url);
  4544. tor_assert(prefix);
  4545. tor_assert(end_pos);
  4546. /* Check if the prefix does start the url. */
  4547. if (strcmpstart(url, prefix)) {
  4548. goto err;
  4549. }
  4550. /* Move pointer to the end of the prefix string. */
  4551. start = url + strlen(prefix);
  4552. /* Try this to be the HS version and if we are still at the separator, next
  4553. * will be move to the right value. */
  4554. version = tor_parse_long(start, 10, 0, INT_MAX, &ok, &end);
  4555. if (!ok) {
  4556. goto err;
  4557. }
  4558. *end_pos = end;
  4559. return (int) version;
  4560. err:
  4561. *end_pos = NULL;
  4562. return -1;
  4563. }
  4564. /* Handle the POST request for a hidden service descripror. The request is in
  4565. * <b>url</b>, the body of the request is in <b>body</b>. Return 200 on success
  4566. * else return 400 indicating a bad request. */
  4567. STATIC int
  4568. handle_post_hs_descriptor(const char *url, const char *body)
  4569. {
  4570. int version;
  4571. const char *end_pos;
  4572. tor_assert(url);
  4573. tor_assert(body);
  4574. version = parse_hs_version_from_post(url, "/tor/hs/", &end_pos);
  4575. if (version < 0) {
  4576. goto err;
  4577. }
  4578. /* We have a valid version number, now make sure it's a publish request. Use
  4579. * the end position just after the version and check for the command. */
  4580. if (strcmpstart(end_pos, "/publish")) {
  4581. goto err;
  4582. }
  4583. switch (version) {
  4584. case HS_VERSION_THREE:
  4585. if (hs_cache_store_as_dir(body) < 0) {
  4586. goto err;
  4587. }
  4588. log_info(LD_REND, "Publish request for HS descriptor handled "
  4589. "successfully.");
  4590. break;
  4591. default:
  4592. /* Unsupported version, return a bad request. */
  4593. goto err;
  4594. }
  4595. return 200;
  4596. err:
  4597. /* Bad request. */
  4598. return 400;
  4599. }
  4600. /** Helper function: called when a dirserver gets a complete HTTP POST
  4601. * request. Look for an uploaded server descriptor or rendezvous
  4602. * service descriptor. On finding one, process it and write a
  4603. * response into conn-\>outbuf. If the request is unrecognized, send a
  4604. * 400. Always return 0. */
  4605. MOCK_IMPL(STATIC int,
  4606. directory_handle_command_post,(dir_connection_t *conn, const char *headers,
  4607. const char *body, size_t body_len))
  4608. {
  4609. char *url = NULL;
  4610. const or_options_t *options = get_options();
  4611. log_debug(LD_DIRSERV,"Received POST command.");
  4612. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  4613. if (!public_server_mode(options)) {
  4614. log_info(LD_DIR, "Rejected dir post request from %s "
  4615. "since we're not a public relay.", conn->base_.address);
  4616. write_http_status_line(conn, 503, "Not acting as a public relay");
  4617. goto done;
  4618. }
  4619. if (parse_http_url(headers, &url) < 0) {
  4620. write_http_status_line(conn, 400, "Bad request");
  4621. return 0;
  4622. }
  4623. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  4624. /* Handle v2 rendezvous service publish request. */
  4625. if (connection_dir_is_encrypted(conn) &&
  4626. !strcmpstart(url,"/tor/rendezvous2/publish")) {
  4627. if (rend_cache_store_v2_desc_as_dir(body) < 0) {
  4628. log_warn(LD_REND, "Rejected v2 rend descriptor (body size %d) from %s.",
  4629. (int)body_len, conn->base_.address);
  4630. write_http_status_line(conn, 400,
  4631. "Invalid v2 service descriptor rejected");
  4632. } else {
  4633. write_http_status_line(conn, 200, "Service descriptor (v2) stored");
  4634. log_info(LD_REND, "Handled v2 rendezvous descriptor post: accepted");
  4635. }
  4636. goto done;
  4637. }
  4638. /* Handle HS descriptor publish request. */
  4639. /* XXX: This should be disabled with a consensus param until we want to
  4640. * the prop224 be deployed and thus use. */
  4641. if (connection_dir_is_encrypted(conn) && !strcmpstart(url, "/tor/hs/")) {
  4642. const char *msg = "HS descriptor stored successfully.";
  4643. /* We most probably have a publish request for an HS descriptor. */
  4644. int code = handle_post_hs_descriptor(url, body);
  4645. if (code != 200) {
  4646. msg = "Invalid HS descriptor. Rejected.";
  4647. }
  4648. write_http_status_line(conn, code, msg);
  4649. goto done;
  4650. }
  4651. if (!authdir_mode(options)) {
  4652. /* we just provide cached directories; we don't want to
  4653. * receive anything. */
  4654. write_http_status_line(conn, 400, "Nonauthoritative directory does not "
  4655. "accept posted server descriptors");
  4656. goto done;
  4657. }
  4658. if (authdir_mode(options) &&
  4659. !strcmp(url,"/tor/")) { /* server descriptor post */
  4660. const char *msg = "[None]";
  4661. uint8_t purpose = authdir_mode_bridge(options) ?
  4662. ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  4663. was_router_added_t r = dirserv_add_multiple_descriptors(body, purpose,
  4664. conn->base_.address, &msg);
  4665. tor_assert(msg);
  4666. if (r == ROUTER_ADDED_SUCCESSFULLY) {
  4667. write_http_status_line(conn, 200, msg);
  4668. } else if (WRA_WAS_OUTDATED(r)) {
  4669. write_http_response_header_impl(conn, -1, NULL, NULL,
  4670. "X-Descriptor-Not-New: Yes\r\n", -1);
  4671. } else {
  4672. log_info(LD_DIRSERV,
  4673. "Rejected router descriptor or extra-info from %s "
  4674. "(\"%s\").",
  4675. conn->base_.address, msg);
  4676. write_http_status_line(conn, 400, msg);
  4677. }
  4678. goto done;
  4679. }
  4680. if (authdir_mode_v3(options) &&
  4681. !strcmp(url,"/tor/post/vote")) { /* v3 networkstatus vote */
  4682. const char *msg = "OK";
  4683. int status;
  4684. if (dirvote_add_vote(body, &msg, &status)) {
  4685. write_http_status_line(conn, status, "Vote stored");
  4686. } else {
  4687. tor_assert(msg);
  4688. log_warn(LD_DIRSERV, "Rejected vote from %s (\"%s\").",
  4689. conn->base_.address, msg);
  4690. write_http_status_line(conn, status, msg);
  4691. }
  4692. goto done;
  4693. }
  4694. if (authdir_mode_v3(options) &&
  4695. !strcmp(url,"/tor/post/consensus-signature")) { /* sigs on consensus. */
  4696. const char *msg = NULL;
  4697. if (dirvote_add_signatures(body, conn->base_.address, &msg)>=0) {
  4698. write_http_status_line(conn, 200, msg?msg:"Signatures stored");
  4699. } else {
  4700. log_warn(LD_DIR, "Unable to store signatures posted by %s: %s",
  4701. conn->base_.address, msg?msg:"???");
  4702. write_http_status_line(conn, 400, msg?msg:"Unable to store signatures");
  4703. }
  4704. goto done;
  4705. }
  4706. /* we didn't recognize the url */
  4707. write_http_status_line(conn, 404, "Not found");
  4708. done:
  4709. tor_free(url);
  4710. return 0;
  4711. }
  4712. /** Called when a dirserver receives data on a directory connection;
  4713. * looks for an HTTP request. If the request is complete, remove it
  4714. * from the inbuf, try to process it; otherwise, leave it on the
  4715. * buffer. Return a 0 on success, or -1 on error.
  4716. */
  4717. STATIC int
  4718. directory_handle_command(dir_connection_t *conn)
  4719. {
  4720. char *headers=NULL, *body=NULL;
  4721. size_t body_len=0;
  4722. int r;
  4723. tor_assert(conn);
  4724. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  4725. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  4726. &headers, MAX_HEADERS_SIZE,
  4727. &body, &body_len, MAX_DIR_UL_SIZE, 0)) {
  4728. case -1: /* overflow */
  4729. log_warn(LD_DIRSERV,
  4730. "Request too large from address '%s' to DirPort. Closing.",
  4731. safe_str(conn->base_.address));
  4732. return -1;
  4733. case 0:
  4734. log_debug(LD_DIRSERV,"command not all here yet.");
  4735. return 0;
  4736. /* case 1, fall through */
  4737. }
  4738. http_set_address_origin(headers, TO_CONN(conn));
  4739. // we should escape headers here as well,
  4740. // but we can't call escaped() twice, as it uses the same buffer
  4741. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, escaped(body));
  4742. if (!strncasecmp(headers,"GET",3))
  4743. r = directory_handle_command_get(conn, headers, body, body_len);
  4744. else if (!strncasecmp(headers,"POST",4))
  4745. r = directory_handle_command_post(conn, headers, body, body_len);
  4746. else {
  4747. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  4748. "Got headers %s with unknown command. Closing.",
  4749. escaped(headers));
  4750. r = -1;
  4751. }
  4752. tor_free(headers); tor_free(body);
  4753. return r;
  4754. }
  4755. /** Write handler for directory connections; called when all data has
  4756. * been flushed. Close the connection or wait for a response as
  4757. * appropriate.
  4758. */
  4759. int
  4760. connection_dir_finished_flushing(dir_connection_t *conn)
  4761. {
  4762. tor_assert(conn);
  4763. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  4764. /* Note that we have finished writing the directory response. For direct
  4765. * connections this means we're done; for tunneled connections it's only
  4766. * an intermediate step. */
  4767. if (conn->dirreq_id)
  4768. geoip_change_dirreq_state(conn->dirreq_id, DIRREQ_TUNNELED,
  4769. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  4770. else
  4771. geoip_change_dirreq_state(TO_CONN(conn)->global_identifier,
  4772. DIRREQ_DIRECT,
  4773. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  4774. switch (conn->base_.state) {
  4775. case DIR_CONN_STATE_CONNECTING:
  4776. case DIR_CONN_STATE_CLIENT_SENDING:
  4777. log_debug(LD_DIR,"client finished sending command.");
  4778. conn->base_.state = DIR_CONN_STATE_CLIENT_READING;
  4779. return 0;
  4780. case DIR_CONN_STATE_SERVER_WRITING:
  4781. if (conn->spool) {
  4782. log_warn(LD_BUG, "Emptied a dirserv buffer, but it's still spooling!");
  4783. connection_mark_for_close(TO_CONN(conn));
  4784. } else {
  4785. log_debug(LD_DIRSERV, "Finished writing server response. Closing.");
  4786. connection_mark_for_close(TO_CONN(conn));
  4787. }
  4788. return 0;
  4789. default:
  4790. log_warn(LD_BUG,"called in unexpected state %d.",
  4791. conn->base_.state);
  4792. tor_fragile_assert();
  4793. return -1;
  4794. }
  4795. return 0;
  4796. }
  4797. /* We just got a new consensus! If there are other in-progress requests
  4798. * for this consensus flavor (for example because we launched several in
  4799. * parallel), cancel them.
  4800. *
  4801. * We do this check here (not just in
  4802. * connection_ap_handshake_attach_circuit()) to handle the edge case where
  4803. * a consensus fetch begins and ends before some other one tries to attach to
  4804. * a circuit, in which case the other one won't know that we're all happy now.
  4805. *
  4806. * Don't mark the conn that just gave us the consensus -- otherwise we
  4807. * would end up double-marking it when it cleans itself up.
  4808. */
  4809. static void
  4810. connection_dir_close_consensus_fetches(dir_connection_t *except_this_one,
  4811. const char *resource)
  4812. {
  4813. smartlist_t *conns_to_close =
  4814. connection_dir_list_by_purpose_and_resource(DIR_PURPOSE_FETCH_CONSENSUS,
  4815. resource);
  4816. SMARTLIST_FOREACH_BEGIN(conns_to_close, dir_connection_t *, d) {
  4817. if (d == except_this_one)
  4818. continue;
  4819. log_info(LD_DIR, "Closing consensus fetch (to %s) since one "
  4820. "has just arrived.", TO_CONN(d)->address);
  4821. connection_mark_for_close(TO_CONN(d));
  4822. } SMARTLIST_FOREACH_END(d);
  4823. smartlist_free(conns_to_close);
  4824. }
  4825. /** Connected handler for directory connections: begin sending data to the
  4826. * server, and return 0.
  4827. * Only used when connections don't immediately connect. */
  4828. int
  4829. connection_dir_finished_connecting(dir_connection_t *conn)
  4830. {
  4831. tor_assert(conn);
  4832. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  4833. tor_assert(conn->base_.state == DIR_CONN_STATE_CONNECTING);
  4834. log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
  4835. conn->base_.address,conn->base_.port);
  4836. /* start flushing conn */
  4837. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  4838. return 0;
  4839. }
  4840. /** Decide which download schedule we want to use based on descriptor type
  4841. * in <b>dls</b> and <b>options</b>.
  4842. * Then return a list of int pointers defining download delays in seconds.
  4843. * Helper function for download_status_increment_failure(),
  4844. * download_status_reset(), and download_status_increment_attempt(). */
  4845. STATIC const smartlist_t *
  4846. find_dl_schedule(const download_status_t *dls, const or_options_t *options)
  4847. {
  4848. const int dir_server = dir_server_mode(options);
  4849. const int multi_d = networkstatus_consensus_can_use_multiple_directories(
  4850. options);
  4851. const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
  4852. time(NULL));
  4853. const int use_fallbacks = networkstatus_consensus_can_use_extra_fallbacks(
  4854. options);
  4855. switch (dls->schedule) {
  4856. case DL_SCHED_GENERIC:
  4857. if (dir_server) {
  4858. return options->TestingServerDownloadSchedule;
  4859. } else {
  4860. return options->TestingClientDownloadSchedule;
  4861. }
  4862. case DL_SCHED_CONSENSUS:
  4863. if (!multi_d) {
  4864. return options->TestingServerConsensusDownloadSchedule;
  4865. } else {
  4866. if (we_are_bootstrapping) {
  4867. if (!use_fallbacks) {
  4868. /* A bootstrapping client without extra fallback directories */
  4869. return
  4870. options->ClientBootstrapConsensusAuthorityOnlyDownloadSchedule;
  4871. } else if (dls->want_authority) {
  4872. /* A bootstrapping client with extra fallback directories, but
  4873. * connecting to an authority */
  4874. return
  4875. options->ClientBootstrapConsensusAuthorityDownloadSchedule;
  4876. } else {
  4877. /* A bootstrapping client connecting to extra fallback directories
  4878. */
  4879. return
  4880. options->ClientBootstrapConsensusFallbackDownloadSchedule;
  4881. }
  4882. } else {
  4883. return options->TestingClientConsensusDownloadSchedule;
  4884. }
  4885. }
  4886. case DL_SCHED_BRIDGE:
  4887. return options->TestingBridgeDownloadSchedule;
  4888. default:
  4889. tor_assert(0);
  4890. }
  4891. /* Impossible, but gcc will fail with -Werror without a `return`. */
  4892. return NULL;
  4893. }
  4894. /** Decide which minimum and maximum delay step we want to use based on
  4895. * descriptor type in <b>dls</b> and <b>options</b>.
  4896. * Helper function for download_status_schedule_get_delay(). */
  4897. STATIC void
  4898. find_dl_min_and_max_delay(download_status_t *dls, const or_options_t *options,
  4899. int *min, int *max)
  4900. {
  4901. tor_assert(dls);
  4902. tor_assert(options);
  4903. tor_assert(min);
  4904. tor_assert(max);
  4905. /*
  4906. * For now, just use the existing schedule config stuff and pick the
  4907. * first/last entries off to get min/max delay for backoff purposes
  4908. */
  4909. const smartlist_t *schedule = find_dl_schedule(dls, options);
  4910. tor_assert(schedule != NULL && smartlist_len(schedule) >= 2);
  4911. *min = *((int *)(smartlist_get(schedule, 0)));
  4912. /* Increment on failure schedules always use exponential backoff, but they
  4913. * have a smaller limit when they're deterministic */
  4914. if (dls->backoff == DL_SCHED_DETERMINISTIC)
  4915. *max = *((int *)((smartlist_get(schedule, smartlist_len(schedule) - 1))));
  4916. else
  4917. *max = INT_MAX;
  4918. }
  4919. /** Advance one delay step. The algorithm is to use the previous delay to
  4920. * compute an increment, we construct a value uniformly at random between
  4921. * delay+1 and (delay*(DIR_DEFAULT_RANDOM_MULTIPLIER+1))+1 (or
  4922. * DIR_TEST_NET_RANDOM_MULTIPLIER in test networks).
  4923. * We then clamp that value to be no larger than max_delay, and return it.
  4924. *
  4925. * Requires that delay is less than INT_MAX, and delay is in [0,max_delay].
  4926. */
  4927. STATIC int
  4928. next_random_exponential_delay(int delay, int max_delay)
  4929. {
  4930. /* Check preconditions */
  4931. if (BUG(max_delay < 0))
  4932. max_delay = 0;
  4933. if (BUG(delay > max_delay))
  4934. delay = max_delay;
  4935. if (delay == INT_MAX)
  4936. return INT_MAX; /* prevent overflow */
  4937. if (BUG(delay < 0))
  4938. delay = 0;
  4939. /* How much are we willing to add to the delay? */
  4940. int max_increment;
  4941. int multiplier = DIR_DEFAULT_RANDOM_MULTIPLIER;
  4942. if (get_options()->TestingTorNetwork) {
  4943. /* Decrease the multiplier in testing networks. This reduces the variance,
  4944. * so that bootstrap is more reliable. */
  4945. multiplier = DIR_TEST_NET_RANDOM_MULTIPLIER;
  4946. }
  4947. if (delay && delay < (INT_MAX-1) / multiplier) {
  4948. max_increment = delay * multiplier;
  4949. } else if (delay) {
  4950. max_increment = INT_MAX-1;
  4951. } else {
  4952. max_increment = 1;
  4953. }
  4954. if (BUG(max_increment < 1))
  4955. max_increment = 1;
  4956. /* the + 1 here is so that we always wait longer than last time. */
  4957. int increment = crypto_rand_int(max_increment)+1;
  4958. if (increment < max_delay - delay)
  4959. return delay + increment;
  4960. else
  4961. return max_delay;
  4962. }
  4963. /** Find the current delay for dls based on schedule or min_delay/
  4964. * max_delay if we're using exponential backoff. If dls->backoff is
  4965. * DL_SCHED_RANDOM_EXPONENTIAL, we must have 0 <= min_delay <= max_delay <=
  4966. * INT_MAX, but schedule may be set to NULL; otherwise schedule is required.
  4967. * This function sets dls->next_attempt_at based on now, and returns the delay.
  4968. * Helper for download_status_increment_failure and
  4969. * download_status_increment_attempt. */
  4970. STATIC int
  4971. download_status_schedule_get_delay(download_status_t *dls,
  4972. const smartlist_t *schedule,
  4973. int min_delay, int max_delay,
  4974. time_t now)
  4975. {
  4976. tor_assert(dls);
  4977. /* We don't need a schedule if we're using random exponential backoff */
  4978. tor_assert(dls->backoff == DL_SCHED_RANDOM_EXPONENTIAL ||
  4979. schedule != NULL);
  4980. /* If we're using random exponential backoff, we do need min/max delay */
  4981. tor_assert(dls->backoff != DL_SCHED_RANDOM_EXPONENTIAL ||
  4982. (min_delay >= 0 && max_delay >= min_delay));
  4983. int delay = INT_MAX;
  4984. uint8_t dls_schedule_position = (dls->increment_on
  4985. == DL_SCHED_INCREMENT_ATTEMPT
  4986. ? dls->n_download_attempts
  4987. : dls->n_download_failures);
  4988. if (dls->backoff == DL_SCHED_DETERMINISTIC) {
  4989. if (dls_schedule_position < smartlist_len(schedule))
  4990. delay = *(int *)smartlist_get(schedule, dls_schedule_position);
  4991. else if (dls_schedule_position == IMPOSSIBLE_TO_DOWNLOAD)
  4992. delay = INT_MAX;
  4993. else
  4994. delay = *(int *)smartlist_get(schedule, smartlist_len(schedule) - 1);
  4995. } else if (dls->backoff == DL_SCHED_RANDOM_EXPONENTIAL) {
  4996. /* Check if we missed a reset somehow */
  4997. IF_BUG_ONCE(dls->last_backoff_position > dls_schedule_position) {
  4998. dls->last_backoff_position = 0;
  4999. dls->last_delay_used = 0;
  5000. }
  5001. if (dls_schedule_position > 0) {
  5002. delay = dls->last_delay_used;
  5003. while (dls->last_backoff_position < dls_schedule_position) {
  5004. /* Do one increment step */
  5005. delay = next_random_exponential_delay(delay, max_delay);
  5006. /* Update our position */
  5007. ++(dls->last_backoff_position);
  5008. }
  5009. } else {
  5010. /* If we're just starting out, use the minimum delay */
  5011. delay = min_delay;
  5012. }
  5013. /* Clamp it within min/max if we have them */
  5014. if (min_delay >= 0 && delay < min_delay) delay = min_delay;
  5015. if (max_delay != INT_MAX && delay > max_delay) delay = max_delay;
  5016. /* Store it for next time */
  5017. dls->last_backoff_position = dls_schedule_position;
  5018. dls->last_delay_used = delay;
  5019. }
  5020. /* A negative delay makes no sense. Knowing that delay is
  5021. * non-negative allows us to safely do the wrapping check below. */
  5022. tor_assert(delay >= 0);
  5023. /* Avoid now+delay overflowing TIME_MAX, by comparing with a subtraction
  5024. * that won't overflow (since delay is non-negative). */
  5025. if (delay < INT_MAX && now <= TIME_MAX - delay) {
  5026. dls->next_attempt_at = now+delay;
  5027. } else {
  5028. dls->next_attempt_at = TIME_MAX;
  5029. }
  5030. return delay;
  5031. }
  5032. /* Log a debug message about item, which increments on increment_action, has
  5033. * incremented dls_n_download_increments times. The message varies based on
  5034. * was_schedule_incremented (if not, not_incremented_response is logged), and
  5035. * the values of increment, dls_next_attempt_at, and now.
  5036. * Helper for download_status_increment_failure and
  5037. * download_status_increment_attempt. */
  5038. static void
  5039. download_status_log_helper(const char *item, int was_schedule_incremented,
  5040. const char *increment_action,
  5041. const char *not_incremented_response,
  5042. uint8_t dls_n_download_increments, int increment,
  5043. time_t dls_next_attempt_at, time_t now)
  5044. {
  5045. if (item) {
  5046. if (!was_schedule_incremented)
  5047. log_debug(LD_DIR, "%s %s %d time(s); I'll try again %s.",
  5048. item, increment_action, (int)dls_n_download_increments,
  5049. not_incremented_response);
  5050. else if (increment == 0)
  5051. log_debug(LD_DIR, "%s %s %d time(s); I'll try again immediately.",
  5052. item, increment_action, (int)dls_n_download_increments);
  5053. else if (dls_next_attempt_at < TIME_MAX)
  5054. log_debug(LD_DIR, "%s %s %d time(s); I'll try again in %d seconds.",
  5055. item, increment_action, (int)dls_n_download_increments,
  5056. (int)(dls_next_attempt_at-now));
  5057. else
  5058. log_debug(LD_DIR, "%s %s %d time(s); Giving up for a while.",
  5059. item, increment_action, (int)dls_n_download_increments);
  5060. }
  5061. }
  5062. /** Determine when a failed download attempt should be retried.
  5063. * Called when an attempt to download <b>dls</b> has failed with HTTP status
  5064. * <b>status_code</b>. Increment the failure count (if the code indicates a
  5065. * real failure, or if we're a server) and set <b>dls</b>-\>next_attempt_at to
  5066. * an appropriate time in the future and return it.
  5067. * If <b>dls->increment_on</b> is DL_SCHED_INCREMENT_ATTEMPT, increment the
  5068. * failure count, and return a time in the far future for the next attempt (to
  5069. * avoid an immediate retry). */
  5070. time_t
  5071. download_status_increment_failure(download_status_t *dls, int status_code,
  5072. const char *item, int server, time_t now)
  5073. {
  5074. (void) status_code; // XXXX no longer used.
  5075. (void) server; // XXXX no longer used.
  5076. int increment = -1;
  5077. int min_delay = 0, max_delay = INT_MAX;
  5078. tor_assert(dls);
  5079. /* dls wasn't reset before it was used */
  5080. if (dls->next_attempt_at == 0) {
  5081. download_status_reset(dls);
  5082. }
  5083. /* count the failure */
  5084. if (dls->n_download_failures < IMPOSSIBLE_TO_DOWNLOAD-1) {
  5085. ++dls->n_download_failures;
  5086. }
  5087. if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
  5088. /* We don't find out that a failure-based schedule has attempted a
  5089. * connection until that connection fails.
  5090. * We'll never find out about successful connections, but this doesn't
  5091. * matter, because schedules are reset after a successful download.
  5092. */
  5093. if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
  5094. ++dls->n_download_attempts;
  5095. /* only return a failure retry time if this schedule increments on failures
  5096. */
  5097. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  5098. find_dl_min_and_max_delay(dls, get_options(), &min_delay, &max_delay);
  5099. increment = download_status_schedule_get_delay(dls, schedule,
  5100. min_delay, max_delay, now);
  5101. }
  5102. download_status_log_helper(item, !dls->increment_on, "failed",
  5103. "concurrently", dls->n_download_failures,
  5104. increment,
  5105. download_status_get_next_attempt_at(dls),
  5106. now);
  5107. if (dls->increment_on == DL_SCHED_INCREMENT_ATTEMPT) {
  5108. /* stop this schedule retrying on failure, it will launch concurrent
  5109. * connections instead */
  5110. return TIME_MAX;
  5111. } else {
  5112. return download_status_get_next_attempt_at(dls);
  5113. }
  5114. }
  5115. /** Determine when the next download attempt should be made when using an
  5116. * attempt-based (potentially concurrent) download schedule.
  5117. * Called when an attempt to download <b>dls</b> is being initiated.
  5118. * Increment the attempt count and set <b>dls</b>-\>next_attempt_at to an
  5119. * appropriate time in the future and return it.
  5120. * If <b>dls->increment_on</b> is DL_SCHED_INCREMENT_FAILURE, don't increment
  5121. * the attempts, and return a time in the far future (to avoid launching a
  5122. * concurrent attempt). */
  5123. time_t
  5124. download_status_increment_attempt(download_status_t *dls, const char *item,
  5125. time_t now)
  5126. {
  5127. int delay = -1;
  5128. int min_delay = 0, max_delay = INT_MAX;
  5129. tor_assert(dls);
  5130. /* dls wasn't reset before it was used */
  5131. if (dls->next_attempt_at == 0) {
  5132. download_status_reset(dls);
  5133. }
  5134. if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
  5135. /* this schedule should retry on failure, and not launch any concurrent
  5136. attempts */
  5137. log_warn(LD_BUG, "Tried to launch an attempt-based connection on a "
  5138. "failure-based schedule.");
  5139. return TIME_MAX;
  5140. }
  5141. if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
  5142. ++dls->n_download_attempts;
  5143. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  5144. find_dl_min_and_max_delay(dls, get_options(), &min_delay, &max_delay);
  5145. delay = download_status_schedule_get_delay(dls, schedule,
  5146. min_delay, max_delay, now);
  5147. download_status_log_helper(item, dls->increment_on, "attempted",
  5148. "on failure", dls->n_download_attempts,
  5149. delay, download_status_get_next_attempt_at(dls),
  5150. now);
  5151. return download_status_get_next_attempt_at(dls);
  5152. }
  5153. static time_t
  5154. download_status_get_initial_delay_from_now(const download_status_t *dls)
  5155. {
  5156. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  5157. /* We use constant initial delays, even in exponential backoff
  5158. * schedules. */
  5159. return time(NULL) + *(int *)smartlist_get(schedule, 0);
  5160. }
  5161. /** Reset <b>dls</b> so that it will be considered downloadable
  5162. * immediately, and/or to show that we don't need it anymore.
  5163. *
  5164. * Must be called to initialise a download schedule, otherwise the zeroth item
  5165. * in the schedule will never be used.
  5166. *
  5167. * (We find the zeroth element of the download schedule, and set
  5168. * next_attempt_at to be the appropriate offset from 'now'. In most
  5169. * cases this means setting it to 'now', so the item will be immediately
  5170. * downloadable; when using authorities with fallbacks, there is a few seconds'
  5171. * delay.) */
  5172. void
  5173. download_status_reset(download_status_t *dls)
  5174. {
  5175. if (dls->n_download_failures == IMPOSSIBLE_TO_DOWNLOAD
  5176. || dls->n_download_attempts == IMPOSSIBLE_TO_DOWNLOAD)
  5177. return; /* Don't reset this. */
  5178. dls->n_download_failures = 0;
  5179. dls->n_download_attempts = 0;
  5180. dls->next_attempt_at = download_status_get_initial_delay_from_now(dls);
  5181. dls->last_backoff_position = 0;
  5182. dls->last_delay_used = 0;
  5183. /* Don't reset dls->want_authority or dls->increment_on */
  5184. }
  5185. /** Return the number of failures on <b>dls</b> since the last success (if
  5186. * any). */
  5187. int
  5188. download_status_get_n_failures(const download_status_t *dls)
  5189. {
  5190. return dls->n_download_failures;
  5191. }
  5192. /** Return the number of attempts to download <b>dls</b> since the last success
  5193. * (if any). This can differ from download_status_get_n_failures() due to
  5194. * outstanding concurrent attempts. */
  5195. int
  5196. download_status_get_n_attempts(const download_status_t *dls)
  5197. {
  5198. return dls->n_download_attempts;
  5199. }
  5200. /** Return the next time to attempt to download <b>dls</b>. */
  5201. time_t
  5202. download_status_get_next_attempt_at(const download_status_t *dls)
  5203. {
  5204. /* dls wasn't reset before it was used */
  5205. if (dls->next_attempt_at == 0) {
  5206. /* so give the answer we would have given if it had been */
  5207. return download_status_get_initial_delay_from_now(dls);
  5208. }
  5209. return dls->next_attempt_at;
  5210. }
  5211. /** Called when one or more routerdesc (or extrainfo, if <b>was_extrainfo</b>)
  5212. * fetches have failed (with uppercase fingerprints listed in <b>failed</b>,
  5213. * either as descriptor digests or as identity digests based on
  5214. * <b>was_descriptor_digests</b>).
  5215. */
  5216. static void
  5217. dir_routerdesc_download_failed(smartlist_t *failed, int status_code,
  5218. int router_purpose,
  5219. int was_extrainfo, int was_descriptor_digests)
  5220. {
  5221. char digest[DIGEST_LEN];
  5222. time_t now = time(NULL);
  5223. int server = directory_fetches_from_authorities(get_options());
  5224. if (!was_descriptor_digests) {
  5225. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  5226. tor_assert(!was_extrainfo);
  5227. connection_dir_retry_bridges(failed);
  5228. }
  5229. return; /* FFFF should implement for other-than-router-purpose someday */
  5230. }
  5231. SMARTLIST_FOREACH_BEGIN(failed, const char *, cp) {
  5232. download_status_t *dls = NULL;
  5233. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  5234. log_warn(LD_BUG, "Malformed fingerprint in list: %s", escaped(cp));
  5235. continue;
  5236. }
  5237. if (was_extrainfo) {
  5238. signed_descriptor_t *sd =
  5239. router_get_by_extrainfo_digest(digest);
  5240. if (sd)
  5241. dls = &sd->ei_dl_status;
  5242. } else {
  5243. dls = router_get_dl_status_by_descriptor_digest(digest);
  5244. }
  5245. if (!dls || dls->n_download_failures >=
  5246. get_options()->TestingDescriptorMaxDownloadTries)
  5247. continue;
  5248. download_status_increment_failure(dls, status_code, cp, server, now);
  5249. } SMARTLIST_FOREACH_END(cp);
  5250. /* No need to relaunch descriptor downloads here: we already do it
  5251. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  5252. }
  5253. /** Called when a connection to download microdescriptors has failed in whole
  5254. * or in part. <b>failed</b> is a list of every microdesc digest we didn't
  5255. * get. <b>status_code</b> is the http status code we received. Reschedule the
  5256. * microdesc downloads as appropriate. */
  5257. static void
  5258. dir_microdesc_download_failed(smartlist_t *failed,
  5259. int status_code)
  5260. {
  5261. networkstatus_t *consensus
  5262. = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  5263. routerstatus_t *rs;
  5264. download_status_t *dls;
  5265. time_t now = time(NULL);
  5266. int server = directory_fetches_from_authorities(get_options());
  5267. if (! consensus)
  5268. return;
  5269. SMARTLIST_FOREACH_BEGIN(failed, const char *, d) {
  5270. rs = router_get_mutable_consensus_status_by_descriptor_digest(consensus,d);
  5271. if (!rs)
  5272. continue;
  5273. dls = &rs->dl_status;
  5274. if (dls->n_download_failures >=
  5275. get_options()->TestingMicrodescMaxDownloadTries)
  5276. continue;
  5277. {
  5278. char buf[BASE64_DIGEST256_LEN+1];
  5279. digest256_to_base64(buf, d);
  5280. download_status_increment_failure(dls, status_code, buf,
  5281. server, now);
  5282. }
  5283. } SMARTLIST_FOREACH_END(d);
  5284. }
  5285. /** Helper. Compare two fp_pair_t objects, and return negative, 0, or
  5286. * positive as appropriate. */
  5287. static int
  5288. compare_pairs_(const void **a, const void **b)
  5289. {
  5290. const fp_pair_t *fp1 = *a, *fp2 = *b;
  5291. int r;
  5292. if ((r = fast_memcmp(fp1->first, fp2->first, DIGEST_LEN)))
  5293. return r;
  5294. else
  5295. return fast_memcmp(fp1->second, fp2->second, DIGEST_LEN);
  5296. }
  5297. /** Divide a string <b>res</b> of the form FP1-FP2+FP3-FP4...[.z], where each
  5298. * FP is a hex-encoded fingerprint, into a sequence of distinct sorted
  5299. * fp_pair_t. Skip malformed pairs. On success, return 0 and add those
  5300. * fp_pair_t into <b>pairs_out</b>. On failure, return -1. */
  5301. int
  5302. dir_split_resource_into_fingerprint_pairs(const char *res,
  5303. smartlist_t *pairs_out)
  5304. {
  5305. smartlist_t *pairs_tmp = smartlist_new();
  5306. smartlist_t *pairs_result = smartlist_new();
  5307. smartlist_split_string(pairs_tmp, res, "+", 0, 0);
  5308. if (smartlist_len(pairs_tmp)) {
  5309. char *last = smartlist_get(pairs_tmp,smartlist_len(pairs_tmp)-1);
  5310. size_t last_len = strlen(last);
  5311. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  5312. last[last_len-2] = '\0';
  5313. }
  5314. }
  5315. SMARTLIST_FOREACH_BEGIN(pairs_tmp, char *, cp) {
  5316. if (strlen(cp) != HEX_DIGEST_LEN*2+1) {
  5317. log_info(LD_DIR,
  5318. "Skipping digest pair %s with non-standard length.", escaped(cp));
  5319. } else if (cp[HEX_DIGEST_LEN] != '-') {
  5320. log_info(LD_DIR,
  5321. "Skipping digest pair %s with missing dash.", escaped(cp));
  5322. } else {
  5323. fp_pair_t pair;
  5324. if (base16_decode(pair.first, DIGEST_LEN,
  5325. cp, HEX_DIGEST_LEN) != DIGEST_LEN ||
  5326. base16_decode(pair.second,DIGEST_LEN,
  5327. cp+HEX_DIGEST_LEN+1, HEX_DIGEST_LEN) != DIGEST_LEN) {
  5328. log_info(LD_DIR, "Skipping non-decodable digest pair %s", escaped(cp));
  5329. } else {
  5330. smartlist_add(pairs_result, tor_memdup(&pair, sizeof(pair)));
  5331. }
  5332. }
  5333. tor_free(cp);
  5334. } SMARTLIST_FOREACH_END(cp);
  5335. smartlist_free(pairs_tmp);
  5336. /* Uniq-and-sort */
  5337. smartlist_sort(pairs_result, compare_pairs_);
  5338. smartlist_uniq(pairs_result, compare_pairs_, tor_free_);
  5339. smartlist_add_all(pairs_out, pairs_result);
  5340. smartlist_free(pairs_result);
  5341. return 0;
  5342. }
  5343. /** Given a directory <b>resource</b> request, containing zero
  5344. * or more strings separated by plus signs, followed optionally by ".z", store
  5345. * the strings, in order, into <b>fp_out</b>. If <b>compressed_out</b> is
  5346. * non-NULL, set it to 1 if the resource ends in ".z", else set it to 0.
  5347. *
  5348. * If (flags & DSR_HEX), then delete all elements that aren't hex digests, and
  5349. * decode the rest. If (flags & DSR_BASE64), then use "-" rather than "+" as
  5350. * a separator, delete all the elements that aren't base64-encoded digests,
  5351. * and decode the rest. If (flags & DSR_DIGEST256), these digests should be
  5352. * 256 bits long; else they should be 160.
  5353. *
  5354. * If (flags & DSR_SORT_UNIQ), then sort the list and remove all duplicates.
  5355. */
  5356. int
  5357. dir_split_resource_into_fingerprints(const char *resource,
  5358. smartlist_t *fp_out, int *compressed_out,
  5359. int flags)
  5360. {
  5361. const int decode_hex = flags & DSR_HEX;
  5362. const int decode_base64 = flags & DSR_BASE64;
  5363. const int digests_are_256 = flags & DSR_DIGEST256;
  5364. const int sort_uniq = flags & DSR_SORT_UNIQ;
  5365. const int digest_len = digests_are_256 ? DIGEST256_LEN : DIGEST_LEN;
  5366. const int hex_digest_len = digests_are_256 ?
  5367. HEX_DIGEST256_LEN : HEX_DIGEST_LEN;
  5368. const int base64_digest_len = digests_are_256 ?
  5369. BASE64_DIGEST256_LEN : BASE64_DIGEST_LEN;
  5370. smartlist_t *fp_tmp = smartlist_new();
  5371. tor_assert(!(decode_hex && decode_base64));
  5372. tor_assert(fp_out);
  5373. smartlist_split_string(fp_tmp, resource, decode_base64?"-":"+", 0, 0);
  5374. if (compressed_out)
  5375. *compressed_out = 0;
  5376. if (smartlist_len(fp_tmp)) {
  5377. char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
  5378. size_t last_len = strlen(last);
  5379. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  5380. last[last_len-2] = '\0';
  5381. if (compressed_out)
  5382. *compressed_out = 1;
  5383. }
  5384. }
  5385. if (decode_hex || decode_base64) {
  5386. const size_t encoded_len = decode_hex ? hex_digest_len : base64_digest_len;
  5387. int i;
  5388. char *cp, *d = NULL;
  5389. for (i = 0; i < smartlist_len(fp_tmp); ++i) {
  5390. cp = smartlist_get(fp_tmp, i);
  5391. if (strlen(cp) != encoded_len) {
  5392. log_info(LD_DIR,
  5393. "Skipping digest %s with non-standard length.", escaped(cp));
  5394. smartlist_del_keeporder(fp_tmp, i--);
  5395. goto again;
  5396. }
  5397. d = tor_malloc_zero(digest_len);
  5398. if (decode_hex ?
  5399. (base16_decode(d, digest_len, cp, hex_digest_len) != digest_len) :
  5400. (base64_decode(d, digest_len, cp, base64_digest_len)
  5401. != digest_len)) {
  5402. log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
  5403. smartlist_del_keeporder(fp_tmp, i--);
  5404. goto again;
  5405. }
  5406. smartlist_set(fp_tmp, i, d);
  5407. d = NULL;
  5408. again:
  5409. tor_free(cp);
  5410. tor_free(d);
  5411. }
  5412. }
  5413. if (sort_uniq) {
  5414. if (decode_hex || decode_base64) {
  5415. if (digests_are_256) {
  5416. smartlist_sort_digests256(fp_tmp);
  5417. smartlist_uniq_digests256(fp_tmp);
  5418. } else {
  5419. smartlist_sort_digests(fp_tmp);
  5420. smartlist_uniq_digests(fp_tmp);
  5421. }
  5422. } else {
  5423. smartlist_sort_strings(fp_tmp);
  5424. smartlist_uniq_strings(fp_tmp);
  5425. }
  5426. }
  5427. smartlist_add_all(fp_out, fp_tmp);
  5428. smartlist_free(fp_tmp);
  5429. return 0;
  5430. }
  5431. /** As dir_split_resource_into_fingerprints, but instead fills
  5432. * <b>spool_out</b> with a list of spoolable_resource_t for the resource
  5433. * identified through <b>source</b>. */
  5434. int
  5435. dir_split_resource_into_spoolable(const char *resource,
  5436. dir_spool_source_t source,
  5437. smartlist_t *spool_out,
  5438. int *compressed_out,
  5439. int flags)
  5440. {
  5441. smartlist_t *fingerprints = smartlist_new();
  5442. tor_assert(flags & (DSR_HEX|DSR_BASE64));
  5443. const size_t digest_len =
  5444. (flags & DSR_DIGEST256) ? DIGEST256_LEN : DIGEST_LEN;
  5445. int r = dir_split_resource_into_fingerprints(resource, fingerprints,
  5446. compressed_out, flags);
  5447. /* This is not a very efficient implementation XXXX */
  5448. SMARTLIST_FOREACH_BEGIN(fingerprints, uint8_t *, digest) {
  5449. spooled_resource_t *spooled =
  5450. spooled_resource_new(source, digest, digest_len);
  5451. if (spooled)
  5452. smartlist_add(spool_out, spooled);
  5453. tor_free(digest);
  5454. } SMARTLIST_FOREACH_END(digest);
  5455. smartlist_free(fingerprints);
  5456. return r;
  5457. }