routerlist.c 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerlist.c
  8. * \brief Code to
  9. * maintain and access the global list of routerinfos for known
  10. * servers.
  11. **/
  12. #include "or.h"
  13. #include "circuitbuild.h"
  14. #include "config.h"
  15. #include "connection.h"
  16. #include "control.h"
  17. #include "directory.h"
  18. #include "dirserv.h"
  19. #include "dirvote.h"
  20. #include "geoip.h"
  21. #include "hibernate.h"
  22. #include "main.h"
  23. #include "microdesc.h"
  24. #include "networkstatus.h"
  25. #include "nodelist.h"
  26. #include "policies.h"
  27. #include "reasons.h"
  28. #include "rendcommon.h"
  29. #include "rendservice.h"
  30. #include "rephist.h"
  31. #include "router.h"
  32. #include "routerlist.h"
  33. #include "routerparse.h"
  34. // #define DEBUG_ROUTERLIST
  35. /****************************************************************************/
  36. /* static function prototypes */
  37. static const routerstatus_t *router_pick_directory_server_impl(
  38. authority_type_t auth, int flags);
  39. static const routerstatus_t *router_pick_trusteddirserver_impl(
  40. authority_type_t auth, int flags, int *n_busy_out);
  41. static void mark_all_trusteddirservers_up(void);
  42. static int router_nickname_matches(const routerinfo_t *router,
  43. const char *nickname);
  44. static int node_nickname_matches(const node_t *router,
  45. const char *nickname);
  46. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  47. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  48. static void update_router_have_minimum_dir_info(void);
  49. static const char *signed_descriptor_get_body_impl(
  50. const signed_descriptor_t *desc,
  51. int with_annotations);
  52. static void list_pending_downloads(digestmap_t *result,
  53. int purpose, const char *prefix);
  54. DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
  55. DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
  56. DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
  57. #define SDMAP_FOREACH(map, keyvar, valvar) \
  58. DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
  59. valvar)
  60. #define RIMAP_FOREACH(map, keyvar, valvar) \
  61. DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
  62. #define EIMAP_FOREACH(map, keyvar, valvar) \
  63. DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
  64. /****************************************************************************/
  65. /** Global list of a trusted_dir_server_t object for each trusted directory
  66. * server. */
  67. static smartlist_t *trusted_dir_servers = NULL;
  68. /** List of for a given authority, and download status for latest certificate.
  69. */
  70. typedef struct cert_list_t {
  71. download_status_t dl_status;
  72. smartlist_t *certs;
  73. } cert_list_t;
  74. /** Map from v3 identity key digest to cert_list_t. */
  75. static digestmap_t *trusted_dir_certs = NULL;
  76. /** True iff any key certificate in at least one member of
  77. * <b>trusted_dir_certs</b> has changed since we last flushed the
  78. * certificates to disk. */
  79. static int trusted_dir_servers_certs_changed = 0;
  80. /** Global list of all of the routers that we know about. */
  81. static routerlist_t *routerlist = NULL;
  82. /** List of strings for nicknames we've already warned about and that are
  83. * still unknown / unavailable. */
  84. static smartlist_t *warned_nicknames = NULL;
  85. /** The last time we tried to download any routerdesc, or 0 for "never". We
  86. * use this to rate-limit download attempts when the number of routerdescs to
  87. * download is low. */
  88. static time_t last_routerdesc_download_attempted = 0;
  89. /** When we last computed the weights to use for bandwidths on directory
  90. * requests, what were the total weighted bandwidth, and our share of that
  91. * bandwidth? Used to determine what fraction of directory requests we should
  92. * expect to see. */
  93. static uint64_t sl_last_total_weighted_bw = 0,
  94. sl_last_weighted_bw_of_me = 0;
  95. /** Return the number of directory authorities whose type matches some bit set
  96. * in <b>type</b> */
  97. int
  98. get_n_authorities(authority_type_t type)
  99. {
  100. int n = 0;
  101. if (!trusted_dir_servers)
  102. return 0;
  103. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  104. if (ds->type & type)
  105. ++n);
  106. return n;
  107. }
  108. #define get_n_v2_authorities() get_n_authorities(V2_AUTHORITY)
  109. /** Helper: Return the cert_list_t for an authority whose authority ID is
  110. * <b>id_digest</b>, allocating a new list if necessary. */
  111. static cert_list_t *
  112. get_cert_list(const char *id_digest)
  113. {
  114. cert_list_t *cl;
  115. if (!trusted_dir_certs)
  116. trusted_dir_certs = digestmap_new();
  117. cl = digestmap_get(trusted_dir_certs, id_digest);
  118. if (!cl) {
  119. cl = tor_malloc_zero(sizeof(cert_list_t));
  120. cl->dl_status.schedule = DL_SCHED_CONSENSUS;
  121. cl->certs = smartlist_create();
  122. digestmap_set(trusted_dir_certs, id_digest, cl);
  123. }
  124. return cl;
  125. }
  126. /** Reload the cached v3 key certificates from the cached-certs file in
  127. * the data directory. Return 0 on success, -1 on failure. */
  128. int
  129. trusted_dirs_reload_certs(void)
  130. {
  131. char *filename;
  132. char *contents;
  133. int r;
  134. filename = get_datadir_fname("cached-certs");
  135. contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  136. tor_free(filename);
  137. if (!contents)
  138. return 0;
  139. r = trusted_dirs_load_certs_from_string(contents, 1, 1);
  140. tor_free(contents);
  141. return r;
  142. }
  143. /** Helper: return true iff we already have loaded the exact cert
  144. * <b>cert</b>. */
  145. static INLINE int
  146. already_have_cert(authority_cert_t *cert)
  147. {
  148. cert_list_t *cl = get_cert_list(cert->cache_info.identity_digest);
  149. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  150. {
  151. if (!memcmp(c->cache_info.signed_descriptor_digest,
  152. cert->cache_info.signed_descriptor_digest,
  153. DIGEST_LEN))
  154. return 1;
  155. });
  156. return 0;
  157. }
  158. /** Load a bunch of new key certificates from the string <b>contents</b>. If
  159. * <b>from_store</b> is true, the certificates are from the cache, and we
  160. * don't need to flush them to disk. If <b>flush</b> is true, we need
  161. * to flush any changed certificates to disk now. Return 0 on success, -1
  162. * if any certs fail to parse. */
  163. int
  164. trusted_dirs_load_certs_from_string(const char *contents, int from_store,
  165. int flush)
  166. {
  167. trusted_dir_server_t *ds;
  168. const char *s, *eos;
  169. int failure_code = 0;
  170. for (s = contents; *s; s = eos) {
  171. authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
  172. cert_list_t *cl;
  173. if (!cert) {
  174. failure_code = -1;
  175. break;
  176. }
  177. ds = trusteddirserver_get_by_v3_auth_digest(
  178. cert->cache_info.identity_digest);
  179. log_debug(LD_DIR, "Parsed certificate for %s",
  180. ds ? ds->nickname : "unknown authority");
  181. if (already_have_cert(cert)) {
  182. /* we already have this one. continue. */
  183. log_info(LD_DIR, "Skipping %s certificate for %s that we "
  184. "already have.",
  185. from_store ? "cached" : "downloaded",
  186. ds ? ds->nickname : "an old or new authority");
  187. /* a duplicate on a download should be treated as a failure, since it
  188. * probably means we wanted a different secret key or we are trying to
  189. * replace an expired cert that has not in fact been updated. */
  190. if (!from_store) {
  191. log_warn(LD_DIR, "Got a certificate for %s, but we already have it. "
  192. "Maybe they haven't updated it. Waiting for a while.",
  193. ds ? ds->nickname : "an old or new authority");
  194. authority_cert_dl_failed(cert->cache_info.identity_digest, 404);
  195. }
  196. authority_cert_free(cert);
  197. continue;
  198. }
  199. if (ds) {
  200. log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
  201. "signing key %s", from_store ? "cached" : "downloaded",
  202. ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
  203. } else {
  204. int adding = directory_caches_dir_info(get_options());
  205. log_info(LD_DIR, "%s %s certificate for unrecognized directory "
  206. "authority with signing key %s",
  207. adding ? "Adding" : "Not adding",
  208. from_store ? "cached" : "downloaded",
  209. hex_str(cert->signing_key_digest,DIGEST_LEN));
  210. if (!adding) {
  211. authority_cert_free(cert);
  212. continue;
  213. }
  214. }
  215. cl = get_cert_list(cert->cache_info.identity_digest);
  216. smartlist_add(cl->certs, cert);
  217. if (ds && cert->cache_info.published_on > ds->addr_current_at) {
  218. /* Check to see whether we should update our view of the authority's
  219. * address. */
  220. if (cert->addr && cert->dir_port &&
  221. (ds->addr != cert->addr ||
  222. ds->dir_port != cert->dir_port)) {
  223. char *a = tor_dup_ip(cert->addr);
  224. log_notice(LD_DIR, "Updating address for directory authority %s "
  225. "from %s:%d to %s:%d based on certificate.",
  226. ds->nickname, ds->address, (int)ds->dir_port,
  227. a, cert->dir_port);
  228. tor_free(a);
  229. ds->addr = cert->addr;
  230. ds->dir_port = cert->dir_port;
  231. }
  232. ds->addr_current_at = cert->cache_info.published_on;
  233. }
  234. if (!from_store)
  235. trusted_dir_servers_certs_changed = 1;
  236. }
  237. if (flush)
  238. trusted_dirs_flush_certs_to_disk();
  239. /* call this even if failure_code is <0, since some certs might have
  240. * succeeded. */
  241. networkstatus_note_certs_arrived();
  242. return failure_code;
  243. }
  244. /** Save all v3 key certificates to the cached-certs file. */
  245. void
  246. trusted_dirs_flush_certs_to_disk(void)
  247. {
  248. char *filename;
  249. smartlist_t *chunks;
  250. if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
  251. return;
  252. chunks = smartlist_create();
  253. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  254. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  255. {
  256. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  257. c->bytes = cert->cache_info.signed_descriptor_body;
  258. c->len = cert->cache_info.signed_descriptor_len;
  259. smartlist_add(chunks, c);
  260. });
  261. } DIGESTMAP_FOREACH_END;
  262. filename = get_datadir_fname("cached-certs");
  263. if (write_chunks_to_file(filename, chunks, 0)) {
  264. log_warn(LD_FS, "Error writing certificates to disk.");
  265. }
  266. tor_free(filename);
  267. SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
  268. smartlist_free(chunks);
  269. trusted_dir_servers_certs_changed = 0;
  270. }
  271. /** Remove all v3 authority certificates that have been superseded for more
  272. * than 48 hours. (If the most recent cert was published more than 48 hours
  273. * ago, then we aren't going to get any consensuses signed with older
  274. * keys.) */
  275. static void
  276. trusted_dirs_remove_old_certs(void)
  277. {
  278. time_t now = time(NULL);
  279. #define DEAD_CERT_LIFETIME (2*24*60*60)
  280. #define OLD_CERT_LIFETIME (7*24*60*60)
  281. if (!trusted_dir_certs)
  282. return;
  283. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  284. authority_cert_t *newest = NULL;
  285. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  286. if (!newest || (cert->cache_info.published_on >
  287. newest->cache_info.published_on))
  288. newest = cert);
  289. if (newest) {
  290. const time_t newest_published = newest->cache_info.published_on;
  291. SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
  292. int expired;
  293. time_t cert_published;
  294. if (newest == cert)
  295. continue;
  296. expired = ftime_definitely_after(now, cert->expires);
  297. cert_published = cert->cache_info.published_on;
  298. /* Store expired certs for 48 hours after a newer arrives;
  299. */
  300. if (expired ?
  301. (newest_published + DEAD_CERT_LIFETIME < now) :
  302. (cert_published + OLD_CERT_LIFETIME < newest_published)) {
  303. SMARTLIST_DEL_CURRENT(cl->certs, cert);
  304. authority_cert_free(cert);
  305. trusted_dir_servers_certs_changed = 1;
  306. }
  307. } SMARTLIST_FOREACH_END(cert);
  308. }
  309. } DIGESTMAP_FOREACH_END;
  310. #undef OLD_CERT_LIFETIME
  311. trusted_dirs_flush_certs_to_disk();
  312. }
  313. /** Return the newest v3 authority certificate whose v3 authority identity key
  314. * has digest <b>id_digest</b>. Return NULL if no such authority is known,
  315. * or it has no certificate. */
  316. authority_cert_t *
  317. authority_cert_get_newest_by_id(const char *id_digest)
  318. {
  319. cert_list_t *cl;
  320. authority_cert_t *best = NULL;
  321. if (!trusted_dir_certs ||
  322. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  323. return NULL;
  324. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  325. {
  326. if (!best || cert->cache_info.published_on > best->cache_info.published_on)
  327. best = cert;
  328. });
  329. return best;
  330. }
  331. /** Return the newest v3 authority certificate whose directory signing key has
  332. * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
  333. */
  334. authority_cert_t *
  335. authority_cert_get_by_sk_digest(const char *sk_digest)
  336. {
  337. authority_cert_t *c;
  338. if (!trusted_dir_certs)
  339. return NULL;
  340. if ((c = get_my_v3_authority_cert()) &&
  341. !memcmp(c->signing_key_digest, sk_digest, DIGEST_LEN))
  342. return c;
  343. if ((c = get_my_v3_legacy_cert()) &&
  344. !memcmp(c->signing_key_digest, sk_digest, DIGEST_LEN))
  345. return c;
  346. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  347. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  348. {
  349. if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  350. return cert;
  351. });
  352. } DIGESTMAP_FOREACH_END;
  353. return NULL;
  354. }
  355. /** Return the v3 authority certificate with signing key matching
  356. * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
  357. * Return NULL if no such authority is known. */
  358. authority_cert_t *
  359. authority_cert_get_by_digests(const char *id_digest,
  360. const char *sk_digest)
  361. {
  362. cert_list_t *cl;
  363. if (!trusted_dir_certs ||
  364. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  365. return NULL;
  366. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  367. if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  368. return cert; );
  369. return NULL;
  370. }
  371. /** Add every known authority_cert_t to <b>certs_out</b>. */
  372. void
  373. authority_cert_get_all(smartlist_t *certs_out)
  374. {
  375. tor_assert(certs_out);
  376. if (!trusted_dir_certs)
  377. return;
  378. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  379. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  380. smartlist_add(certs_out, c));
  381. } DIGESTMAP_FOREACH_END;
  382. }
  383. /** Called when an attempt to download a certificate with the authority with
  384. * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
  385. * the failure, so we don't try again immediately. */
  386. void
  387. authority_cert_dl_failed(const char *id_digest, int status)
  388. {
  389. cert_list_t *cl;
  390. if (!trusted_dir_certs ||
  391. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  392. return;
  393. download_status_failed(&cl->dl_status, status);
  394. }
  395. /** Return true iff when we've been getting enough failures when trying to
  396. * download the certificate with ID digest <b>id_digest</b> that we're willing
  397. * to start bugging the user about it. */
  398. int
  399. authority_cert_dl_looks_uncertain(const char *id_digest)
  400. {
  401. #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
  402. cert_list_t *cl;
  403. int n_failures;
  404. if (!trusted_dir_certs ||
  405. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  406. return 0;
  407. n_failures = download_status_get_n_failures(&cl->dl_status);
  408. return n_failures >= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER;
  409. }
  410. /** How many times will we try to fetch a certificate before giving up? */
  411. #define MAX_CERT_DL_FAILURES 8
  412. /** Try to download any v3 authority certificates that we may be missing. If
  413. * <b>status</b> is provided, try to get all the ones that were used to sign
  414. * <b>status</b>. Additionally, try to have a non-expired certificate for
  415. * every V3 authority in trusted_dir_servers. Don't fetch certificates we
  416. * already have.
  417. **/
  418. void
  419. authority_certs_fetch_missing(networkstatus_t *status, time_t now)
  420. {
  421. digestmap_t *pending;
  422. authority_cert_t *cert;
  423. smartlist_t *missing_digests;
  424. char *resource = NULL;
  425. cert_list_t *cl;
  426. const int cache = directory_caches_dir_info(get_options());
  427. if (should_delay_dir_fetches(get_options()))
  428. return;
  429. pending = digestmap_new();
  430. missing_digests = smartlist_create();
  431. list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
  432. if (status) {
  433. SMARTLIST_FOREACH_BEGIN(status->voters, networkstatus_voter_info_t *,
  434. voter) {
  435. if (!smartlist_len(voter->sigs))
  436. continue; /* This authority never signed this consensus, so don't
  437. * go looking for a cert with key digest 0000000000. */
  438. if (!cache &&
  439. !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
  440. continue; /* We are not a cache, and we don't know this authority.*/
  441. cl = get_cert_list(voter->identity_digest);
  442. SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
  443. cert = authority_cert_get_by_digests(voter->identity_digest,
  444. sig->signing_key_digest);
  445. if (cert) {
  446. if (now < cert->expires)
  447. download_status_reset(&cl->dl_status);
  448. continue;
  449. }
  450. if (download_status_is_ready(&cl->dl_status, now,
  451. MAX_CERT_DL_FAILURES) &&
  452. !digestmap_get(pending, voter->identity_digest)) {
  453. log_notice(LD_DIR, "We're missing a certificate from authority "
  454. "with signing key %s: launching request.",
  455. hex_str(sig->signing_key_digest, DIGEST_LEN));
  456. smartlist_add(missing_digests, sig->identity_digest);
  457. }
  458. } SMARTLIST_FOREACH_END(sig);
  459. } SMARTLIST_FOREACH_END(voter);
  460. }
  461. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds) {
  462. int found = 0;
  463. if (!(ds->type & V3_AUTHORITY))
  464. continue;
  465. if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
  466. continue;
  467. cl = get_cert_list(ds->v3_identity_digest);
  468. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert, {
  469. if (!ftime_definitely_after(now, cert->expires)) {
  470. /* It's not expired, and we weren't looking for something to
  471. * verify a consensus with. Call it done. */
  472. download_status_reset(&cl->dl_status);
  473. found = 1;
  474. break;
  475. }
  476. });
  477. if (!found &&
  478. download_status_is_ready(&cl->dl_status, now,MAX_CERT_DL_FAILURES) &&
  479. !digestmap_get(pending, ds->v3_identity_digest)) {
  480. log_notice(LD_DIR, "No current certificate known for authority %s; "
  481. "launching request.", ds->nickname);
  482. smartlist_add(missing_digests, ds->v3_identity_digest);
  483. }
  484. } SMARTLIST_FOREACH_END(ds);
  485. if (!smartlist_len(missing_digests)) {
  486. goto done;
  487. } else {
  488. smartlist_t *fps = smartlist_create();
  489. smartlist_add(fps, tor_strdup("fp/"));
  490. SMARTLIST_FOREACH(missing_digests, const char *, d, {
  491. char *fp;
  492. if (digestmap_get(pending, d))
  493. continue;
  494. fp = tor_malloc(HEX_DIGEST_LEN+2);
  495. base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  496. fp[HEX_DIGEST_LEN] = '+';
  497. fp[HEX_DIGEST_LEN+1] = '\0';
  498. smartlist_add(fps, fp);
  499. });
  500. if (smartlist_len(fps) == 1) {
  501. /* we didn't add any: they were all pending */
  502. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  503. smartlist_free(fps);
  504. goto done;
  505. }
  506. resource = smartlist_join_strings(fps, "", 0, NULL);
  507. resource[strlen(resource)-1] = '\0';
  508. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  509. smartlist_free(fps);
  510. }
  511. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
  512. resource, PDS_RETRY_IF_NO_SERVERS);
  513. done:
  514. tor_free(resource);
  515. smartlist_free(missing_digests);
  516. digestmap_free(pending, NULL);
  517. }
  518. /* Router descriptor storage.
  519. *
  520. * Routerdescs are stored in a big file, named "cached-descriptors". As new
  521. * routerdescs arrive, we append them to a journal file named
  522. * "cached-descriptors.new".
  523. *
  524. * From time to time, we replace "cached-descriptors" with a new file
  525. * containing only the live, non-superseded descriptors, and clear
  526. * cached-routers.new.
  527. *
  528. * On startup, we read both files.
  529. */
  530. /** Helper: return 1 iff the router log is so big we want to rebuild the
  531. * store. */
  532. static int
  533. router_should_rebuild_store(desc_store_t *store)
  534. {
  535. if (store->store_len > (1<<16))
  536. return (store->journal_len > store->store_len / 2 ||
  537. store->bytes_dropped > store->store_len / 2);
  538. else
  539. return store->journal_len > (1<<15);
  540. }
  541. /** Return the desc_store_t in <b>rl</b> that should be used to store
  542. * <b>sd</b>. */
  543. static INLINE desc_store_t *
  544. desc_get_store(routerlist_t *rl, const signed_descriptor_t *sd)
  545. {
  546. if (sd->is_extrainfo)
  547. return &rl->extrainfo_store;
  548. else
  549. return &rl->desc_store;
  550. }
  551. /** Add the signed_descriptor_t in <b>desc</b> to the router
  552. * journal; change its saved_location to SAVED_IN_JOURNAL and set its
  553. * offset appropriately. */
  554. static int
  555. signed_desc_append_to_journal(signed_descriptor_t *desc,
  556. desc_store_t *store)
  557. {
  558. char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
  559. const char *body = signed_descriptor_get_body_impl(desc,1);
  560. size_t len = desc->signed_descriptor_len + desc->annotations_len;
  561. if (append_bytes_to_file(fname, body, len, 1)) {
  562. log_warn(LD_FS, "Unable to store router descriptor");
  563. tor_free(fname);
  564. return -1;
  565. }
  566. desc->saved_location = SAVED_IN_JOURNAL;
  567. tor_free(fname);
  568. desc->saved_offset = store->journal_len;
  569. store->journal_len += len;
  570. return 0;
  571. }
  572. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  573. * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
  574. * the signed_descriptor_t* in *<b>b</b>. */
  575. static int
  576. _compare_signed_descriptors_by_age(const void **_a, const void **_b)
  577. {
  578. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  579. return (int)(r1->published_on - r2->published_on);
  580. }
  581. #define RRS_FORCE 1
  582. #define RRS_DONT_REMOVE_OLD 2
  583. /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
  584. * <b>flags</b>, then atomically replace the saved router store with the
  585. * routers currently in our routerlist, and clear the journal. Unless
  586. * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
  587. * rebuilding the store. Return 0 on success, -1 on failure.
  588. */
  589. static int
  590. router_rebuild_store(int flags, desc_store_t *store)
  591. {
  592. smartlist_t *chunk_list = NULL;
  593. char *fname = NULL, *fname_tmp = NULL;
  594. int r = -1;
  595. off_t offset = 0;
  596. smartlist_t *signed_descriptors = NULL;
  597. int nocache=0;
  598. size_t total_expected_len = 0;
  599. int had_any;
  600. int force = flags & RRS_FORCE;
  601. if (!force && !router_should_rebuild_store(store)) {
  602. r = 0;
  603. goto done;
  604. }
  605. if (!routerlist) {
  606. r = 0;
  607. goto done;
  608. }
  609. if (store->type == EXTRAINFO_STORE)
  610. had_any = !eimap_isempty(routerlist->extra_info_map);
  611. else
  612. had_any = (smartlist_len(routerlist->routers)+
  613. smartlist_len(routerlist->old_routers))>0;
  614. /* Don't save deadweight. */
  615. if (!(flags & RRS_DONT_REMOVE_OLD))
  616. routerlist_remove_old_routers();
  617. log_info(LD_DIR, "Rebuilding %s cache", store->description);
  618. fname = get_datadir_fname(store->fname_base);
  619. fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
  620. chunk_list = smartlist_create();
  621. /* We sort the routers by age to enhance locality on disk. */
  622. signed_descriptors = smartlist_create();
  623. if (store->type == EXTRAINFO_STORE) {
  624. eimap_iter_t *iter;
  625. for (iter = eimap_iter_init(routerlist->extra_info_map);
  626. !eimap_iter_done(iter);
  627. iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
  628. const char *key;
  629. extrainfo_t *ei;
  630. eimap_iter_get(iter, &key, &ei);
  631. smartlist_add(signed_descriptors, &ei->cache_info);
  632. }
  633. } else {
  634. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  635. smartlist_add(signed_descriptors, sd));
  636. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  637. smartlist_add(signed_descriptors, &ri->cache_info));
  638. }
  639. smartlist_sort(signed_descriptors, _compare_signed_descriptors_by_age);
  640. /* Now, add the appropriate members to chunk_list */
  641. SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
  642. {
  643. sized_chunk_t *c;
  644. const char *body = signed_descriptor_get_body_impl(sd, 1);
  645. if (!body) {
  646. log_warn(LD_BUG, "No descriptor available for router.");
  647. goto done;
  648. }
  649. if (sd->do_not_cache) {
  650. ++nocache;
  651. continue;
  652. }
  653. c = tor_malloc(sizeof(sized_chunk_t));
  654. c->bytes = body;
  655. c->len = sd->signed_descriptor_len + sd->annotations_len;
  656. total_expected_len += c->len;
  657. smartlist_add(chunk_list, c);
  658. });
  659. if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
  660. log_warn(LD_FS, "Error writing router store to disk.");
  661. goto done;
  662. }
  663. /* Our mmap is now invalid. */
  664. if (store->mmap) {
  665. tor_munmap_file(store->mmap);
  666. store->mmap = NULL;
  667. }
  668. if (replace_file(fname_tmp, fname)<0) {
  669. log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
  670. goto done;
  671. }
  672. errno = 0;
  673. store->mmap = tor_mmap_file(fname);
  674. if (! store->mmap) {
  675. if (errno == ERANGE) {
  676. /* empty store.*/
  677. if (total_expected_len) {
  678. log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
  679. " but when we went to mmap it, it was empty!", fname);
  680. } else if (had_any) {
  681. log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
  682. "okay if we're just starting up after a long time. "
  683. "Otherwise, it's a bug.", fname);
  684. }
  685. } else {
  686. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  687. }
  688. }
  689. log_info(LD_DIR, "Reconstructing pointers into cache");
  690. offset = 0;
  691. SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
  692. {
  693. if (sd->do_not_cache)
  694. continue;
  695. sd->saved_location = SAVED_IN_CACHE;
  696. if (store->mmap) {
  697. tor_free(sd->signed_descriptor_body); // sets it to null
  698. sd->saved_offset = offset;
  699. }
  700. offset += sd->signed_descriptor_len + sd->annotations_len;
  701. signed_descriptor_get_body(sd); /* reconstruct and assert */
  702. });
  703. tor_free(fname);
  704. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  705. write_str_to_file(fname, "", 1);
  706. r = 0;
  707. store->store_len = (size_t) offset;
  708. store->journal_len = 0;
  709. store->bytes_dropped = 0;
  710. done:
  711. smartlist_free(signed_descriptors);
  712. tor_free(fname);
  713. tor_free(fname_tmp);
  714. if (chunk_list) {
  715. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  716. smartlist_free(chunk_list);
  717. }
  718. return r;
  719. }
  720. /** Helper: Reload a cache file and its associated journal, setting metadata
  721. * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
  722. * else reload the router descriptor store. */
  723. static int
  724. router_reload_router_list_impl(desc_store_t *store)
  725. {
  726. char *fname = NULL, *altname = NULL, *contents = NULL;
  727. struct stat st;
  728. int read_from_old_location = 0;
  729. int extrainfo = (store->type == EXTRAINFO_STORE);
  730. time_t now = time(NULL);
  731. store->journal_len = store->store_len = 0;
  732. fname = get_datadir_fname(store->fname_base);
  733. if (store->fname_alt_base)
  734. altname = get_datadir_fname(store->fname_alt_base);
  735. if (store->mmap) /* get rid of it first */
  736. tor_munmap_file(store->mmap);
  737. store->mmap = NULL;
  738. store->mmap = tor_mmap_file(fname);
  739. if (!store->mmap && altname && file_status(altname) == FN_FILE) {
  740. read_from_old_location = 1;
  741. log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
  742. "location %s.", fname, altname);
  743. if ((store->mmap = tor_mmap_file(altname)))
  744. read_from_old_location = 1;
  745. }
  746. if (altname && !read_from_old_location) {
  747. remove_file_if_very_old(altname, now);
  748. }
  749. if (store->mmap) {
  750. store->store_len = store->mmap->size;
  751. if (extrainfo)
  752. router_load_extrainfo_from_string(store->mmap->data,
  753. store->mmap->data+store->mmap->size,
  754. SAVED_IN_CACHE, NULL, 0);
  755. else
  756. router_load_routers_from_string(store->mmap->data,
  757. store->mmap->data+store->mmap->size,
  758. SAVED_IN_CACHE, NULL, 0, NULL);
  759. }
  760. tor_free(fname);
  761. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  762. if (file_status(fname) == FN_FILE)
  763. contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  764. if (read_from_old_location) {
  765. tor_free(altname);
  766. altname = get_datadir_fname_suffix(store->fname_alt_base, ".new");
  767. if (!contents)
  768. contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  769. else
  770. remove_file_if_very_old(altname, now);
  771. }
  772. if (contents) {
  773. if (extrainfo)
  774. router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
  775. NULL, 0);
  776. else
  777. router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
  778. NULL, 0, NULL);
  779. store->journal_len = (size_t) st.st_size;
  780. tor_free(contents);
  781. }
  782. tor_free(fname);
  783. tor_free(altname);
  784. if (store->journal_len || read_from_old_location) {
  785. /* Always clear the journal on startup.*/
  786. router_rebuild_store(RRS_FORCE, store);
  787. } else if (!extrainfo) {
  788. /* Don't cache expired routers. (This is in an else because
  789. * router_rebuild_store() also calls remove_old_routers().) */
  790. routerlist_remove_old_routers();
  791. }
  792. return 0;
  793. }
  794. /** Load all cached router descriptors and extra-info documents from the
  795. * store. Return 0 on success and -1 on failure.
  796. */
  797. int
  798. router_reload_router_list(void)
  799. {
  800. routerlist_t *rl = router_get_routerlist();
  801. if (router_reload_router_list_impl(&rl->desc_store))
  802. return -1;
  803. if (router_reload_router_list_impl(&rl->extrainfo_store))
  804. return -1;
  805. return 0;
  806. }
  807. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  808. * known trusted dirservers. Callers must not modify the list or its
  809. * contents.
  810. */
  811. smartlist_t *
  812. router_get_trusted_dir_servers(void)
  813. {
  814. if (!trusted_dir_servers)
  815. trusted_dir_servers = smartlist_create();
  816. return trusted_dir_servers;
  817. }
  818. /** Try to find a running dirserver that supports operations of <b>type</b>.
  819. *
  820. * If there are no running dirservers in our routerlist and the
  821. * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
  822. * as running again, and pick one.
  823. *
  824. * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
  825. * dirservers that we can't reach.
  826. *
  827. * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
  828. * (if we're a dirserver).
  829. *
  830. * Don't pick an authority if any non-authority is viable; try to avoid using
  831. * servers that have returned 503 recently.
  832. */
  833. const routerstatus_t *
  834. router_pick_directory_server(authority_type_t type, int flags)
  835. {
  836. const routerstatus_t *choice;
  837. if (get_options()->PreferTunneledDirConns)
  838. flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
  839. if (!routerlist)
  840. return NULL;
  841. choice = router_pick_directory_server_impl(type, flags);
  842. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  843. return choice;
  844. log_info(LD_DIR,
  845. "No reachable router entries for dirservers. "
  846. "Trying them all again.");
  847. /* mark all authdirservers as up again */
  848. mark_all_trusteddirservers_up();
  849. /* try again */
  850. choice = router_pick_directory_server_impl(type, flags);
  851. return choice;
  852. }
  853. /** Try to determine which fraction of v2 and v3 directory requests aimed at
  854. * caches will be sent to us. Set *<b>v2_share_out</b> and
  855. * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
  856. * expect to see, respectively. Return 0 on success, negative on failure. */
  857. int
  858. router_get_my_share_of_directory_requests(double *v2_share_out,
  859. double *v3_share_out)
  860. {
  861. const routerinfo_t *me = router_get_my_routerinfo();
  862. const routerstatus_t *rs;
  863. const int pds_flags = PDS_ALLOW_SELF|PDS_IGNORE_FASCISTFIREWALL;
  864. *v2_share_out = *v3_share_out = 0.0;
  865. if (!me)
  866. return -1;
  867. rs = router_get_consensus_status_by_id(me->cache_info.identity_digest);
  868. if (!rs)
  869. return -1;
  870. /* Calling for side effect */
  871. /* XXXX This is a bit of a kludge */
  872. if (rs->is_v2_dir) {
  873. sl_last_total_weighted_bw = 0;
  874. router_pick_directory_server(V2_AUTHORITY, pds_flags);
  875. if (sl_last_total_weighted_bw != 0) {
  876. *v2_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  877. U64_TO_DBL(sl_last_total_weighted_bw);
  878. }
  879. }
  880. if (rs->version_supports_v3_dir) {
  881. sl_last_total_weighted_bw = 0;
  882. router_pick_directory_server(V3_AUTHORITY, pds_flags);
  883. if (sl_last_total_weighted_bw != 0) {
  884. *v3_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  885. U64_TO_DBL(sl_last_total_weighted_bw);
  886. }
  887. }
  888. return 0;
  889. }
  890. /** Return the trusted_dir_server_t for the directory authority whose identity
  891. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  892. */
  893. trusted_dir_server_t *
  894. router_get_trusteddirserver_by_digest(const char *digest)
  895. {
  896. if (!trusted_dir_servers)
  897. return NULL;
  898. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  899. {
  900. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  901. return ds;
  902. });
  903. return NULL;
  904. }
  905. /** Return the trusted_dir_server_t for the directory authority whose
  906. * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
  907. * is known.
  908. */
  909. trusted_dir_server_t *
  910. trusteddirserver_get_by_v3_auth_digest(const char *digest)
  911. {
  912. if (!trusted_dir_servers)
  913. return NULL;
  914. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  915. {
  916. if (!memcmp(ds->v3_identity_digest, digest, DIGEST_LEN) &&
  917. (ds->type & V3_AUTHORITY))
  918. return ds;
  919. });
  920. return NULL;
  921. }
  922. /** Try to find a running trusted dirserver. Flags are as for
  923. * router_pick_directory_server.
  924. */
  925. const routerstatus_t *
  926. router_pick_trusteddirserver(authority_type_t type, int flags)
  927. {
  928. const routerstatus_t *choice;
  929. int busy = 0;
  930. if (get_options()->PreferTunneledDirConns)
  931. flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
  932. choice = router_pick_trusteddirserver_impl(type, flags, &busy);
  933. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  934. return choice;
  935. if (busy) {
  936. /* If the reason that we got no server is that servers are "busy",
  937. * we must be excluding good servers because we already have serverdesc
  938. * fetches with them. Do not mark down servers up because of this. */
  939. tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  940. PDS_NO_EXISTING_MICRODESC_FETCH)));
  941. return NULL;
  942. }
  943. log_info(LD_DIR,
  944. "No trusted dirservers are reachable. Trying them all again.");
  945. mark_all_trusteddirservers_up();
  946. return router_pick_trusteddirserver_impl(type, flags, NULL);
  947. }
  948. /** How long do we avoid using a directory server after it's given us a 503? */
  949. #define DIR_503_TIMEOUT (60*60)
  950. /** Pick a random running valid directory server/mirror from our
  951. * routerlist. Arguments are as for router_pick_directory_server(), except
  952. * that RETRY_IF_NO_SERVERS is ignored, and:
  953. *
  954. * If the _PDS_PREFER_TUNNELED_DIR_CONNS flag is set, prefer directory servers
  955. * that we can use with BEGINDIR.
  956. */
  957. static const routerstatus_t *
  958. router_pick_directory_server_impl(authority_type_t type, int flags)
  959. {
  960. const node_t *result;
  961. smartlist_t *direct, *tunnel;
  962. smartlist_t *trusted_direct, *trusted_tunnel;
  963. smartlist_t *overloaded_direct, *overloaded_tunnel;
  964. time_t now = time(NULL);
  965. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  966. int requireother = ! (flags & PDS_ALLOW_SELF);
  967. int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  968. int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
  969. if (!consensus)
  970. return NULL;
  971. direct = smartlist_create();
  972. tunnel = smartlist_create();
  973. trusted_direct = smartlist_create();
  974. trusted_tunnel = smartlist_create();
  975. overloaded_direct = smartlist_create();
  976. overloaded_tunnel = smartlist_create();
  977. /* Find all the running dirservers we know about. */
  978. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  979. int is_trusted;
  980. int is_overloaded;
  981. tor_addr_t addr;
  982. const routerstatus_t *status = node->rs;
  983. if (!status)
  984. continue;
  985. if (!node->is_running || !status->dir_port || !node->is_valid)
  986. continue;
  987. if (node->is_bad_directory)
  988. continue;
  989. if (requireother && router_digest_is_me(node->identity))
  990. continue;
  991. if (type & V3_AUTHORITY) {
  992. if (!(status->version_supports_v3_dir ||
  993. router_digest_is_trusted_dir_type(node->identity,
  994. V3_AUTHORITY)))
  995. continue;
  996. }
  997. is_trusted = router_digest_is_trusted_dir(node->identity);
  998. if ((type & V2_AUTHORITY) && !(node->rs->is_v2_dir || is_trusted))
  999. continue;
  1000. if ((type & EXTRAINFO_CACHE) &&
  1001. !router_supports_extrainfo(node->identity, 0))
  1002. continue;
  1003. /* XXXX IP6 proposal 118 */
  1004. tor_addr_from_ipv4h(&addr, node->rs->addr);
  1005. is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
  1006. if (prefer_tunnel &&
  1007. status->version_supports_begindir &&
  1008. (!fascistfirewall ||
  1009. fascist_firewall_allows_address_or(&addr, status->or_port)))
  1010. smartlist_add(is_trusted ? trusted_tunnel :
  1011. is_overloaded ? overloaded_tunnel : tunnel, (void*)node);
  1012. else if (!fascistfirewall ||
  1013. fascist_firewall_allows_address_dir(&addr, status->dir_port))
  1014. smartlist_add(is_trusted ? trusted_direct :
  1015. is_overloaded ? overloaded_direct : direct, (void*)node);
  1016. } SMARTLIST_FOREACH_END(node);
  1017. if (smartlist_len(tunnel)) {
  1018. result = node_sl_choose_by_bandwidth(tunnel, WEIGHT_FOR_DIR);
  1019. } else if (smartlist_len(overloaded_tunnel)) {
  1020. result = node_sl_choose_by_bandwidth(overloaded_tunnel,
  1021. WEIGHT_FOR_DIR);
  1022. } else if (smartlist_len(trusted_tunnel)) {
  1023. /* FFFF We don't distinguish between trusteds and overloaded trusteds
  1024. * yet. Maybe one day we should. */
  1025. /* FFFF We also don't load balance over authorities yet. I think this
  1026. * is a feature, but it could easily be a bug. -RD */
  1027. result = smartlist_choose(trusted_tunnel);
  1028. } else if (smartlist_len(direct)) {
  1029. result = node_sl_choose_by_bandwidth(direct, WEIGHT_FOR_DIR);
  1030. } else if (smartlist_len(overloaded_direct)) {
  1031. result = node_sl_choose_by_bandwidth(overloaded_direct,
  1032. WEIGHT_FOR_DIR);
  1033. } else {
  1034. result = smartlist_choose(trusted_direct);
  1035. }
  1036. smartlist_free(direct);
  1037. smartlist_free(tunnel);
  1038. smartlist_free(trusted_direct);
  1039. smartlist_free(trusted_tunnel);
  1040. smartlist_free(overloaded_direct);
  1041. smartlist_free(overloaded_tunnel);
  1042. return result ? result->rs : NULL;
  1043. }
  1044. /** Choose randomly from among the trusted dirservers that are up. Flags
  1045. * are as for router_pick_directory_server_impl().
  1046. */
  1047. static const routerstatus_t *
  1048. router_pick_trusteddirserver_impl(authority_type_t type, int flags,
  1049. int *n_busy_out)
  1050. {
  1051. smartlist_t *direct, *tunnel;
  1052. smartlist_t *overloaded_direct, *overloaded_tunnel;
  1053. const routerinfo_t *me = router_get_my_routerinfo();
  1054. const routerstatus_t *result;
  1055. time_t now = time(NULL);
  1056. const int requireother = ! (flags & PDS_ALLOW_SELF);
  1057. const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  1058. const int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
  1059. const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
  1060. const int no_microdesc_fetching =(flags & PDS_NO_EXISTING_MICRODESC_FETCH);
  1061. int n_busy = 0;
  1062. if (!trusted_dir_servers)
  1063. return NULL;
  1064. direct = smartlist_create();
  1065. tunnel = smartlist_create();
  1066. overloaded_direct = smartlist_create();
  1067. overloaded_tunnel = smartlist_create();
  1068. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, d)
  1069. {
  1070. int is_overloaded =
  1071. d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
  1072. tor_addr_t addr;
  1073. if (!d->is_running) continue;
  1074. if ((type & d->type) == 0)
  1075. continue;
  1076. if ((type & EXTRAINFO_CACHE) &&
  1077. !router_supports_extrainfo(d->digest, 1))
  1078. continue;
  1079. if (requireother && me && router_digest_is_me(d->digest))
  1080. continue;
  1081. /* XXXX IP6 proposal 118 */
  1082. tor_addr_from_ipv4h(&addr, d->addr);
  1083. if (no_serverdesc_fetching) {
  1084. if (connection_get_by_type_addr_port_purpose(
  1085. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_SERVERDESC)
  1086. || connection_get_by_type_addr_port_purpose(
  1087. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_EXTRAINFO)) {
  1088. //log_debug(LD_DIR, "We have an existing connection to fetch "
  1089. // "descriptor from %s; delaying",d->description);
  1090. ++n_busy;
  1091. continue;
  1092. }
  1093. }
  1094. if (no_microdesc_fetching) {
  1095. if (connection_get_by_type_addr_port_purpose(
  1096. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_MICRODESC)) {
  1097. ++n_busy;
  1098. continue;
  1099. }
  1100. }
  1101. if (prefer_tunnel &&
  1102. d->or_port &&
  1103. (!fascistfirewall ||
  1104. fascist_firewall_allows_address_or(&addr, d->or_port)))
  1105. smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
  1106. &d->fake_status);
  1107. else if (!fascistfirewall ||
  1108. fascist_firewall_allows_address_dir(&addr, d->dir_port))
  1109. smartlist_add(is_overloaded ? overloaded_direct : direct,
  1110. &d->fake_status);
  1111. }
  1112. SMARTLIST_FOREACH_END(d);
  1113. if (smartlist_len(tunnel)) {
  1114. result = smartlist_choose(tunnel);
  1115. } else if (smartlist_len(overloaded_tunnel)) {
  1116. result = smartlist_choose(overloaded_tunnel);
  1117. } else if (smartlist_len(direct)) {
  1118. result = smartlist_choose(direct);
  1119. } else {
  1120. result = smartlist_choose(overloaded_direct);
  1121. }
  1122. if (n_busy_out)
  1123. *n_busy_out = n_busy;
  1124. smartlist_free(direct);
  1125. smartlist_free(tunnel);
  1126. smartlist_free(overloaded_direct);
  1127. smartlist_free(overloaded_tunnel);
  1128. return result;
  1129. }
  1130. /** Go through and mark the authoritative dirservers as up. */
  1131. static void
  1132. mark_all_trusteddirservers_up(void)
  1133. {
  1134. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node, {
  1135. if (router_digest_is_trusted_dir(node->identity))
  1136. node->is_running = 1;
  1137. });
  1138. if (trusted_dir_servers) {
  1139. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  1140. {
  1141. routerstatus_t *rs;
  1142. dir->is_running = 1;
  1143. download_status_reset(&dir->v2_ns_dl_status);
  1144. rs = router_get_mutable_consensus_status_by_id(dir->digest);
  1145. if (rs) {
  1146. rs->last_dir_503_at = 0;
  1147. control_event_networkstatus_changed_single(rs);
  1148. }
  1149. });
  1150. }
  1151. router_dir_info_changed();
  1152. }
  1153. /** Return true iff r1 and r2 have the same address and OR port. */
  1154. int
  1155. routers_have_same_or_addr(const routerinfo_t *r1, const routerinfo_t *r2)
  1156. {
  1157. return r1->addr == r2->addr && r1->or_port == r2->or_port;
  1158. }
  1159. /** Reset all internal variables used to count failed downloads of network
  1160. * status objects. */
  1161. void
  1162. router_reset_status_download_failures(void)
  1163. {
  1164. mark_all_trusteddirservers_up();
  1165. }
  1166. /** Return true iff router1 and router2 have similar enough network addresses
  1167. * that we should treat them as being in the same family */
  1168. static INLINE int
  1169. addrs_in_same_network_family(const tor_addr_t *a1,
  1170. const tor_addr_t *a2)
  1171. {
  1172. /* XXXX MOVE ? */
  1173. return 0 == tor_addr_compare_masked(a1, a2, 16, CMP_SEMANTIC);
  1174. }
  1175. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  1176. * This is used to make sure we don't pick siblings in a single path,
  1177. * or pick more than one relay from a family for our entry guard list.
  1178. */
  1179. void
  1180. nodelist_add_node_family(smartlist_t *sl, const node_t *node)
  1181. {
  1182. /* XXXX MOVE */
  1183. const smartlist_t *all_nodes = nodelist_get_list();
  1184. const smartlist_t *declared_family;
  1185. or_options_t *options = get_options();
  1186. tor_assert(node);
  1187. declared_family = node_get_declared_family(node);
  1188. /* First, add any nodes with similar network addresses. */
  1189. if (options->EnforceDistinctSubnets) {
  1190. tor_addr_t node_addr;
  1191. node_get_addr(node, &node_addr);
  1192. SMARTLIST_FOREACH_BEGIN(all_nodes, const node_t *, node2) {
  1193. tor_addr_t a;
  1194. node_get_addr(node2, &a);
  1195. if (addrs_in_same_network_family(&a, &node_addr))
  1196. smartlist_add(sl, (void*)node2);
  1197. } SMARTLIST_FOREACH_END(node2);
  1198. }
  1199. /* Now, add all nodes in the declared_family of this node, if they
  1200. * also declare this node to be in their family. */
  1201. if (declared_family) {
  1202. /* Add every r such that router declares familyness with node, and node
  1203. * declares familyhood with router. */
  1204. SMARTLIST_FOREACH_BEGIN(declared_family, const char *, name) {
  1205. const node_t *node2;
  1206. const smartlist_t *family2;
  1207. if (!(node2 = node_get_by_nickname(name, 0)))
  1208. continue;
  1209. if (!(family2 = node_get_declared_family(node2)))
  1210. continue;
  1211. SMARTLIST_FOREACH_BEGIN(family2, const char *, name2) {
  1212. if (node_nickname_matches(node, name2)) {
  1213. smartlist_add(sl, (void*)node2);
  1214. break;
  1215. }
  1216. } SMARTLIST_FOREACH_END(name2);
  1217. } SMARTLIST_FOREACH_END(name);
  1218. }
  1219. /* If the user declared any families locally, honor those too. */
  1220. if (options->NodeFamilySets) {
  1221. SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
  1222. if (routerset_contains_node(rs, node)) {
  1223. routerset_get_all_nodes(sl, rs, 0);
  1224. }
  1225. });
  1226. }
  1227. }
  1228. /** Given a <b>router</b>, add every node_t in its family to <b>sl</b>.
  1229. *
  1230. * Note the type mismatch: This function takes a routerinfo, but adds nodes
  1231. * to the smartlist!
  1232. */
  1233. static void
  1234. routerlist_add_nodes_in_family(smartlist_t *sl, const routerinfo_t *router)
  1235. {
  1236. /* XXXX MOVE ? */
  1237. node_t fake_node;
  1238. const node_t *node = node_get_by_id(router->cache_info.identity_digest);;
  1239. if (node == NULL) {
  1240. memset(&fake_node, 0, sizeof(fake_node));
  1241. fake_node.ri = (routerinfo_t *)router;
  1242. memcpy(fake_node.identity, router->cache_info.identity_digest, DIGEST_LEN);
  1243. node = &fake_node;
  1244. }
  1245. nodelist_add_node_family(sl, node);
  1246. }
  1247. /** Return true iff <b>node</b> is named by some nickname in <b>lst</b>. */
  1248. static INLINE int
  1249. node_in_nickname_smartlist(const smartlist_t *lst, const node_t *node)
  1250. {
  1251. /* XXXX MOVE */
  1252. if (!lst) return 0;
  1253. SMARTLIST_FOREACH(lst, const char *, name, {
  1254. if (node_nickname_matches(node, name))
  1255. return 1;
  1256. });
  1257. return 0;
  1258. }
  1259. /** Return true iff r1 and r2 are in the same family, but not the same
  1260. * router. */
  1261. int
  1262. nodes_in_same_family(const node_t *node1, const node_t *node2)
  1263. {
  1264. /* XXXX MOVE */
  1265. or_options_t *options = get_options();
  1266. /* Are they in the same family because of their addresses? */
  1267. if (options->EnforceDistinctSubnets) {
  1268. tor_addr_t a1, a2;
  1269. node_get_addr(node1, &a1);
  1270. node_get_addr(node2, &a2);
  1271. if (addrs_in_same_network_family(&a1, &a2))
  1272. return 1;
  1273. }
  1274. /* Are they in the same family because the agree they are? */
  1275. {
  1276. const smartlist_t *f1, *f2;
  1277. f1 = node_get_declared_family(node1);
  1278. f2 = node_get_declared_family(node2);
  1279. if (f1 && f2 &&
  1280. node_in_nickname_smartlist(f1, node2) &&
  1281. node_in_nickname_smartlist(f2, node1))
  1282. return 1;
  1283. }
  1284. /* Are they in the same option because the user says they are? */
  1285. if (options->NodeFamilySets) {
  1286. SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
  1287. if (routerset_contains_node(rs, node1) &&
  1288. routerset_contains_node(rs, node2))
  1289. return 1;
  1290. });
  1291. }
  1292. return 0;
  1293. }
  1294. #if 0
  1295. /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
  1296. * see which nicknames in <b>list</b> name nodes we know about, and add
  1297. * the nodes for those routers to <b>sl</b>. If <b>must_be_running</b>,
  1298. * only include routers that we think are running.
  1299. * Warn if any non-Named routers are specified by nickname.
  1300. */
  1301. static void
  1302. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
  1303. int must_be_running)
  1304. { /*XXXX MOVE or Kill. */
  1305. /*XXXX this is only used in one place. Can we kill it?*/
  1306. const node_t *node;
  1307. const routerinfo_t *router;
  1308. smartlist_t *nickname_list;
  1309. int have_dir_info = router_have_minimum_dir_info();
  1310. if (!list)
  1311. return; /* nothing to do */
  1312. tor_assert(sl);
  1313. nickname_list = smartlist_create();
  1314. if (!warned_nicknames)
  1315. warned_nicknames = smartlist_create();
  1316. smartlist_split_string(nickname_list, list, ",",
  1317. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1318. SMARTLIST_FOREACH_BEGIN(nickname_list, const char *, nick) {
  1319. int warned;
  1320. if (!is_legal_nickname_or_hexdigest(nick)) {
  1321. log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
  1322. continue;
  1323. }
  1324. node = node_get_by_nickname(nick, 1);
  1325. router = node->ri;
  1326. warned = smartlist_string_isin(warned_nicknames, nick);
  1327. if (node) {
  1328. if (!must_be_running || node->is_running) {
  1329. smartlist_add(sl,(void*)node);
  1330. }
  1331. } else if (!router_get_consensus_status_by_nickname(nick,1)) {
  1332. if (!warned) {
  1333. log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
  1334. "Nickname list includes '%s' which isn't a known router.",nick);
  1335. smartlist_add(warned_nicknames, tor_strdup(nick));
  1336. }
  1337. }
  1338. } SMARTLIST_FOREACH_END(nick);
  1339. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  1340. smartlist_free(nickname_list);
  1341. }
  1342. #endif
  1343. /** Return 1 iff any member of the (possibly NULL) comma-separated list
  1344. * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
  1345. * return 0.
  1346. */
  1347. int
  1348. router_nickname_is_in_list(const routerinfo_t *router, const char *list)
  1349. {
  1350. smartlist_t *nickname_list;
  1351. int v = 0;
  1352. if (!list)
  1353. return 0; /* definitely not */
  1354. tor_assert(router);
  1355. nickname_list = smartlist_create();
  1356. smartlist_split_string(nickname_list, list, ",",
  1357. SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1358. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  1359. if (router_nickname_matches(router, cp)) {v=1;break;});
  1360. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  1361. smartlist_free(nickname_list);
  1362. return v;
  1363. }
  1364. /** Add every suitable node from our nodelist to <b>sl</b>, so that
  1365. * we can pick a node for a circuit.
  1366. */
  1367. static void
  1368. router_add_running_nodes_to_smartlist(smartlist_t *sl, int allow_invalid,
  1369. int need_uptime, int need_capacity,
  1370. int need_guard, int need_desc)
  1371. { /* XXXX MOVE */
  1372. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  1373. if (!node->is_running ||
  1374. (!node->is_valid && !allow_invalid))
  1375. continue;
  1376. if (need_desc && !(node->ri || (node->rs && node->md)))
  1377. continue;
  1378. if (node->ri && node->ri->purpose != ROUTER_PURPOSE_GENERAL)
  1379. continue;
  1380. if (node_is_unreliable(node, need_uptime, need_capacity, need_guard))
  1381. continue;
  1382. smartlist_add(sl, (void *)node);
  1383. } SMARTLIST_FOREACH_END(node);
  1384. }
  1385. /** Look through the routerlist until we find a router that has my key.
  1386. Return it. */
  1387. const routerinfo_t *
  1388. routerlist_find_my_routerinfo(void)
  1389. {
  1390. if (!routerlist)
  1391. return NULL;
  1392. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1393. {
  1394. if (router_is_me(router))
  1395. return router;
  1396. });
  1397. return NULL;
  1398. }
  1399. /** Find a router that's up, that has this IP address, and
  1400. * that allows exit to this address:port, or return NULL if there
  1401. * isn't a good one.
  1402. */
  1403. const node_t *
  1404. router_find_exact_exit_enclave(const char *address, uint16_t port)
  1405. {/*XXXX MOVE*/
  1406. uint32_t addr;
  1407. struct in_addr in;
  1408. tor_addr_t a;
  1409. if (!tor_inet_aton(address, &in))
  1410. return NULL; /* it's not an IP already */
  1411. addr = ntohl(in.s_addr);
  1412. tor_addr_from_ipv4h(&a, addr);
  1413. SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, {
  1414. if (node_get_addr_ipv4h(node) == addr &&
  1415. node->is_running &&
  1416. compare_tor_addr_to_node_policy(&a, port, node) ==
  1417. ADDR_POLICY_ACCEPTED)
  1418. return node;
  1419. });
  1420. return NULL;
  1421. }
  1422. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1423. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1424. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1425. * bandwidth.
  1426. * If <b>need_guard</b>, we require that the router is a possible entry guard.
  1427. */
  1428. int
  1429. node_is_unreliable(const node_t *node, int need_uptime,
  1430. int need_capacity, int need_guard)
  1431. {
  1432. if (need_uptime && !node->is_stable)
  1433. return 1;
  1434. if (need_capacity && !node->is_fast)
  1435. return 1;
  1436. if (need_guard && !node->is_possible_guard)
  1437. return 1;
  1438. return 0;
  1439. }
  1440. /** Return the smaller of the router's configured BandwidthRate
  1441. * and its advertised capacity. */
  1442. uint32_t
  1443. router_get_advertised_bandwidth(const routerinfo_t *router)
  1444. {
  1445. if (router->bandwidthcapacity < router->bandwidthrate)
  1446. return router->bandwidthcapacity;
  1447. return router->bandwidthrate;
  1448. }
  1449. /** Do not weight any declared bandwidth more than this much when picking
  1450. * routers by bandwidth. */
  1451. #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
  1452. /** Return the smaller of the router's configured BandwidthRate
  1453. * and its advertised capacity, capped by max-believe-bw. */
  1454. uint32_t
  1455. router_get_advertised_bandwidth_capped(const routerinfo_t *router)
  1456. {
  1457. uint32_t result = router->bandwidthcapacity;
  1458. if (result > router->bandwidthrate)
  1459. result = router->bandwidthrate;
  1460. if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
  1461. result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
  1462. return result;
  1463. }
  1464. /** When weighting bridges, enforce these values as lower and upper
  1465. * bound for believable bandwidth, because there is no way for us
  1466. * to verify a bridge's bandwidth currently. */
  1467. #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
  1468. #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
  1469. /** Return the smaller of the router's configured BandwidthRate
  1470. * and its advertised capacity, making sure to stay within the
  1471. * interval between bridge-min-believe-bw and
  1472. * bridge-max-believe-bw. */
  1473. static uint32_t
  1474. bridge_get_advertised_bandwidth_bounded(routerinfo_t *router)
  1475. {
  1476. uint32_t result = router->bandwidthcapacity;
  1477. if (result > router->bandwidthrate)
  1478. result = router->bandwidthrate;
  1479. if (result > BRIDGE_MAX_BELIEVABLE_BANDWIDTH)
  1480. result = BRIDGE_MAX_BELIEVABLE_BANDWIDTH;
  1481. else if (result < BRIDGE_MIN_BELIEVABLE_BANDWIDTH)
  1482. result = BRIDGE_MIN_BELIEVABLE_BANDWIDTH;
  1483. return result;
  1484. }
  1485. /** Return bw*1000, unless bw*1000 would overflow, in which case return
  1486. * INT32_MAX. */
  1487. static INLINE int32_t
  1488. kb_to_bytes(uint32_t bw)
  1489. {
  1490. return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
  1491. }
  1492. /** Helper function:
  1493. * choose a random element of smartlist <b>sl</b> of nodes, weighted by
  1494. * the advertised bandwidth of each element using the consensus
  1495. * bandwidth weights.
  1496. *
  1497. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1498. * nodes' bandwidth equally regardless of their Exit status, since there may
  1499. * be some in the list because they exit to obscure ports. If
  1500. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1501. * exit-node's bandwidth less depending on the smallness of the fraction of
  1502. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1503. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1504. * guards proportionally less.
  1505. */
  1506. static const node_t *
  1507. smartlist_choose_node_by_bandwidth_weights(smartlist_t *sl,
  1508. bandwidth_weight_rule_t rule)
  1509. {
  1510. int64_t weight_scale;
  1511. int64_t rand_bw;
  1512. double Wg = -1, Wm = -1, We = -1, Wd = -1;
  1513. double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
  1514. double weighted_bw = 0;
  1515. double *bandwidths;
  1516. double tmp = 0;
  1517. unsigned int i;
  1518. int have_unknown = 0; /* true iff sl contains element not in consensus. */
  1519. /* Can't choose exit and guard at same time */
  1520. tor_assert(rule == NO_WEIGHTING ||
  1521. rule == WEIGHT_FOR_EXIT ||
  1522. rule == WEIGHT_FOR_GUARD ||
  1523. rule == WEIGHT_FOR_MID ||
  1524. rule == WEIGHT_FOR_DIR);
  1525. if (smartlist_len(sl) == 0) {
  1526. log_info(LD_CIRC,
  1527. "Empty routerlist passed in to consensus weight node "
  1528. "selection for rule %s",
  1529. bandwidth_weight_rule_to_string(rule));
  1530. return NULL;
  1531. }
  1532. weight_scale = networkstatus_get_param(NULL, "bwweightscale",
  1533. BW_WEIGHT_SCALE);
  1534. if (rule == WEIGHT_FOR_GUARD) {
  1535. Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
  1536. Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
  1537. We = 0;
  1538. Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
  1539. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1540. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1541. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1542. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1543. } else if (rule == WEIGHT_FOR_MID) {
  1544. Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
  1545. Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
  1546. We = networkstatus_get_bw_weight(NULL, "Wme", -1);
  1547. Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
  1548. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1549. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1550. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1551. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1552. } else if (rule == WEIGHT_FOR_EXIT) {
  1553. // Guards CAN be exits if they have weird exit policies
  1554. // They are d then I guess...
  1555. We = networkstatus_get_bw_weight(NULL, "Wee", -1);
  1556. Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
  1557. Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
  1558. Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
  1559. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1560. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1561. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1562. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1563. } else if (rule == WEIGHT_FOR_DIR) {
  1564. We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
  1565. Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
  1566. Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
  1567. Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
  1568. Wgb = Wmb = Web = Wdb = weight_scale;
  1569. } else if (rule == NO_WEIGHTING) {
  1570. Wg = Wm = We = Wd = weight_scale;
  1571. Wgb = Wmb = Web = Wdb = weight_scale;
  1572. }
  1573. if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
  1574. || Web < 0) {
  1575. log_debug(LD_CIRC,
  1576. "Got negative bandwidth weights. Defaulting to old selection"
  1577. " algorithm.");
  1578. return NULL; // Use old algorithm.
  1579. }
  1580. Wg /= weight_scale;
  1581. Wm /= weight_scale;
  1582. We /= weight_scale;
  1583. Wd /= weight_scale;
  1584. Wgb /= weight_scale;
  1585. Wmb /= weight_scale;
  1586. Web /= weight_scale;
  1587. Wdb /= weight_scale;
  1588. bandwidths = tor_malloc_zero(sizeof(double)*smartlist_len(sl));
  1589. // Cycle through smartlist and total the bandwidth.
  1590. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1591. int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0, is_me = 0;
  1592. double weight = 1;
  1593. is_exit = node->is_exit;
  1594. is_guard = node->is_possible_guard;
  1595. is_dir = node_is_dir(node);
  1596. if (node->rs) {
  1597. if (!node->rs->has_bandwidth) {
  1598. tor_free(bandwidths);
  1599. /* This should never happen, unless all the authorites downgrade
  1600. * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
  1601. log_warn(LD_BUG,
  1602. "Consensus is not listing bandwidths. Defaulting back to "
  1603. "old router selection algorithm.");
  1604. return NULL;
  1605. }
  1606. this_bw = kb_to_bytes(node->rs->bandwidth);
  1607. } else if (node->ri) {
  1608. /* bridge or other descriptor not in our consensus */
  1609. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1610. have_unknown = 1;
  1611. } else {
  1612. /* We can't use this one. */
  1613. continue;
  1614. }
  1615. is_me = router_digest_is_me(node->identity);
  1616. if (is_guard && is_exit) {
  1617. weight = (is_dir ? Wdb*Wd : Wd);
  1618. } else if (is_guard) {
  1619. weight = (is_dir ? Wgb*Wg : Wg);
  1620. } else if (is_exit) {
  1621. weight = (is_dir ? Web*We : We);
  1622. } else { // middle
  1623. weight = (is_dir ? Wmb*Wm : Wm);
  1624. }
  1625. bandwidths[node_sl_idx] = weight*this_bw;
  1626. weighted_bw += weight*this_bw;
  1627. if (is_me)
  1628. sl_last_weighted_bw_of_me = weight*this_bw;
  1629. } SMARTLIST_FOREACH_END(node);
  1630. /* XXXX022 this is a kludge to expose these values. */
  1631. sl_last_total_weighted_bw = weighted_bw;
  1632. log_debug(LD_CIRC, "Choosing node for rule %s based on weights "
  1633. "Wg=%lf Wm=%lf We=%lf Wd=%lf with total bw %lf",
  1634. bandwidth_weight_rule_to_string(rule),
  1635. Wg, Wm, We, Wd, weighted_bw);
  1636. /* If there is no bandwidth, choose at random */
  1637. if (DBL_TO_U64(weighted_bw) == 0) {
  1638. /* Don't warn when using bridges/relays not in the consensus */
  1639. if (!have_unknown)
  1640. log_warn(LD_CIRC,
  1641. "Weighted bandwidth is %lf in node selection for rule %s",
  1642. weighted_bw, bandwidth_weight_rule_to_string(rule));
  1643. tor_free(bandwidths);
  1644. return smartlist_choose(sl);
  1645. }
  1646. rand_bw = crypto_rand_uint64(DBL_TO_U64(weighted_bw));
  1647. rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
  1648. * from 1 below. See bug 1203 for details. */
  1649. /* Last, count through sl until we get to the element we picked */
  1650. tmp = 0.0;
  1651. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1652. tmp += bandwidths[i];
  1653. if (tmp >= rand_bw)
  1654. break;
  1655. }
  1656. if (i == (unsigned)smartlist_len(sl)) {
  1657. /* This was once possible due to round-off error, but shouldn't be able
  1658. * to occur any longer. */
  1659. tor_fragile_assert();
  1660. --i;
  1661. log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
  1662. " which router we chose. Please tell the developers. "
  1663. "%lf " U64_FORMAT " %lf", tmp, U64_PRINTF_ARG(rand_bw),
  1664. weighted_bw);
  1665. }
  1666. tor_free(bandwidths);
  1667. return smartlist_get(sl, i);
  1668. }
  1669. /** Helper function:
  1670. * choose a random node_t element of smartlist <b>sl</b>, weighted by
  1671. * the advertised bandwidth of each element.
  1672. *
  1673. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1674. * nodes' bandwidth equally regardless of their Exit status, since there may
  1675. * be some in the list because they exit to obscure ports. If
  1676. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1677. * exit-node's bandwidth less depending on the smallness of the fraction of
  1678. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1679. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1680. * guards proportionally less.
  1681. */
  1682. static const node_t *
  1683. smartlist_choose_node_by_bandwidth(smartlist_t *sl,
  1684. bandwidth_weight_rule_t rule)
  1685. {
  1686. unsigned i;
  1687. int32_t *bandwidths;
  1688. int is_exit;
  1689. int is_guard;
  1690. uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
  1691. uint64_t total_nonguard_bw = 0, total_guard_bw = 0;
  1692. uint64_t rand_bw, tmp;
  1693. double exit_weight;
  1694. double guard_weight;
  1695. int n_unknown = 0;
  1696. bitarray_t *exit_bits;
  1697. bitarray_t *guard_bits;
  1698. int me_idx = -1;
  1699. // This function does not support WEIGHT_FOR_DIR
  1700. // or WEIGHT_FOR_MID
  1701. if (rule == WEIGHT_FOR_DIR || rule == WEIGHT_FOR_MID) {
  1702. rule = NO_WEIGHTING;
  1703. }
  1704. /* Can't choose exit and guard at same time */
  1705. tor_assert(rule == NO_WEIGHTING ||
  1706. rule == WEIGHT_FOR_EXIT ||
  1707. rule == WEIGHT_FOR_GUARD);
  1708. if (smartlist_len(sl) == 0) {
  1709. log_info(LD_CIRC,
  1710. "Empty routerlist passed in to old node selection for rule %s",
  1711. bandwidth_weight_rule_to_string(rule));
  1712. return NULL;
  1713. }
  1714. /* First count the total bandwidth weight, and make a list
  1715. * of each value. <0 means "unknown; no routerinfo." We use the
  1716. * bits of negative values to remember whether the router was fast (-x)&1
  1717. * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
  1718. bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
  1719. exit_bits = bitarray_init_zero(smartlist_len(sl));
  1720. guard_bits = bitarray_init_zero(smartlist_len(sl));
  1721. /* Iterate over all the routerinfo_t or routerstatus_t, and */
  1722. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1723. /* first, learn what bandwidth we think i has */
  1724. int is_known = 1;
  1725. int32_t flags = 0;
  1726. uint32_t this_bw = 0;
  1727. i = node_sl_idx;
  1728. if (router_digest_is_me(node->identity))
  1729. me_idx = node_sl_idx;
  1730. is_exit = node->is_exit;
  1731. is_guard = node->is_possible_guard;
  1732. if (node->rs) {
  1733. if (node->rs->has_bandwidth) {
  1734. this_bw = kb_to_bytes(node->rs->bandwidth);
  1735. } else { /* guess */
  1736. /* XXX022 once consensuses always list bandwidths, we can take
  1737. * this guessing business out. -RD */
  1738. is_known = 0;
  1739. flags = node->rs->is_fast ? 1 : 0;
  1740. flags |= is_exit ? 2 : 0;
  1741. flags |= is_guard ? 4 : 0;
  1742. }
  1743. } else if (node->ri) {
  1744. /* Must be a bridge if we're willing to use it */
  1745. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1746. }
  1747. if (is_exit)
  1748. bitarray_set(exit_bits, i);
  1749. if (is_guard)
  1750. bitarray_set(guard_bits, i);
  1751. if (is_known) {
  1752. bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
  1753. // XXX this is no longer true! We don't always cap the bw anymore. Can
  1754. // a consensus make us overflow?-sh
  1755. tor_assert(bandwidths[i] >= 0);
  1756. if (is_guard)
  1757. total_guard_bw += this_bw;
  1758. else
  1759. total_nonguard_bw += this_bw;
  1760. if (is_exit)
  1761. total_exit_bw += this_bw;
  1762. else
  1763. total_nonexit_bw += this_bw;
  1764. } else {
  1765. ++n_unknown;
  1766. bandwidths[node_sl_idx] = -flags;
  1767. }
  1768. } SMARTLIST_FOREACH_END(node);
  1769. /* Now, fill in the unknown values. */
  1770. if (n_unknown) {
  1771. int32_t avg_fast, avg_slow;
  1772. if (total_exit_bw+total_nonexit_bw) {
  1773. /* if there's some bandwidth, there's at least one known router,
  1774. * so no worries about div by 0 here */
  1775. int n_known = smartlist_len(sl)-n_unknown;
  1776. avg_fast = avg_slow = (int32_t)
  1777. ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
  1778. } else {
  1779. avg_fast = 40000;
  1780. avg_slow = 20000;
  1781. }
  1782. for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
  1783. int32_t bw = bandwidths[i];
  1784. if (bw>=0)
  1785. continue;
  1786. is_exit = ((-bw)&2);
  1787. is_guard = ((-bw)&4);
  1788. bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
  1789. if (is_exit)
  1790. total_exit_bw += bandwidths[i];
  1791. else
  1792. total_nonexit_bw += bandwidths[i];
  1793. if (is_guard)
  1794. total_guard_bw += bandwidths[i];
  1795. else
  1796. total_nonguard_bw += bandwidths[i];
  1797. }
  1798. }
  1799. /* If there's no bandwidth at all, pick at random. */
  1800. if (!(total_exit_bw+total_nonexit_bw)) {
  1801. tor_free(bandwidths);
  1802. tor_free(exit_bits);
  1803. tor_free(guard_bits);
  1804. return smartlist_choose(sl);
  1805. }
  1806. /* Figure out how to weight exits and guards */
  1807. {
  1808. double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
  1809. double exit_bw = U64_TO_DBL(total_exit_bw);
  1810. double guard_bw = U64_TO_DBL(total_guard_bw);
  1811. /*
  1812. * For detailed derivation of this formula, see
  1813. * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
  1814. */
  1815. if (rule == WEIGHT_FOR_EXIT || !total_exit_bw)
  1816. exit_weight = 1.0;
  1817. else
  1818. exit_weight = 1.0 - all_bw/(3.0*exit_bw);
  1819. if (rule == WEIGHT_FOR_GUARD || !total_guard_bw)
  1820. guard_weight = 1.0;
  1821. else
  1822. guard_weight = 1.0 - all_bw/(3.0*guard_bw);
  1823. if (exit_weight <= 0.0)
  1824. exit_weight = 0.0;
  1825. if (guard_weight <= 0.0)
  1826. guard_weight = 0.0;
  1827. total_bw = 0;
  1828. sl_last_weighted_bw_of_me = 0;
  1829. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1830. uint64_t bw;
  1831. is_exit = bitarray_is_set(exit_bits, i);
  1832. is_guard = bitarray_is_set(guard_bits, i);
  1833. if (is_exit && is_guard)
  1834. bw = ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
  1835. else if (is_guard)
  1836. bw = ((uint64_t)(bandwidths[i] * guard_weight));
  1837. else if (is_exit)
  1838. bw = ((uint64_t)(bandwidths[i] * exit_weight));
  1839. else
  1840. bw = bandwidths[i];
  1841. total_bw += bw;
  1842. if (i == (unsigned) me_idx)
  1843. sl_last_weighted_bw_of_me = bw;
  1844. }
  1845. }
  1846. /* XXXX022 this is a kludge to expose these values. */
  1847. sl_last_total_weighted_bw = total_bw;
  1848. log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
  1849. ", exit bw = "U64_FORMAT
  1850. ", nonexit bw = "U64_FORMAT", exit weight = %lf "
  1851. "(for exit == %d)"
  1852. ", guard bw = "U64_FORMAT
  1853. ", nonguard bw = "U64_FORMAT", guard weight = %lf "
  1854. "(for guard == %d)",
  1855. U64_PRINTF_ARG(total_bw),
  1856. U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
  1857. exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
  1858. U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
  1859. guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
  1860. /* Almost done: choose a random value from the bandwidth weights. */
  1861. rand_bw = crypto_rand_uint64(total_bw);
  1862. rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
  1863. * from 1 below. See bug 1203 for details. */
  1864. /* Last, count through sl until we get to the element we picked */
  1865. tmp = 0;
  1866. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1867. is_exit = bitarray_is_set(exit_bits, i);
  1868. is_guard = bitarray_is_set(guard_bits, i);
  1869. /* Weights can be 0 if not counting guards/exits */
  1870. if (is_exit && is_guard)
  1871. tmp += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
  1872. else if (is_guard)
  1873. tmp += ((uint64_t)(bandwidths[i] * guard_weight));
  1874. else if (is_exit)
  1875. tmp += ((uint64_t)(bandwidths[i] * exit_weight));
  1876. else
  1877. tmp += bandwidths[i];
  1878. if (tmp >= rand_bw)
  1879. break;
  1880. }
  1881. if (i == (unsigned)smartlist_len(sl)) {
  1882. /* This was once possible due to round-off error, but shouldn't be able
  1883. * to occur any longer. */
  1884. tor_fragile_assert();
  1885. --i;
  1886. log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
  1887. " which router we chose. Please tell the developers. "
  1888. U64_FORMAT " " U64_FORMAT " " U64_FORMAT, U64_PRINTF_ARG(tmp),
  1889. U64_PRINTF_ARG(rand_bw), U64_PRINTF_ARG(total_bw));
  1890. }
  1891. tor_free(bandwidths);
  1892. tor_free(exit_bits);
  1893. tor_free(guard_bits);
  1894. return smartlist_get(sl, i);
  1895. }
  1896. /** Choose a random element of status list <b>sl</b>, weighted by
  1897. * the advertised bandwidth of each node */
  1898. const node_t *
  1899. node_sl_choose_by_bandwidth(smartlist_t *sl,
  1900. bandwidth_weight_rule_t rule)
  1901. { /*XXXX MOVE */
  1902. const node_t *ret;
  1903. if ((ret = smartlist_choose_node_by_bandwidth_weights(sl, rule))) {
  1904. return ret;
  1905. } else {
  1906. return smartlist_choose_node_by_bandwidth(sl, rule);
  1907. }
  1908. }
  1909. /** Return a random running node from the nodelist. Never
  1910. * pick a node that is in
  1911. * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
  1912. * even if they are the only nodes available.
  1913. * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
  1914. * a minimum uptime, return one of those.
  1915. * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
  1916. * advertised capacity of each router.
  1917. * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
  1918. * routers.
  1919. * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
  1920. * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
  1921. * picking an exit node, otherwise we weight bandwidths for picking a relay
  1922. * node (that is, possibly discounting exit nodes).
  1923. * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
  1924. * have a routerinfo or microdescriptor -- that is, enough info to be
  1925. * used to build a circuit.
  1926. */
  1927. const node_t *
  1928. router_choose_random_node(smartlist_t *excludedsmartlist,
  1929. routerset_t *excludedset,
  1930. router_crn_flags_t flags)
  1931. { /* XXXX MOVE */
  1932. const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
  1933. const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
  1934. const int need_guard = (flags & CRN_NEED_GUARD) != 0;
  1935. const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
  1936. const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
  1937. const int need_desc = (flags & CRN_NEED_DESC) != 0;
  1938. smartlist_t *sl=smartlist_create(),
  1939. *excludednodes=smartlist_create();
  1940. const node_t *choice = NULL;
  1941. const routerinfo_t *r;
  1942. bandwidth_weight_rule_t rule;
  1943. tor_assert(!(weight_for_exit && need_guard));
  1944. rule = weight_for_exit ? WEIGHT_FOR_EXIT :
  1945. (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
  1946. /* Exclude relays that allow single hop exit circuits, if the user
  1947. * wants to (such relays might be risky) */
  1948. if (get_options()->ExcludeSingleHopRelays) {
  1949. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
  1950. if (node_allows_single_hop_exits(node)) {
  1951. smartlist_add(excludednodes, node);
  1952. });
  1953. }
  1954. if ((r = routerlist_find_my_routerinfo())) {
  1955. const node_t *me = node_get_by_id(r->cache_info.identity_digest);
  1956. if (me)
  1957. smartlist_add(excludednodes, (void *)me);
  1958. routerlist_add_nodes_in_family(excludednodes, r);
  1959. }
  1960. router_add_running_nodes_to_smartlist(sl, allow_invalid,
  1961. need_uptime, need_capacity,
  1962. need_guard, need_desc);
  1963. smartlist_subtract(sl,excludednodes);
  1964. if (excludedsmartlist)
  1965. smartlist_subtract(sl,excludedsmartlist);
  1966. if (excludedset)
  1967. routerset_subtract_nodes(sl,excludedset);
  1968. // Always weight by bandwidth
  1969. choice = node_sl_choose_by_bandwidth(sl, rule);
  1970. smartlist_free(sl);
  1971. if (!choice && (need_uptime || need_capacity || need_guard)) {
  1972. /* try once more -- recurse but with fewer restrictions. */
  1973. log_info(LD_CIRC,
  1974. "We couldn't find any live%s%s%s routers; falling back "
  1975. "to list of all routers.",
  1976. need_capacity?", fast":"",
  1977. need_uptime?", stable":"",
  1978. need_guard?", guard":"");
  1979. flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
  1980. choice = router_choose_random_node(
  1981. excludedsmartlist, excludedset, flags);
  1982. }
  1983. smartlist_free(excludednodes);
  1984. if (!choice) {
  1985. log_warn(LD_CIRC,
  1986. "No available nodes when trying to choose node. Failing.");
  1987. }
  1988. return choice;
  1989. }
  1990. /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
  1991. * Return 0 on success, -1 on failure. Store the result into the
  1992. * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
  1993. * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
  1994. * at <b>nickname_out</b>.
  1995. *
  1996. * The recognized format is:
  1997. * HexName = Dollar? HexDigest NamePart?
  1998. * Dollar = '?'
  1999. * HexDigest = HexChar*20
  2000. * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
  2001. * NamePart = QualChar Name
  2002. * QualChar = '=' | '~'
  2003. * Name = NameChar*(1..MAX_NICKNAME_LEN)
  2004. * NameChar = Any ASCII alphanumeric character
  2005. */
  2006. int
  2007. hex_digest_nickname_decode(const char *hexdigest,
  2008. char *digest_out,
  2009. char *nickname_qualifier_char_out,
  2010. char *nickname_out)
  2011. {
  2012. size_t len;
  2013. tor_assert(hexdigest);
  2014. if (hexdigest[0] == '$')
  2015. ++hexdigest;
  2016. len = strlen(hexdigest);
  2017. if (len < HEX_DIGEST_LEN) {
  2018. return -1;
  2019. } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
  2020. hexdigest[HEX_DIGEST_LEN] == '~') &&
  2021. len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
  2022. *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
  2023. strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
  2024. } else if (len == HEX_DIGEST_LEN) {
  2025. ;
  2026. } else {
  2027. return -1;
  2028. }
  2029. if (base16_decode(digest_out, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  2030. return -1;
  2031. return 0;
  2032. }
  2033. /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
  2034. * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
  2035. * (which is optionally prefixed with a single dollar sign). Return false if
  2036. * <b>hexdigest</b> is malformed, or it doesn't match. */
  2037. static int
  2038. hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest,
  2039. const char *nickname, int is_named)
  2040. {
  2041. char digest[DIGEST_LEN];
  2042. char nn_char='\0';
  2043. char nn_buf[MAX_NICKNAME_LEN+1];
  2044. if (hex_digest_nickname_decode(hexdigest, digest, &nn_char, nn_buf) == -1)
  2045. return 0;
  2046. if (nn_char == '=' || nn_char == '~') {
  2047. if (strcasecmp(nn_buf, nickname))
  2048. return 0;
  2049. if (nn_char == '=' && !is_named)
  2050. return 0;
  2051. }
  2052. return !memcmp(digest, identity_digest, DIGEST_LEN);
  2053. }
  2054. /* Return true iff <b>router</b> is listed as named in the current
  2055. * consensus. */
  2056. static int
  2057. router_is_named(const routerinfo_t *router)
  2058. {
  2059. const char *digest =
  2060. networkstatus_get_router_digest_by_nickname(router->nickname);
  2061. return (digest &&
  2062. !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
  2063. }
  2064. /** Return true iff the digest of <b>router</b>'s identity key,
  2065. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  2066. * optionally prefixed with a single dollar sign). Return false if
  2067. * <b>hexdigest</b> is malformed, or it doesn't match. */
  2068. static INLINE int
  2069. router_hex_digest_matches(const routerinfo_t *router, const char *hexdigest)
  2070. {
  2071. return hex_digest_nickname_matches(hexdigest,
  2072. router->cache_info.identity_digest,
  2073. router->nickname,
  2074. router_is_named(router));
  2075. }
  2076. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  2077. * (case-insensitive), or if <b>router's</b> identity key digest
  2078. * matches a hexadecimal value stored in <b>nickname</b>. Return
  2079. * false otherwise. */
  2080. static int
  2081. router_nickname_matches(const routerinfo_t *router, const char *nickname)
  2082. {
  2083. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  2084. return 1;
  2085. return router_hex_digest_matches(router, nickname);
  2086. }
  2087. /** Return true if <b>node</b>'s nickname matches <b>nickname</b>
  2088. * (case-insensitive), or if <b>node's</b> identity key digest
  2089. * matches a hexadecimal value stored in <b>nickname</b>. Return
  2090. * false otherwise. */
  2091. static int
  2092. node_nickname_matches(const node_t *node, const char *nickname)
  2093. {
  2094. const char *n = node_get_nickname(node);
  2095. if (n && nickname[0]!='$' && !strcasecmp(n, nickname))
  2096. return 1;
  2097. return hex_digest_nickname_matches(nickname,
  2098. node->identity,
  2099. n,
  2100. node_is_named(node));
  2101. }
  2102. /** Return the router in our routerlist whose (case-insensitive)
  2103. * nickname or (case-sensitive) hexadecimal key digest is
  2104. * <b>nickname</b>. Return NULL if no such router is known.
  2105. */
  2106. const routerinfo_t *
  2107. router_get_by_nickname(const char *nickname, int warn_if_unnamed)
  2108. {
  2109. #if 1
  2110. const node_t *node = node_get_by_nickname(nickname, warn_if_unnamed);
  2111. if (node)
  2112. return node->ri;
  2113. else
  2114. return NULL;
  2115. #else
  2116. int maybedigest;
  2117. char digest[DIGEST_LEN];
  2118. routerinfo_t *best_match=NULL;
  2119. int n_matches = 0;
  2120. const char *named_digest = NULL;
  2121. tor_assert(nickname);
  2122. if (!routerlist)
  2123. return NULL;
  2124. if (nickname[0] == '$')
  2125. return router_get_by_hexdigest(nickname);
  2126. if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
  2127. return NULL;
  2128. if (server_mode(get_options()) &&
  2129. !strcasecmp(nickname, get_options()->Nickname))
  2130. return router_get_my_routerinfo();
  2131. maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
  2132. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  2133. if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
  2134. return rimap_get(routerlist->identity_map, named_digest);
  2135. }
  2136. if (networkstatus_nickname_is_unnamed(nickname))
  2137. return NULL;
  2138. /* If we reach this point, there's no canonical value for the nickname. */
  2139. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  2140. {
  2141. if (!strcasecmp(router->nickname, nickname)) {
  2142. ++n_matches;
  2143. if (n_matches <= 1 || router->is_running)
  2144. best_match = router;
  2145. } else if (maybedigest &&
  2146. !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
  2147. ) {
  2148. if (router_hex_digest_matches(router, nickname))
  2149. return router;
  2150. /* If we reach this point, we have a ID=name syntax that matches the
  2151. * identity but not the name. That isn't an acceptable match. */
  2152. }
  2153. });
  2154. if (best_match) {
  2155. if (warn_if_unnamed && n_matches > 1) {
  2156. smartlist_t *fps = smartlist_create();
  2157. int any_unwarned = 0;
  2158. SMARTLIST_FOREACH_BEGIN(routerlist->routers, routerinfo_t *, router) {
  2159. routerstatus_t *rs;
  2160. char *desc;
  2161. size_t dlen;
  2162. char fp[HEX_DIGEST_LEN+1];
  2163. if (strcasecmp(router->nickname, nickname))
  2164. continue;
  2165. rs = router_get_mutable_consensus_status_by_id(
  2166. router->cache_info.identity_digest);
  2167. if (rs && !rs->name_lookup_warned) {
  2168. rs->name_lookup_warned = 1;
  2169. any_unwarned = 1;
  2170. }
  2171. base16_encode(fp, sizeof(fp),
  2172. router->cache_info.identity_digest, DIGEST_LEN);
  2173. dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
  2174. desc = tor_malloc(dlen);
  2175. tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
  2176. fp, router->address, router->or_port);
  2177. smartlist_add(fps, desc);
  2178. } SMARTLIST_FOREACH_END(router);
  2179. if (any_unwarned) {
  2180. char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
  2181. log_warn(LD_CONFIG,
  2182. "There are multiple matches for the nickname \"%s\","
  2183. " but none is listed as named by the directory authorities. "
  2184. "Choosing one arbitrarily. If you meant one in particular, "
  2185. "you should say %s.", nickname, alternatives);
  2186. tor_free(alternatives);
  2187. }
  2188. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  2189. smartlist_free(fps);
  2190. } else if (warn_if_unnamed) {
  2191. routerstatus_t *rs = router_get_mutable_consensus_status_by_id(
  2192. best_match->cache_info.identity_digest);
  2193. if (rs && !rs->name_lookup_warned) {
  2194. char fp[HEX_DIGEST_LEN+1];
  2195. base16_encode(fp, sizeof(fp),
  2196. best_match->cache_info.identity_digest, DIGEST_LEN);
  2197. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
  2198. "name is not registered, so it could be used by any server, "
  2199. "not just the one you meant. "
  2200. "To make sure you get the same server in the future, refer to "
  2201. "it by key, as \"$%s\".", nickname, fp);
  2202. rs->name_lookup_warned = 1;
  2203. }
  2204. }
  2205. return best_match;
  2206. }
  2207. return NULL;
  2208. #endif
  2209. }
  2210. /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
  2211. * return 1. If we do, ask tor_version_as_new_as() for the answer.
  2212. */
  2213. int
  2214. router_digest_version_as_new_as(const char *digest, const char *cutoff)
  2215. {
  2216. const routerinfo_t *router = router_get_by_id_digest(digest);
  2217. if (!router)
  2218. return 1;
  2219. return tor_version_as_new_as(router->platform, cutoff);
  2220. }
  2221. /** Return true iff <b>digest</b> is the digest of the identity key of a
  2222. * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
  2223. * is zero, any authority is okay. */
  2224. int
  2225. router_digest_is_trusted_dir_type(const char *digest, authority_type_t type)
  2226. {
  2227. if (!trusted_dir_servers)
  2228. return 0;
  2229. if (authdir_mode(get_options()) && router_digest_is_me(digest))
  2230. return 1;
  2231. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2232. if (!memcmp(digest, ent->digest, DIGEST_LEN)) {
  2233. return (!type) || ((type & ent->type) != 0);
  2234. });
  2235. return 0;
  2236. }
  2237. /** Return true iff <b>addr</b> is the address of one of our trusted
  2238. * directory authorities. */
  2239. int
  2240. router_addr_is_trusted_dir(uint32_t addr)
  2241. {
  2242. if (!trusted_dir_servers)
  2243. return 0;
  2244. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2245. if (ent->addr == addr)
  2246. return 1;
  2247. );
  2248. return 0;
  2249. }
  2250. /** If hexdigest is correctly formed, base16_decode it into
  2251. * digest, which must have DIGEST_LEN space in it.
  2252. * Return 0 on success, -1 on failure.
  2253. */
  2254. int
  2255. hexdigest_to_digest(const char *hexdigest, char *digest)
  2256. {
  2257. if (hexdigest[0]=='$')
  2258. ++hexdigest;
  2259. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  2260. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  2261. return -1;
  2262. return 0;
  2263. }
  2264. /** Return the router in our routerlist whose hexadecimal key digest
  2265. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  2266. const routerinfo_t *
  2267. router_get_by_hexdigest(const char *hexdigest)
  2268. {
  2269. if (is_legal_nickname(hexdigest))
  2270. return NULL;
  2271. /* It's not a legal nickname, so it must be a hexdigest or nothing. */
  2272. return router_get_by_nickname(hexdigest, 1);
  2273. }
  2274. /** As router_get_by_id_digest,but return a pointer that you're allowed to
  2275. * modify */
  2276. routerinfo_t *
  2277. router_get_mutable_by_digest(const char *digest)
  2278. {
  2279. tor_assert(digest);
  2280. if (!routerlist) return NULL;
  2281. // routerlist_assert_ok(routerlist);
  2282. return rimap_get(routerlist->identity_map, digest);
  2283. }
  2284. /** Return the router in our routerlist whose 20-byte key digest
  2285. * is <b>digest</b>. Return NULL if no such router is known. */
  2286. const routerinfo_t *
  2287. router_get_by_id_digest(const char *digest)
  2288. {
  2289. return router_get_mutable_by_digest(digest);
  2290. }
  2291. /** Return the router in our routerlist whose 20-byte descriptor
  2292. * is <b>digest</b>. Return NULL if no such router is known. */
  2293. signed_descriptor_t *
  2294. router_get_by_descriptor_digest(const char *digest)
  2295. {
  2296. tor_assert(digest);
  2297. if (!routerlist) return NULL;
  2298. return sdmap_get(routerlist->desc_digest_map, digest);
  2299. }
  2300. /** Return the signed descriptor for the router in our routerlist whose
  2301. * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
  2302. * is known. */
  2303. signed_descriptor_t *
  2304. router_get_by_extrainfo_digest(const char *digest)
  2305. {
  2306. tor_assert(digest);
  2307. if (!routerlist) return NULL;
  2308. return sdmap_get(routerlist->desc_by_eid_map, digest);
  2309. }
  2310. /** Return the signed descriptor for the extrainfo_t in our routerlist whose
  2311. * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
  2312. * document is known. */
  2313. signed_descriptor_t *
  2314. extrainfo_get_by_descriptor_digest(const char *digest)
  2315. {
  2316. extrainfo_t *ei;
  2317. tor_assert(digest);
  2318. if (!routerlist) return NULL;
  2319. ei = eimap_get(routerlist->extra_info_map, digest);
  2320. return ei ? &ei->cache_info : NULL;
  2321. }
  2322. /** Return a pointer to the signed textual representation of a descriptor.
  2323. * The returned string is not guaranteed to be NUL-terminated: the string's
  2324. * length will be in desc-\>signed_descriptor_len.
  2325. *
  2326. * If <b>with_annotations</b> is set, the returned string will include
  2327. * the annotations
  2328. * (if any) preceding the descriptor. This will increase the length of the
  2329. * string by desc-\>annotations_len.
  2330. *
  2331. * The caller must not free the string returned.
  2332. */
  2333. static const char *
  2334. signed_descriptor_get_body_impl(const signed_descriptor_t *desc,
  2335. int with_annotations)
  2336. {
  2337. const char *r = NULL;
  2338. size_t len = desc->signed_descriptor_len;
  2339. off_t offset = desc->saved_offset;
  2340. if (with_annotations)
  2341. len += desc->annotations_len;
  2342. else
  2343. offset += desc->annotations_len;
  2344. tor_assert(len > 32);
  2345. if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
  2346. desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
  2347. if (store && store->mmap) {
  2348. tor_assert(desc->saved_offset + len <= store->mmap->size);
  2349. r = store->mmap->data + offset;
  2350. } else if (store) {
  2351. log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
  2352. "mmaped in our cache. Is another process running in our data "
  2353. "directory? Exiting.");
  2354. exit(1);
  2355. }
  2356. }
  2357. if (!r) /* no mmap, or not in cache. */
  2358. r = desc->signed_descriptor_body +
  2359. (with_annotations ? 0 : desc->annotations_len);
  2360. tor_assert(r);
  2361. if (!with_annotations) {
  2362. if (memcmp("router ", r, 7) && memcmp("extra-info ", r, 11)) {
  2363. char *cp = tor_strndup(r, 64);
  2364. log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
  2365. "Is another process running in our data directory? Exiting.",
  2366. desc, escaped(cp));
  2367. exit(1);
  2368. }
  2369. }
  2370. return r;
  2371. }
  2372. /** Return a pointer to the signed textual representation of a descriptor.
  2373. * The returned string is not guaranteed to be NUL-terminated: the string's
  2374. * length will be in desc-\>signed_descriptor_len.
  2375. *
  2376. * The caller must not free the string returned.
  2377. */
  2378. const char *
  2379. signed_descriptor_get_body(const signed_descriptor_t *desc)
  2380. {
  2381. return signed_descriptor_get_body_impl(desc, 0);
  2382. }
  2383. /** As signed_descriptor_get_body(), but points to the beginning of the
  2384. * annotations section rather than the beginning of the descriptor. */
  2385. const char *
  2386. signed_descriptor_get_annotations(const signed_descriptor_t *desc)
  2387. {
  2388. return signed_descriptor_get_body_impl(desc, 1);
  2389. }
  2390. /** Return the current list of all known routers. */
  2391. routerlist_t *
  2392. router_get_routerlist(void)
  2393. {
  2394. if (PREDICT_UNLIKELY(!routerlist)) {
  2395. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  2396. routerlist->routers = smartlist_create();
  2397. routerlist->old_routers = smartlist_create();
  2398. routerlist->identity_map = rimap_new();
  2399. routerlist->desc_digest_map = sdmap_new();
  2400. routerlist->desc_by_eid_map = sdmap_new();
  2401. routerlist->extra_info_map = eimap_new();
  2402. routerlist->desc_store.fname_base = "cached-descriptors";
  2403. routerlist->desc_store.fname_alt_base = "cached-routers";
  2404. routerlist->extrainfo_store.fname_base = "cached-extrainfo";
  2405. routerlist->desc_store.type = ROUTER_STORE;
  2406. routerlist->extrainfo_store.type = EXTRAINFO_STORE;
  2407. routerlist->desc_store.description = "router descriptors";
  2408. routerlist->extrainfo_store.description = "extra-info documents";
  2409. }
  2410. return routerlist;
  2411. }
  2412. /** Free all storage held by <b>router</b>. */
  2413. void
  2414. routerinfo_free(routerinfo_t *router)
  2415. {
  2416. if (!router)
  2417. return;
  2418. tor_free(router->cache_info.signed_descriptor_body);
  2419. tor_free(router->address);
  2420. tor_free(router->nickname);
  2421. tor_free(router->platform);
  2422. tor_free(router->contact_info);
  2423. if (router->onion_pkey)
  2424. crypto_free_pk_env(router->onion_pkey);
  2425. if (router->identity_pkey)
  2426. crypto_free_pk_env(router->identity_pkey);
  2427. if (router->declared_family) {
  2428. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  2429. smartlist_free(router->declared_family);
  2430. }
  2431. addr_policy_list_free(router->exit_policy);
  2432. /* XXXX Remove if this turns out to affect performance. */
  2433. memset(router, 77, sizeof(routerinfo_t));
  2434. tor_free(router);
  2435. }
  2436. /** Release all storage held by <b>extrainfo</b> */
  2437. void
  2438. extrainfo_free(extrainfo_t *extrainfo)
  2439. {
  2440. if (!extrainfo)
  2441. return;
  2442. tor_free(extrainfo->cache_info.signed_descriptor_body);
  2443. tor_free(extrainfo->pending_sig);
  2444. /* XXXX remove this if it turns out to slow us down. */
  2445. memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  2446. tor_free(extrainfo);
  2447. }
  2448. /** Release storage held by <b>sd</b>. */
  2449. static void
  2450. signed_descriptor_free(signed_descriptor_t *sd)
  2451. {
  2452. if (!sd)
  2453. return;
  2454. tor_free(sd->signed_descriptor_body);
  2455. /* XXXX remove this once more bugs go away. */
  2456. memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
  2457. tor_free(sd);
  2458. }
  2459. /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
  2460. */
  2461. static signed_descriptor_t *
  2462. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  2463. {
  2464. signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  2465. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  2466. sd->routerlist_index = -1;
  2467. ri->cache_info.signed_descriptor_body = NULL;
  2468. routerinfo_free(ri);
  2469. return sd;
  2470. }
  2471. /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
  2472. static void
  2473. _extrainfo_free(void *e)
  2474. {
  2475. extrainfo_free(e);
  2476. }
  2477. /** Free all storage held by a routerlist <b>rl</b>. */
  2478. void
  2479. routerlist_free(routerlist_t *rl)
  2480. {
  2481. if (!rl)
  2482. return;
  2483. rimap_free(rl->identity_map, NULL);
  2484. sdmap_free(rl->desc_digest_map, NULL);
  2485. sdmap_free(rl->desc_by_eid_map, NULL);
  2486. eimap_free(rl->extra_info_map, _extrainfo_free);
  2487. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2488. routerinfo_free(r));
  2489. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  2490. signed_descriptor_free(sd));
  2491. smartlist_free(rl->routers);
  2492. smartlist_free(rl->old_routers);
  2493. if (routerlist->desc_store.mmap)
  2494. tor_munmap_file(routerlist->desc_store.mmap);
  2495. if (routerlist->extrainfo_store.mmap)
  2496. tor_munmap_file(routerlist->extrainfo_store.mmap);
  2497. tor_free(rl);
  2498. router_dir_info_changed();
  2499. }
  2500. /** Log information about how much memory is being used for routerlist,
  2501. * at log level <b>severity</b>. */
  2502. void
  2503. dump_routerlist_mem_usage(int severity)
  2504. {
  2505. uint64_t livedescs = 0;
  2506. uint64_t olddescs = 0;
  2507. if (!routerlist)
  2508. return;
  2509. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  2510. livedescs += r->cache_info.signed_descriptor_len);
  2511. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  2512. olddescs += sd->signed_descriptor_len);
  2513. log(severity, LD_DIR,
  2514. "In %d live descriptors: "U64_FORMAT" bytes. "
  2515. "In %d old descriptors: "U64_FORMAT" bytes.",
  2516. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  2517. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  2518. }
  2519. /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
  2520. * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
  2521. * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
  2522. * is not in <b>sl</b>. */
  2523. static INLINE int
  2524. _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
  2525. {
  2526. if (idx < 0) {
  2527. idx = -1;
  2528. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  2529. if (r == ri) {
  2530. idx = r_sl_idx;
  2531. break;
  2532. });
  2533. } else {
  2534. tor_assert(idx < smartlist_len(sl));
  2535. tor_assert(smartlist_get(sl, idx) == ri);
  2536. };
  2537. return idx;
  2538. }
  2539. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  2540. * as needed. There must be no previous member of <b>rl</b> with the same
  2541. * identity digest as <b>ri</b>: If there is, call routerlist_replace
  2542. * instead.
  2543. */
  2544. static void
  2545. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  2546. {
  2547. routerinfo_t *ri_old;
  2548. {
  2549. /* XXXX Remove if this slows us down. */
  2550. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2551. tor_assert(ri_generated != ri);
  2552. }
  2553. tor_assert(ri->cache_info.routerlist_index == -1);
  2554. ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  2555. tor_assert(!ri_old);
  2556. sdmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
  2557. &(ri->cache_info));
  2558. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2559. sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
  2560. &ri->cache_info);
  2561. smartlist_add(rl->routers, ri);
  2562. ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
  2563. nodelist_add_routerinfo(ri);
  2564. router_dir_info_changed();
  2565. #ifdef DEBUG_ROUTERLIST
  2566. routerlist_assert_ok(rl);
  2567. #endif
  2568. }
  2569. /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
  2570. * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
  2571. * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
  2572. static int
  2573. extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
  2574. {
  2575. int r = 0;
  2576. routerinfo_t *ri = rimap_get(rl->identity_map,
  2577. ei->cache_info.identity_digest);
  2578. signed_descriptor_t *sd =
  2579. sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
  2580. extrainfo_t *ei_tmp;
  2581. {
  2582. /* XXXX remove this code if it slows us down. */
  2583. extrainfo_t *ei_generated = router_get_my_extrainfo();
  2584. tor_assert(ei_generated != ei);
  2585. }
  2586. if (!ri) {
  2587. /* This router is unknown; we can't even verify the signature. Give up.*/
  2588. goto done;
  2589. }
  2590. if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
  2591. goto done;
  2592. }
  2593. /* Okay, if we make it here, we definitely have a router corresponding to
  2594. * this extrainfo. */
  2595. ei_tmp = eimap_set(rl->extra_info_map,
  2596. ei->cache_info.signed_descriptor_digest,
  2597. ei);
  2598. r = 1;
  2599. if (ei_tmp) {
  2600. rl->extrainfo_store.bytes_dropped +=
  2601. ei_tmp->cache_info.signed_descriptor_len;
  2602. extrainfo_free(ei_tmp);
  2603. }
  2604. done:
  2605. if (r == 0)
  2606. extrainfo_free(ei);
  2607. #ifdef DEBUG_ROUTERLIST
  2608. routerlist_assert_ok(rl);
  2609. #endif
  2610. return r;
  2611. }
  2612. #define should_cache_old_descriptors() \
  2613. directory_caches_dir_info(get_options())
  2614. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  2615. * a copy of router <b>ri</b> yet, add it to the list of old (not
  2616. * recommended but still served) descriptors. Else free it. */
  2617. static void
  2618. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  2619. {
  2620. {
  2621. /* XXXX remove this code if it slows us down. */
  2622. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2623. tor_assert(ri_generated != ri);
  2624. }
  2625. tor_assert(ri->cache_info.routerlist_index == -1);
  2626. if (should_cache_old_descriptors() &&
  2627. ri->purpose == ROUTER_PURPOSE_GENERAL &&
  2628. !sdmap_get(rl->desc_digest_map,
  2629. ri->cache_info.signed_descriptor_digest)) {
  2630. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  2631. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2632. smartlist_add(rl->old_routers, sd);
  2633. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2634. if (!tor_digest_is_zero(sd->extra_info_digest))
  2635. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2636. } else {
  2637. routerinfo_free(ri);
  2638. }
  2639. #ifdef DEBUG_ROUTERLIST
  2640. routerlist_assert_ok(rl);
  2641. #endif
  2642. }
  2643. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  2644. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  2645. * idx) == ri, we don't need to do a linear search over the list to decide
  2646. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  2647. * the list, if any exists. <b>ri</b> is freed.
  2648. *
  2649. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  2650. * it to rl-&gt;old_routers. */
  2651. void
  2652. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
  2653. {
  2654. routerinfo_t *ri_tmp;
  2655. extrainfo_t *ei_tmp;
  2656. int idx = ri->cache_info.routerlist_index;
  2657. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2658. tor_assert(smartlist_get(rl->routers, idx) == ri);
  2659. nodelist_remove_routerinfo(ri);
  2660. /* make sure the rephist module knows that it's not running */
  2661. rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
  2662. ri->cache_info.routerlist_index = -1;
  2663. smartlist_del(rl->routers, idx);
  2664. if (idx < smartlist_len(rl->routers)) {
  2665. routerinfo_t *r = smartlist_get(rl->routers, idx);
  2666. r->cache_info.routerlist_index = idx;
  2667. }
  2668. ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  2669. router_dir_info_changed();
  2670. tor_assert(ri_tmp == ri);
  2671. if (make_old && should_cache_old_descriptors() &&
  2672. ri->purpose == ROUTER_PURPOSE_GENERAL) {
  2673. signed_descriptor_t *sd;
  2674. sd = signed_descriptor_from_routerinfo(ri);
  2675. smartlist_add(rl->old_routers, sd);
  2676. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2677. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2678. if (!tor_digest_is_zero(sd->extra_info_digest))
  2679. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2680. } else {
  2681. signed_descriptor_t *sd_tmp;
  2682. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2683. ri->cache_info.signed_descriptor_digest);
  2684. tor_assert(sd_tmp == &(ri->cache_info));
  2685. rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
  2686. ei_tmp = eimap_remove(rl->extra_info_map,
  2687. ri->cache_info.extra_info_digest);
  2688. if (ei_tmp) {
  2689. rl->extrainfo_store.bytes_dropped +=
  2690. ei_tmp->cache_info.signed_descriptor_len;
  2691. extrainfo_free(ei_tmp);
  2692. }
  2693. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2694. sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
  2695. routerinfo_free(ri);
  2696. }
  2697. #ifdef DEBUG_ROUTERLIST
  2698. routerlist_assert_ok(rl);
  2699. #endif
  2700. }
  2701. /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
  2702. * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
  2703. * <b>sd</b>. */
  2704. static void
  2705. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  2706. {
  2707. signed_descriptor_t *sd_tmp;
  2708. extrainfo_t *ei_tmp;
  2709. desc_store_t *store;
  2710. if (idx == -1) {
  2711. idx = sd->routerlist_index;
  2712. }
  2713. tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
  2714. /* XXXX edmanm's bridge relay triggered the following assert while
  2715. * running 0.2.0.12-alpha. If anybody triggers this again, see if we
  2716. * can get a backtrace. */
  2717. tor_assert(smartlist_get(rl->old_routers, idx) == sd);
  2718. tor_assert(idx == sd->routerlist_index);
  2719. sd->routerlist_index = -1;
  2720. smartlist_del(rl->old_routers, idx);
  2721. if (idx < smartlist_len(rl->old_routers)) {
  2722. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2723. d->routerlist_index = idx;
  2724. }
  2725. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2726. sd->signed_descriptor_digest);
  2727. tor_assert(sd_tmp == sd);
  2728. store = desc_get_store(rl, sd);
  2729. if (store)
  2730. store->bytes_dropped += sd->signed_descriptor_len;
  2731. ei_tmp = eimap_remove(rl->extra_info_map,
  2732. sd->extra_info_digest);
  2733. if (ei_tmp) {
  2734. rl->extrainfo_store.bytes_dropped +=
  2735. ei_tmp->cache_info.signed_descriptor_len;
  2736. extrainfo_free(ei_tmp);
  2737. }
  2738. if (!tor_digest_is_zero(sd->extra_info_digest))
  2739. sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
  2740. signed_descriptor_free(sd);
  2741. #ifdef DEBUG_ROUTERLIST
  2742. routerlist_assert_ok(rl);
  2743. #endif
  2744. }
  2745. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  2746. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  2747. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  2748. * search over the list to decide which to remove. We put ri_new in the same
  2749. * index as ri_old, if possible. ri is freed as appropriate.
  2750. *
  2751. * If should_cache_descriptors() is true, instead of deleting the router,
  2752. * we add it to rl-&gt;old_routers. */
  2753. static void
  2754. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  2755. routerinfo_t *ri_new)
  2756. {
  2757. int idx;
  2758. routerinfo_t *ri_tmp;
  2759. extrainfo_t *ei_tmp;
  2760. {
  2761. /* XXXX Remove this if it turns out to slow us down. */
  2762. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2763. tor_assert(ri_generated != ri_new);
  2764. }
  2765. tor_assert(ri_old != ri_new);
  2766. tor_assert(ri_new->cache_info.routerlist_index == -1);
  2767. idx = ri_old->cache_info.routerlist_index;
  2768. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2769. tor_assert(smartlist_get(rl->routers, idx) == ri_old);
  2770. nodelist_remove_routerinfo(ri_old);
  2771. nodelist_add_routerinfo(ri_new);
  2772. router_dir_info_changed();
  2773. if (idx >= 0) {
  2774. smartlist_set(rl->routers, idx, ri_new);
  2775. ri_old->cache_info.routerlist_index = -1;
  2776. ri_new->cache_info.routerlist_index = idx;
  2777. /* Check that ri_old is not in rl->routers anymore: */
  2778. tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
  2779. } else {
  2780. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  2781. routerlist_insert(rl, ri_new);
  2782. return;
  2783. }
  2784. if (memcmp(ri_old->cache_info.identity_digest,
  2785. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  2786. /* digests don't match; digestmap_set won't replace */
  2787. rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  2788. }
  2789. ri_tmp = rimap_set(rl->identity_map,
  2790. ri_new->cache_info.identity_digest, ri_new);
  2791. tor_assert(!ri_tmp || ri_tmp == ri_old);
  2792. sdmap_set(rl->desc_digest_map,
  2793. ri_new->cache_info.signed_descriptor_digest,
  2794. &(ri_new->cache_info));
  2795. if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
  2796. sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
  2797. &ri_new->cache_info);
  2798. }
  2799. if (should_cache_old_descriptors() &&
  2800. ri_old->purpose == ROUTER_PURPOSE_GENERAL) {
  2801. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  2802. smartlist_add(rl->old_routers, sd);
  2803. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2804. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2805. if (!tor_digest_is_zero(sd->extra_info_digest))
  2806. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2807. } else {
  2808. if (memcmp(ri_old->cache_info.signed_descriptor_digest,
  2809. ri_new->cache_info.signed_descriptor_digest,
  2810. DIGEST_LEN)) {
  2811. /* digests don't match; digestmap_set didn't replace */
  2812. sdmap_remove(rl->desc_digest_map,
  2813. ri_old->cache_info.signed_descriptor_digest);
  2814. }
  2815. ei_tmp = eimap_remove(rl->extra_info_map,
  2816. ri_old->cache_info.extra_info_digest);
  2817. if (ei_tmp) {
  2818. rl->extrainfo_store.bytes_dropped +=
  2819. ei_tmp->cache_info.signed_descriptor_len;
  2820. extrainfo_free(ei_tmp);
  2821. }
  2822. if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
  2823. sdmap_remove(rl->desc_by_eid_map,
  2824. ri_old->cache_info.extra_info_digest);
  2825. }
  2826. rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
  2827. routerinfo_free(ri_old);
  2828. }
  2829. #ifdef DEBUG_ROUTERLIST
  2830. routerlist_assert_ok(rl);
  2831. #endif
  2832. }
  2833. /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
  2834. * it as a fresh routerinfo_t. */
  2835. static routerinfo_t *
  2836. routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
  2837. {
  2838. routerinfo_t *ri;
  2839. const char *body;
  2840. body = signed_descriptor_get_annotations(sd);
  2841. ri = router_parse_entry_from_string(body,
  2842. body+sd->signed_descriptor_len+sd->annotations_len,
  2843. 0, 1, NULL);
  2844. if (!ri)
  2845. return NULL;
  2846. memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
  2847. sd->signed_descriptor_body = NULL; /* Steal reference. */
  2848. ri->cache_info.routerlist_index = -1;
  2849. routerlist_remove_old(rl, sd, -1);
  2850. return ri;
  2851. }
  2852. /** Free all memory held by the routerlist module. */
  2853. void
  2854. routerlist_free_all(void)
  2855. {
  2856. routerlist_free(routerlist);
  2857. routerlist = NULL;
  2858. if (warned_nicknames) {
  2859. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2860. smartlist_free(warned_nicknames);
  2861. warned_nicknames = NULL;
  2862. }
  2863. if (trusted_dir_servers) {
  2864. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2865. trusted_dir_server_free(ds));
  2866. smartlist_free(trusted_dir_servers);
  2867. trusted_dir_servers = NULL;
  2868. }
  2869. if (trusted_dir_certs) {
  2870. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  2871. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  2872. authority_cert_free(cert));
  2873. smartlist_free(cl->certs);
  2874. tor_free(cl);
  2875. } DIGESTMAP_FOREACH_END;
  2876. digestmap_free(trusted_dir_certs, NULL);
  2877. trusted_dir_certs = NULL;
  2878. }
  2879. }
  2880. /** Forget that we have issued any router-related warnings, so that we'll
  2881. * warn again if we see the same errors. */
  2882. void
  2883. routerlist_reset_warnings(void)
  2884. {
  2885. if (!warned_nicknames)
  2886. warned_nicknames = smartlist_create();
  2887. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2888. smartlist_clear(warned_nicknames); /* now the list is empty. */
  2889. networkstatus_reset_warnings();
  2890. }
  2891. /** Mark the router with ID <b>digest</b> as running or non-running
  2892. * in our routerlist. */
  2893. void
  2894. router_set_status(const char *digest, int up)
  2895. {
  2896. node_t *node;
  2897. tor_assert(digest);
  2898. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  2899. if (!memcmp(d->digest, digest, DIGEST_LEN))
  2900. d->is_running = up);
  2901. node = node_get_mutable_by_id(digest);
  2902. if (node) {
  2903. #if 0
  2904. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  2905. node_get_verbose_nickname(node,buf);
  2906. log_debug(LD_DIR,"Marking router %s as %s.",
  2907. buf, up ? "up" : "down");
  2908. #endif
  2909. if (!up && node_is_me(node) && !we_are_hibernating())
  2910. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  2911. "addresses reachable?");
  2912. node->is_running = up;
  2913. }
  2914. #if 0
  2915. /* No, don't change routerstatus's is_running. I have confirmed that
  2916. * nothing uses it to ask "is the node running? */
  2917. status = router_get_mutable_consensus_status_by_id(digest);
  2918. if (status && status->is_running != up) {
  2919. status->is_running = up;
  2920. control_event_networkstatus_changed_single(status);
  2921. }
  2922. #endif
  2923. router_dir_info_changed();
  2924. }
  2925. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  2926. * older entries (if any) with the same key. Note: Callers should not hold
  2927. * their pointers to <b>router</b> if this function fails; <b>router</b>
  2928. * will either be inserted into the routerlist or freed. Similarly, even
  2929. * if this call succeeds, they should not hold their pointers to
  2930. * <b>router</b> after subsequent calls with other routerinfo's -- they
  2931. * might cause the original routerinfo to get freed.
  2932. *
  2933. * Returns the status for the operation. Might set *<b>msg</b> if it wants
  2934. * the poster of the router to know something.
  2935. *
  2936. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  2937. * <b>from_fetch</b>, we received it in response to a request we made.
  2938. * (If both are false, that means it was uploaded to us as an auth dir
  2939. * server or via the controller.)
  2940. *
  2941. * This function should be called *after*
  2942. * routers_update_status_from_consensus_networkstatus; subsequently, you
  2943. * should call router_rebuild_store and routerlist_descriptors_added.
  2944. */
  2945. was_router_added_t
  2946. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  2947. int from_cache, int from_fetch)
  2948. {
  2949. const char *id_digest;
  2950. int authdir = authdir_mode_handles_descs(get_options(), router->purpose);
  2951. int authdir_believes_valid = 0;
  2952. routerinfo_t *old_router;
  2953. networkstatus_t *consensus = networkstatus_get_latest_consensus();
  2954. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2955. int in_consensus = 0;
  2956. tor_assert(msg);
  2957. if (!routerlist)
  2958. router_get_routerlist();
  2959. id_digest = router->cache_info.identity_digest;
  2960. old_router = router_get_mutable_by_digest(id_digest);
  2961. /* Make sure that we haven't already got this exact descriptor. */
  2962. if (sdmap_get(routerlist->desc_digest_map,
  2963. router->cache_info.signed_descriptor_digest)) {
  2964. /* If we have this descriptor already and the new descriptor is a bridge
  2965. * descriptor, replace it. If we had a bridge descriptor before and the
  2966. * new one is not a bridge descriptor, don't replace it. */
  2967. tor_assert(old_router);
  2968. if (! (routerinfo_is_a_configured_bridge(router) &&
  2969. (router->purpose == ROUTER_PURPOSE_BRIDGE ||
  2970. old_router->purpose != ROUTER_PURPOSE_BRIDGE))) {
  2971. log_info(LD_DIR,
  2972. "Dropping descriptor that we already have for router '%s'",
  2973. router->nickname);
  2974. *msg = "Router descriptor was not new.";
  2975. routerinfo_free(router);
  2976. return ROUTER_WAS_NOT_NEW;
  2977. }
  2978. }
  2979. if (authdir) {
  2980. if (authdir_wants_to_reject_router(router, msg,
  2981. !from_cache && !from_fetch,
  2982. &authdir_believes_valid)) {
  2983. tor_assert(*msg);
  2984. routerinfo_free(router);
  2985. return ROUTER_AUTHDIR_REJECTS;
  2986. }
  2987. } else if (from_fetch) {
  2988. /* Only check the descriptor digest against the network statuses when
  2989. * we are receiving in response to a fetch. */
  2990. if (!signed_desc_digest_is_recognized(&router->cache_info) &&
  2991. !routerinfo_is_a_configured_bridge(router)) {
  2992. /* We asked for it, so some networkstatus must have listed it when we
  2993. * did. Save it if we're a cache in case somebody else asks for it. */
  2994. log_info(LD_DIR,
  2995. "Received a no-longer-recognized descriptor for router '%s'",
  2996. router->nickname);
  2997. *msg = "Router descriptor is not referenced by any network-status.";
  2998. /* Only journal this desc if we'll be serving it. */
  2999. if (!from_cache && should_cache_old_descriptors())
  3000. signed_desc_append_to_journal(&router->cache_info,
  3001. &routerlist->desc_store);
  3002. routerlist_insert_old(routerlist, router);
  3003. return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
  3004. }
  3005. }
  3006. /* We no longer need a router with this descriptor digest. */
  3007. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3008. {
  3009. routerstatus_t *rs =
  3010. networkstatus_v2_find_mutable_entry(ns, id_digest);
  3011. if (rs && !memcmp(rs->descriptor_digest,
  3012. router->cache_info.signed_descriptor_digest,
  3013. DIGEST_LEN))
  3014. rs->need_to_mirror = 0;
  3015. });
  3016. if (consensus) {
  3017. routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
  3018. consensus, id_digest);
  3019. if (rs && !memcmp(rs->descriptor_digest,
  3020. router->cache_info.signed_descriptor_digest,
  3021. DIGEST_LEN)) {
  3022. in_consensus = 1;
  3023. rs->need_to_mirror = 0;
  3024. }
  3025. }
  3026. if (router->purpose == ROUTER_PURPOSE_GENERAL &&
  3027. consensus && !in_consensus && !authdir) {
  3028. /* If it's a general router not listed in the consensus, then don't
  3029. * consider replacing the latest router with it. */
  3030. if (!from_cache && should_cache_old_descriptors())
  3031. signed_desc_append_to_journal(&router->cache_info,
  3032. &routerlist->desc_store);
  3033. routerlist_insert_old(routerlist, router);
  3034. *msg = "Skipping router descriptor: not in consensus.";
  3035. return ROUTER_NOT_IN_CONSENSUS;
  3036. }
  3037. /* If we have a router with the same identity key, choose the newer one. */
  3038. if (old_router) {
  3039. if (!in_consensus && (router->cache_info.published_on <=
  3040. old_router->cache_info.published_on)) {
  3041. /* Same key, but old. This one is not listed in the consensus. */
  3042. log_debug(LD_DIR, "Not-new descriptor for router '%s'",
  3043. router->nickname);
  3044. /* Only journal this desc if we'll be serving it. */
  3045. if (!from_cache && should_cache_old_descriptors())
  3046. signed_desc_append_to_journal(&router->cache_info,
  3047. &routerlist->desc_store);
  3048. routerlist_insert_old(routerlist, router);
  3049. *msg = "Router descriptor was not new.";
  3050. return ROUTER_WAS_NOT_NEW;
  3051. } else {
  3052. /* Same key, and either new, or listed in the consensus. */
  3053. log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
  3054. router->nickname, old_router->nickname,
  3055. hex_str(id_digest,DIGEST_LEN));
  3056. if (routers_have_same_or_addr(router, old_router)) {
  3057. /* these carry over when the address and orport are unchanged. */
  3058. router->last_reachable = old_router->last_reachable;
  3059. router->testing_since = old_router->testing_since;
  3060. }
  3061. routerlist_replace(routerlist, old_router, router);
  3062. if (!from_cache) {
  3063. signed_desc_append_to_journal(&router->cache_info,
  3064. &routerlist->desc_store);
  3065. }
  3066. directory_set_dirty();
  3067. *msg = authdir_believes_valid ? "Valid server updated" :
  3068. ("Invalid server updated. (This dirserver is marking your "
  3069. "server as unapproved.)");
  3070. return ROUTER_ADDED_SUCCESSFULLY;
  3071. }
  3072. }
  3073. if (!in_consensus && from_cache &&
  3074. router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
  3075. *msg = "Router descriptor was really old.";
  3076. routerinfo_free(router);
  3077. return ROUTER_WAS_NOT_NEW;
  3078. }
  3079. /* We haven't seen a router with this identity before. Add it to the end of
  3080. * the list. */
  3081. routerlist_insert(routerlist, router);
  3082. if (!from_cache) {
  3083. signed_desc_append_to_journal(&router->cache_info,
  3084. &routerlist->desc_store);
  3085. }
  3086. directory_set_dirty();
  3087. return ROUTER_ADDED_SUCCESSFULLY;
  3088. }
  3089. /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
  3090. * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
  3091. * we actually inserted it, ROUTER_BAD_EI otherwise.
  3092. */
  3093. was_router_added_t
  3094. router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
  3095. int from_cache, int from_fetch)
  3096. {
  3097. int inserted;
  3098. (void)from_fetch;
  3099. if (msg) *msg = NULL;
  3100. /*XXXX022 Do something with msg */
  3101. inserted = extrainfo_insert(router_get_routerlist(), ei);
  3102. if (inserted && !from_cache)
  3103. signed_desc_append_to_journal(&ei->cache_info,
  3104. &routerlist->extrainfo_store);
  3105. if (inserted)
  3106. return ROUTER_ADDED_SUCCESSFULLY;
  3107. else
  3108. return ROUTER_BAD_EI;
  3109. }
  3110. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  3111. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  3112. * to, or later than that of *<b>b</b>. */
  3113. static int
  3114. _compare_old_routers_by_identity(const void **_a, const void **_b)
  3115. {
  3116. int i;
  3117. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  3118. if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  3119. return i;
  3120. return (int)(r1->published_on - r2->published_on);
  3121. }
  3122. /** Internal type used to represent how long an old descriptor was valid,
  3123. * where it appeared in the list of old descriptors, and whether it's extra
  3124. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  3125. struct duration_idx_t {
  3126. int duration;
  3127. int idx;
  3128. int old;
  3129. };
  3130. /** Sorting helper: compare two duration_idx_t by their duration. */
  3131. static int
  3132. _compare_duration_idx(const void *_d1, const void *_d2)
  3133. {
  3134. const struct duration_idx_t *d1 = _d1;
  3135. const struct duration_idx_t *d2 = _d2;
  3136. return d1->duration - d2->duration;
  3137. }
  3138. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  3139. * must contain routerinfo_t with the same identity and with publication time
  3140. * in ascending order. Remove members from this range until there are no more
  3141. * than max_descriptors_per_router() remaining. Start by removing the oldest
  3142. * members from before <b>cutoff</b>, then remove members which were current
  3143. * for the lowest amount of time. The order of members of old_routers at
  3144. * indices <b>lo</b> or higher may be changed.
  3145. */
  3146. static void
  3147. routerlist_remove_old_cached_routers_with_id(time_t now,
  3148. time_t cutoff, int lo, int hi,
  3149. digestset_t *retain)
  3150. {
  3151. int i, n = hi-lo+1;
  3152. unsigned n_extra, n_rmv = 0;
  3153. struct duration_idx_t *lifespans;
  3154. uint8_t *rmv, *must_keep;
  3155. smartlist_t *lst = routerlist->old_routers;
  3156. #if 1
  3157. const char *ident;
  3158. tor_assert(hi < smartlist_len(lst));
  3159. tor_assert(lo <= hi);
  3160. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  3161. for (i = lo+1; i <= hi; ++i) {
  3162. signed_descriptor_t *r = smartlist_get(lst, i);
  3163. tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
  3164. }
  3165. #endif
  3166. /* Check whether we need to do anything at all. */
  3167. {
  3168. int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
  3169. if (n <= mdpr)
  3170. return;
  3171. n_extra = n - mdpr;
  3172. }
  3173. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  3174. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  3175. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  3176. /* Set lifespans to contain the lifespan and index of each server. */
  3177. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  3178. for (i = lo; i <= hi; ++i) {
  3179. signed_descriptor_t *r = smartlist_get(lst, i);
  3180. signed_descriptor_t *r_next;
  3181. lifespans[i-lo].idx = i;
  3182. if (r->last_listed_as_valid_until >= now ||
  3183. (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
  3184. must_keep[i-lo] = 1;
  3185. }
  3186. if (i < hi) {
  3187. r_next = smartlist_get(lst, i+1);
  3188. tor_assert(r->published_on <= r_next->published_on);
  3189. lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
  3190. } else {
  3191. r_next = NULL;
  3192. lifespans[i-lo].duration = INT_MAX;
  3193. }
  3194. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  3195. ++n_rmv;
  3196. lifespans[i-lo].old = 1;
  3197. rmv[i-lo] = 1;
  3198. }
  3199. }
  3200. if (n_rmv < n_extra) {
  3201. /**
  3202. * We aren't removing enough servers for being old. Sort lifespans by
  3203. * the duration of liveness, and remove the ones we're not already going to
  3204. * remove based on how long they were alive.
  3205. **/
  3206. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  3207. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  3208. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  3209. rmv[lifespans[i].idx-lo] = 1;
  3210. ++n_rmv;
  3211. }
  3212. }
  3213. }
  3214. i = hi;
  3215. do {
  3216. if (rmv[i-lo])
  3217. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  3218. } while (--i >= lo);
  3219. tor_free(must_keep);
  3220. tor_free(rmv);
  3221. tor_free(lifespans);
  3222. }
  3223. /** Deactivate any routers from the routerlist that are more than
  3224. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  3225. * remove old routers from the list of cached routers if we have too many.
  3226. */
  3227. void
  3228. routerlist_remove_old_routers(void)
  3229. {
  3230. int i, hi=-1;
  3231. const char *cur_id = NULL;
  3232. time_t now = time(NULL);
  3233. time_t cutoff;
  3234. routerinfo_t *router;
  3235. signed_descriptor_t *sd;
  3236. digestset_t *retain;
  3237. int caches = directory_caches_dir_info(get_options());
  3238. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3239. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3240. int have_enough_v2;
  3241. trusted_dirs_remove_old_certs();
  3242. if (!routerlist || !consensus)
  3243. return;
  3244. // routerlist_assert_ok(routerlist);
  3245. /* We need to guess how many router descriptors we will wind up wanting to
  3246. retain, so that we can be sure to allocate a large enough Bloom filter
  3247. to hold the digest set. Overestimating is fine; underestimating is bad.
  3248. */
  3249. {
  3250. /* We'll probably retain everything in the consensus. */
  3251. int n_max_retain = smartlist_len(consensus->routerstatus_list);
  3252. if (caches && networkstatus_v2_list) {
  3253. /* If we care about v2 statuses, we'll retain at most as many as are
  3254. listed any of the v2 statues. This will be at least the length of
  3255. the largest v2 networkstatus, and in the worst case, this set will be
  3256. equal to the sum of the lengths of all v2 consensuses. Take the
  3257. worst case.
  3258. */
  3259. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3260. n_max_retain += smartlist_len(ns->entries));
  3261. }
  3262. retain = digestset_new(n_max_retain);
  3263. }
  3264. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3265. /* Build a list of all the descriptors that _anybody_ lists. */
  3266. if (caches && networkstatus_v2_list) {
  3267. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3268. {
  3269. /* XXXX The inner loop here gets pretty expensive, and actually shows up
  3270. * on some profiles. It may be the reason digestmap_set shows up in
  3271. * profiles too. If instead we kept a per-descriptor digest count of
  3272. * how many networkstatuses recommended each descriptor, and changed
  3273. * that only when the networkstatuses changed, that would be a speed
  3274. * improvement, possibly 1-4% if it also removes digestmap_set from the
  3275. * profile. Not worth it for 0.1.2.x, though. The new directory
  3276. * system will obsolete this whole thing in 0.2.0.x. */
  3277. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  3278. if (rs->published_on >= cutoff)
  3279. digestset_add(retain, rs->descriptor_digest));
  3280. });
  3281. }
  3282. /* Retain anything listed in the consensus. */
  3283. if (consensus) {
  3284. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  3285. if (rs->published_on >= cutoff)
  3286. digestset_add(retain, rs->descriptor_digest));
  3287. }
  3288. /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
  3289. * we should consider pruning current routers that are too old and that
  3290. * nobody recommends. (If we don't have a consensus or enough v2
  3291. * networkstatuses, then we should get more before we decide to kill
  3292. * routers.) */
  3293. /* we set this to true iff we don't care about v2 info, or we have enough. */
  3294. have_enough_v2 = !caches ||
  3295. (networkstatus_v2_list &&
  3296. smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
  3297. if (have_enough_v2 && consensus) {
  3298. cutoff = now - ROUTER_MAX_AGE;
  3299. /* Remove too-old unrecommended members of routerlist->routers. */
  3300. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  3301. router = smartlist_get(routerlist->routers, i);
  3302. if (router->cache_info.published_on <= cutoff &&
  3303. router->cache_info.last_listed_as_valid_until < now &&
  3304. !digestset_isin(retain,
  3305. router->cache_info.signed_descriptor_digest)) {
  3306. /* Too old: remove it. (If we're a cache, just move it into
  3307. * old_routers.) */
  3308. log_info(LD_DIR,
  3309. "Forgetting obsolete (too old) routerinfo for router '%s'",
  3310. router->nickname);
  3311. routerlist_remove(routerlist, router, 1, now);
  3312. i--;
  3313. }
  3314. }
  3315. }
  3316. //routerlist_assert_ok(routerlist);
  3317. /* Remove far-too-old members of routerlist->old_routers. */
  3318. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3319. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3320. sd = smartlist_get(routerlist->old_routers, i);
  3321. if (sd->published_on <= cutoff &&
  3322. sd->last_listed_as_valid_until < now &&
  3323. !digestset_isin(retain, sd->signed_descriptor_digest)) {
  3324. /* Too old. Remove it. */
  3325. routerlist_remove_old(routerlist, sd, i--);
  3326. }
  3327. }
  3328. //routerlist_assert_ok(routerlist);
  3329. log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
  3330. smartlist_len(routerlist->routers),
  3331. smartlist_len(routerlist->old_routers));
  3332. /* Now we might have to look at routerlist->old_routers for extraneous
  3333. * members. (We'd keep all the members if we could, but we need to save
  3334. * space.) First, check whether we have too many router descriptors, total.
  3335. * We're okay with having too many for some given router, so long as the
  3336. * total number doesn't approach max_descriptors_per_router()*len(router).
  3337. */
  3338. if (smartlist_len(routerlist->old_routers) <
  3339. smartlist_len(routerlist->routers))
  3340. goto done;
  3341. /* Sort by identity, then fix indices. */
  3342. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  3343. /* Fix indices. */
  3344. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3345. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3346. r->routerlist_index = i;
  3347. }
  3348. /* Iterate through the list from back to front, so when we remove descriptors
  3349. * we don't mess up groups we haven't gotten to. */
  3350. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  3351. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3352. if (!cur_id) {
  3353. cur_id = r->identity_digest;
  3354. hi = i;
  3355. }
  3356. if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
  3357. routerlist_remove_old_cached_routers_with_id(now,
  3358. cutoff, i+1, hi, retain);
  3359. cur_id = r->identity_digest;
  3360. hi = i;
  3361. }
  3362. }
  3363. if (hi>=0)
  3364. routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
  3365. //routerlist_assert_ok(routerlist);
  3366. done:
  3367. digestset_free(retain);
  3368. router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
  3369. router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
  3370. }
  3371. /** We just added a new set of descriptors. Take whatever extra steps
  3372. * we need. */
  3373. void
  3374. routerlist_descriptors_added(smartlist_t *sl, int from_cache)
  3375. {
  3376. tor_assert(sl);
  3377. control_event_descriptors_changed(sl);
  3378. SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
  3379. if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
  3380. learned_bridge_descriptor(ri, from_cache);
  3381. if (ri->needs_retest_if_added) {
  3382. ri->needs_retest_if_added = 0;
  3383. dirserv_single_reachability_test(approx_time(), ri);
  3384. }
  3385. } SMARTLIST_FOREACH_END(ri);
  3386. }
  3387. /**
  3388. * Code to parse a single router descriptor and insert it into the
  3389. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  3390. * descriptor was well-formed but could not be added; and 1 if the
  3391. * descriptor was added.
  3392. *
  3393. * If we don't add it and <b>msg</b> is not NULL, then assign to
  3394. * *<b>msg</b> a static string describing the reason for refusing the
  3395. * descriptor.
  3396. *
  3397. * This is used only by the controller.
  3398. */
  3399. int
  3400. router_load_single_router(const char *s, uint8_t purpose, int cache,
  3401. const char **msg)
  3402. {
  3403. routerinfo_t *ri;
  3404. was_router_added_t r;
  3405. smartlist_t *lst;
  3406. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  3407. tor_assert(msg);
  3408. *msg = NULL;
  3409. tor_snprintf(annotation_buf, sizeof(annotation_buf),
  3410. "@source controller\n"
  3411. "@purpose %s\n", router_purpose_to_string(purpose));
  3412. if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
  3413. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  3414. *msg = "Couldn't parse router descriptor.";
  3415. return -1;
  3416. }
  3417. tor_assert(ri->purpose == purpose);
  3418. if (router_is_me(ri)) {
  3419. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  3420. *msg = "Router's identity key matches mine.";
  3421. routerinfo_free(ri);
  3422. return 0;
  3423. }
  3424. if (!cache) /* obey the preference of the controller */
  3425. ri->cache_info.do_not_cache = 1;
  3426. lst = smartlist_create();
  3427. smartlist_add(lst, ri);
  3428. routers_update_status_from_consensus_networkstatus(lst, 0);
  3429. r = router_add_to_routerlist(ri, msg, 0, 0);
  3430. if (!WRA_WAS_ADDED(r)) {
  3431. /* we've already assigned to *msg now, and ri is already freed */
  3432. tor_assert(*msg);
  3433. if (r == ROUTER_AUTHDIR_REJECTS)
  3434. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  3435. smartlist_free(lst);
  3436. return 0;
  3437. } else {
  3438. routerlist_descriptors_added(lst, 0);
  3439. smartlist_free(lst);
  3440. log_debug(LD_DIR, "Added router to list");
  3441. return 1;
  3442. }
  3443. }
  3444. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  3445. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  3446. * are in response to a query to the network: cache them by adding them to
  3447. * the journal.
  3448. *
  3449. * Return the number of routers actually added.
  3450. *
  3451. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  3452. * uppercased fingerprints. Do not update any router whose
  3453. * fingerprint is not on the list; after updating a router, remove its
  3454. * fingerprint from the list.
  3455. *
  3456. * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
  3457. * are descriptor digests. Otherwise they are identity digests.
  3458. */
  3459. int
  3460. router_load_routers_from_string(const char *s, const char *eos,
  3461. saved_location_t saved_location,
  3462. smartlist_t *requested_fingerprints,
  3463. int descriptor_digests,
  3464. const char *prepend_annotations)
  3465. {
  3466. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  3467. char fp[HEX_DIGEST_LEN+1];
  3468. const char *msg;
  3469. int from_cache = (saved_location != SAVED_NOWHERE);
  3470. int allow_annotations = (saved_location != SAVED_NOWHERE);
  3471. int any_changed = 0;
  3472. router_parse_list_from_string(&s, eos, routers, saved_location, 0,
  3473. allow_annotations, prepend_annotations);
  3474. routers_update_status_from_consensus_networkstatus(routers, !from_cache);
  3475. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  3476. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  3477. was_router_added_t r;
  3478. char d[DIGEST_LEN];
  3479. if (requested_fingerprints) {
  3480. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3481. ri->cache_info.signed_descriptor_digest :
  3482. ri->cache_info.identity_digest,
  3483. DIGEST_LEN);
  3484. if (smartlist_string_isin(requested_fingerprints, fp)) {
  3485. smartlist_string_remove(requested_fingerprints, fp);
  3486. } else {
  3487. char *requested =
  3488. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  3489. log_warn(LD_DIR,
  3490. "We received a router descriptor with a fingerprint (%s) "
  3491. "that we never requested. (We asked for: %s.) Dropping.",
  3492. fp, requested);
  3493. tor_free(requested);
  3494. routerinfo_free(ri);
  3495. continue;
  3496. }
  3497. }
  3498. memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
  3499. r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
  3500. if (WRA_WAS_ADDED(r)) {
  3501. any_changed++;
  3502. smartlist_add(changed, ri);
  3503. routerlist_descriptors_added(changed, from_cache);
  3504. smartlist_clear(changed);
  3505. } else if (WRA_WAS_REJECTED(r)) {
  3506. download_status_t *dl_status;
  3507. dl_status = router_get_dl_status_by_descriptor_digest(d);
  3508. if (dl_status) {
  3509. log_info(LD_GENERAL, "Marking router %s as never downloadable",
  3510. hex_str(d, DIGEST_LEN));
  3511. download_status_mark_impossible(dl_status);
  3512. }
  3513. }
  3514. } SMARTLIST_FOREACH_END(ri);
  3515. routerlist_assert_ok(routerlist);
  3516. if (any_changed)
  3517. router_rebuild_store(0, &routerlist->desc_store);
  3518. smartlist_free(routers);
  3519. smartlist_free(changed);
  3520. return any_changed;
  3521. }
  3522. /** Parse one or more extrainfos from <b>s</b> (ending immediately before
  3523. * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
  3524. * router_load_routers_from_string(). */
  3525. void
  3526. router_load_extrainfo_from_string(const char *s, const char *eos,
  3527. saved_location_t saved_location,
  3528. smartlist_t *requested_fingerprints,
  3529. int descriptor_digests)
  3530. {
  3531. smartlist_t *extrainfo_list = smartlist_create();
  3532. const char *msg;
  3533. int from_cache = (saved_location != SAVED_NOWHERE);
  3534. router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
  3535. NULL);
  3536. log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
  3537. SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
  3538. was_router_added_t added =
  3539. router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
  3540. if (WRA_WAS_ADDED(added) && requested_fingerprints) {
  3541. char fp[HEX_DIGEST_LEN+1];
  3542. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3543. ei->cache_info.signed_descriptor_digest :
  3544. ei->cache_info.identity_digest,
  3545. DIGEST_LEN);
  3546. smartlist_string_remove(requested_fingerprints, fp);
  3547. /* We silently let people stuff us with extrainfos we didn't ask for,
  3548. * so long as we would have wanted them anyway. Since we always fetch
  3549. * all the extrainfos we want, and we never actually act on them
  3550. * inside Tor, this should be harmless. */
  3551. }
  3552. });
  3553. routerlist_assert_ok(routerlist);
  3554. router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
  3555. smartlist_free(extrainfo_list);
  3556. }
  3557. /** Return true iff any networkstatus includes a descriptor whose digest
  3558. * is that of <b>desc</b>. */
  3559. static int
  3560. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  3561. {
  3562. const routerstatus_t *rs;
  3563. networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3564. int caches = directory_caches_dir_info(get_options());
  3565. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3566. if (consensus) {
  3567. rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
  3568. if (rs && !memcmp(rs->descriptor_digest,
  3569. desc->signed_descriptor_digest, DIGEST_LEN))
  3570. return 1;
  3571. }
  3572. if (caches && networkstatus_v2_list) {
  3573. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3574. {
  3575. if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
  3576. continue;
  3577. if (!memcmp(rs->descriptor_digest,
  3578. desc->signed_descriptor_digest, DIGEST_LEN))
  3579. return 1;
  3580. });
  3581. }
  3582. return 0;
  3583. }
  3584. /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
  3585. * give it all a try again. */
  3586. void
  3587. routerlist_retry_directory_downloads(time_t now)
  3588. {
  3589. router_reset_status_download_failures();
  3590. router_reset_descriptor_download_failures();
  3591. update_networkstatus_downloads(now);
  3592. update_router_descriptor_downloads(now);
  3593. update_microdesc_downloads(now);
  3594. }
  3595. /** Return 1 if all running sufficiently-stable routers we can use will reject
  3596. * addr:port, return 0 if any might accept it. */
  3597. int
  3598. router_exit_policy_all_nodes_reject(uint32_t addr, uint16_t port,
  3599. int need_uptime)
  3600. { /* XXXX MOVE */
  3601. addr_policy_result_t r;
  3602. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  3603. if (node->is_running &&
  3604. !node_is_unreliable(node, need_uptime, 0, 0)) {
  3605. r = compare_addr_to_node_policy(addr, port, node);
  3606. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  3607. return 0; /* this one could be ok. good enough. */
  3608. }
  3609. } SMARTLIST_FOREACH_END(node);
  3610. return 1; /* all will reject. */
  3611. }
  3612. /** Return true iff <b>router</b> does not permit exit streams.
  3613. */
  3614. int
  3615. router_exit_policy_rejects_all(const routerinfo_t *router)
  3616. {
  3617. return router->policy_is_reject_star;
  3618. }
  3619. /** Add to the list of authoritative directory servers one at
  3620. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  3621. * <b>address</b> is NULL, add ourself. Return the new trusted directory
  3622. * server entry on success or NULL if we couldn't add it. */
  3623. trusted_dir_server_t *
  3624. add_trusted_dir_server(const char *nickname, const char *address,
  3625. uint16_t dir_port, uint16_t or_port,
  3626. const char *digest, const char *v3_auth_digest,
  3627. authority_type_t type)
  3628. {
  3629. trusted_dir_server_t *ent;
  3630. uint32_t a;
  3631. char *hostname = NULL;
  3632. size_t dlen;
  3633. if (!trusted_dir_servers)
  3634. trusted_dir_servers = smartlist_create();
  3635. if (!address) { /* The address is us; we should guess. */
  3636. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  3637. log_warn(LD_CONFIG,
  3638. "Couldn't find a suitable address when adding ourself as a "
  3639. "trusted directory server.");
  3640. return NULL;
  3641. }
  3642. } else {
  3643. if (tor_lookup_hostname(address, &a)) {
  3644. log_warn(LD_CONFIG,
  3645. "Unable to lookup address for directory server at '%s'",
  3646. address);
  3647. return NULL;
  3648. }
  3649. hostname = tor_strdup(address);
  3650. }
  3651. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  3652. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  3653. ent->address = hostname;
  3654. ent->addr = a;
  3655. ent->dir_port = dir_port;
  3656. ent->or_port = or_port;
  3657. ent->is_running = 1;
  3658. ent->type = type;
  3659. memcpy(ent->digest, digest, DIGEST_LEN);
  3660. if (v3_auth_digest && (type & V3_AUTHORITY))
  3661. memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
  3662. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  3663. ent->description = tor_malloc(dlen);
  3664. if (nickname)
  3665. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  3666. nickname, hostname, (int)dir_port);
  3667. else
  3668. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  3669. hostname, (int)dir_port);
  3670. ent->fake_status.addr = ent->addr;
  3671. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  3672. if (nickname)
  3673. strlcpy(ent->fake_status.nickname, nickname,
  3674. sizeof(ent->fake_status.nickname));
  3675. else
  3676. ent->fake_status.nickname[0] = '\0';
  3677. ent->fake_status.dir_port = ent->dir_port;
  3678. ent->fake_status.or_port = ent->or_port;
  3679. if (ent->or_port)
  3680. ent->fake_status.version_supports_begindir = 1;
  3681. ent->fake_status.version_supports_conditional_consensus = 1;
  3682. smartlist_add(trusted_dir_servers, ent);
  3683. router_dir_info_changed();
  3684. return ent;
  3685. }
  3686. /** Free storage held in <b>cert</b>. */
  3687. void
  3688. authority_cert_free(authority_cert_t *cert)
  3689. {
  3690. if (!cert)
  3691. return;
  3692. tor_free(cert->cache_info.signed_descriptor_body);
  3693. crypto_free_pk_env(cert->signing_key);
  3694. crypto_free_pk_env(cert->identity_key);
  3695. tor_free(cert);
  3696. }
  3697. /** Free storage held in <b>ds</b>. */
  3698. static void
  3699. trusted_dir_server_free(trusted_dir_server_t *ds)
  3700. {
  3701. if (!ds)
  3702. return;
  3703. tor_free(ds->nickname);
  3704. tor_free(ds->description);
  3705. tor_free(ds->address);
  3706. tor_free(ds);
  3707. }
  3708. /** Remove all members from the list of trusted dir servers. */
  3709. void
  3710. clear_trusted_dir_servers(void)
  3711. {
  3712. if (trusted_dir_servers) {
  3713. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  3714. trusted_dir_server_free(ent));
  3715. smartlist_clear(trusted_dir_servers);
  3716. } else {
  3717. trusted_dir_servers = smartlist_create();
  3718. }
  3719. router_dir_info_changed();
  3720. }
  3721. /** Return 1 if any trusted dir server supports v1 directories,
  3722. * else return 0. */
  3723. int
  3724. any_trusted_dir_is_v1_authority(void)
  3725. {
  3726. if (trusted_dir_servers)
  3727. return get_n_authorities(V1_AUTHORITY) > 0;
  3728. return 0;
  3729. }
  3730. /** For every current directory connection whose purpose is <b>purpose</b>,
  3731. * and where the resource being downloaded begins with <b>prefix</b>, split
  3732. * rest of the resource into base16 fingerprints, decode them, and set the
  3733. * corresponding elements of <b>result</b> to a nonzero value.
  3734. * DOCDOC purpose==microdesc
  3735. */
  3736. static void
  3737. list_pending_downloads(digestmap_t *result,
  3738. int purpose, const char *prefix)
  3739. {
  3740. const size_t p_len = strlen(prefix);
  3741. smartlist_t *tmp = smartlist_create();
  3742. smartlist_t *conns = get_connection_array();
  3743. int flags = DSR_HEX;
  3744. if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
  3745. flags = DSR_DIGEST256|DSR_BASE64;
  3746. tor_assert(result);
  3747. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3748. if (conn->type == CONN_TYPE_DIR &&
  3749. conn->purpose == purpose &&
  3750. !conn->marked_for_close) {
  3751. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3752. if (!strcmpstart(resource, prefix))
  3753. dir_split_resource_into_fingerprints(resource + p_len,
  3754. tmp, NULL, flags);
  3755. }
  3756. } SMARTLIST_FOREACH_END(conn);
  3757. SMARTLIST_FOREACH(tmp, char *, d,
  3758. {
  3759. digestmap_set(result, d, (void*)1);
  3760. tor_free(d);
  3761. });
  3762. smartlist_free(tmp);
  3763. }
  3764. /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
  3765. * true) we are currently downloading by descriptor digest, set result[d] to
  3766. * (void*)1. */
  3767. static void
  3768. list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
  3769. {
  3770. int purpose =
  3771. extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
  3772. list_pending_downloads(result, purpose, "d/");
  3773. }
  3774. /** DOCDOC */
  3775. /*XXXX NM should use digest256, if one comes into being. */
  3776. void
  3777. list_pending_microdesc_downloads(digestmap_t *result)
  3778. {
  3779. list_pending_downloads(result, DIR_PURPOSE_FETCH_MICRODESC, "d/");
  3780. }
  3781. /** Launch downloads for all the descriptors whose digests or digests256
  3782. * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
  3783. * range.) If <b>source</b> is given, download from <b>source</b>;
  3784. * otherwise, download from an appropriate random directory server.
  3785. */
  3786. static void
  3787. initiate_descriptor_downloads(const routerstatus_t *source,
  3788. int purpose,
  3789. smartlist_t *digests,
  3790. int lo, int hi, int pds_flags)
  3791. {
  3792. int i, n = hi-lo;
  3793. char *resource, *cp;
  3794. size_t r_len;
  3795. int digest_len = DIGEST_LEN, enc_digest_len = HEX_DIGEST_LEN;
  3796. char sep = '+';
  3797. int b64_256 = 0;
  3798. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3799. /* Microdescriptors are downloaded by "-"-separated base64-encoded
  3800. * 256-bit digests. */
  3801. digest_len = DIGEST256_LEN;
  3802. enc_digest_len = BASE64_DIGEST256_LEN;
  3803. sep = '-';
  3804. b64_256 = 1;
  3805. }
  3806. if (n <= 0)
  3807. return;
  3808. if (lo < 0)
  3809. lo = 0;
  3810. if (hi > smartlist_len(digests))
  3811. hi = smartlist_len(digests);
  3812. r_len = 8 + (enc_digest_len+1)*n;
  3813. cp = resource = tor_malloc(r_len);
  3814. memcpy(cp, "d/", 2);
  3815. cp += 2;
  3816. for (i = lo; i < hi; ++i) {
  3817. if (b64_256) {
  3818. digest256_to_base64(cp, smartlist_get(digests, i));
  3819. } else {
  3820. base16_encode(cp, r_len-(cp-resource),
  3821. smartlist_get(digests,i), digest_len);
  3822. }
  3823. cp += enc_digest_len;
  3824. *cp++ = sep;
  3825. }
  3826. memcpy(cp-1, ".z", 3);
  3827. if (source) {
  3828. /* We know which authority we want. */
  3829. directory_initiate_command_routerstatus(source, purpose,
  3830. ROUTER_PURPOSE_GENERAL,
  3831. 0, /* not private */
  3832. resource, NULL, 0, 0);
  3833. } else {
  3834. directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
  3835. pds_flags);
  3836. }
  3837. tor_free(resource);
  3838. }
  3839. /** Return 0 if this routerstatus is obsolete, too new, isn't
  3840. * running, or otherwise not a descriptor that we would make any
  3841. * use of even if we had it. Else return 1. */
  3842. static INLINE int
  3843. client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
  3844. {
  3845. if (!rs->is_flagged_running && !options->FetchUselessDescriptors) {
  3846. /* If we had this router descriptor, we wouldn't even bother using it.
  3847. * But, if we want to have a complete list, fetch it anyway. */
  3848. return 0;
  3849. }
  3850. if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
  3851. > now) {
  3852. /* Most caches probably don't have this descriptor yet. */
  3853. return 0;
  3854. }
  3855. if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
  3856. /* We'd drop it immediately for being too old. */
  3857. return 0;
  3858. }
  3859. return 1;
  3860. }
  3861. /** Max amount of hashes to download per request.
  3862. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3863. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3864. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3865. * So use 96 because it's a nice number.
  3866. */
  3867. #define MAX_DL_PER_REQUEST 96
  3868. #define MAX_MICRODESC_DL_PER_REQUEST 92
  3869. /** Don't split our requests so finely that we are requesting fewer than
  3870. * this number per server. */
  3871. #define MIN_DL_PER_REQUEST 4
  3872. /** To prevent a single screwy cache from confusing us by selective reply,
  3873. * try to split our requests into at least this many requests. */
  3874. #define MIN_REQUESTS 3
  3875. /** If we want fewer than this many descriptors, wait until we
  3876. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3877. * passed. */
  3878. #define MAX_DL_TO_DELAY 16
  3879. /** When directory clients have only a few servers to request, they batch
  3880. * them until they have more, or until this amount of time has passed. */
  3881. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3882. /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
  3883. * router descriptor digests or microdescriptor digest256s in
  3884. * <b>downloadable</b>, decide whether to delay fetching until we have more.
  3885. * If we don't want to delay, launch one or more requests to the appropriate
  3886. * directory authorities.
  3887. */
  3888. void
  3889. launch_descriptor_downloads(int purpose,
  3890. smartlist_t *downloadable,
  3891. const routerstatus_t *source, time_t now)
  3892. {
  3893. int should_delay = 0, n_downloadable;
  3894. or_options_t *options = get_options();
  3895. const char *descname;
  3896. tor_assert(purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  3897. purpose == DIR_PURPOSE_FETCH_MICRODESC);
  3898. descname = (purpose == DIR_PURPOSE_FETCH_SERVERDESC) ?
  3899. "routerdesc" : "microdesc";
  3900. n_downloadable = smartlist_len(downloadable);
  3901. if (!directory_fetches_dir_info_early(options)) {
  3902. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3903. log_debug(LD_DIR,
  3904. "There are enough downloadable %ss to launch requests.",
  3905. descname);
  3906. should_delay = 0;
  3907. } else {
  3908. should_delay = (last_routerdesc_download_attempted +
  3909. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3910. if (!should_delay && n_downloadable) {
  3911. if (last_routerdesc_download_attempted) {
  3912. log_info(LD_DIR,
  3913. "There are not many downloadable %ss, but we've "
  3914. "been waiting long enough (%d seconds). Downloading.",
  3915. descname,
  3916. (int)(now-last_routerdesc_download_attempted));
  3917. } else {
  3918. log_info(LD_DIR,
  3919. "There are not many downloadable %ss, but we haven't "
  3920. "tried downloading descriptors recently. Downloading.",
  3921. descname);
  3922. }
  3923. }
  3924. }
  3925. }
  3926. /* XXX should we consider having even the dir mirrors delay
  3927. * a little bit, so we don't load the authorities as much? -RD
  3928. * I don't think so. If we do, clients that want those descriptors may
  3929. * not actually find them if the caches haven't got them yet. -NM
  3930. */
  3931. if (! should_delay && n_downloadable) {
  3932. int i, n_per_request;
  3933. const char *req_plural = "", *rtr_plural = "";
  3934. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3935. if (! authdir_mode_any_nonhidserv(options)) {
  3936. /* If we wind up going to the authorities, we want to only open one
  3937. * connection to each authority at a time, so that we don't overload
  3938. * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
  3939. * regardless of whether we're a cache or not; it gets ignored if we're
  3940. * not calling router_pick_trusteddirserver.
  3941. *
  3942. * Setting this flag can make initiate_descriptor_downloads() ignore
  3943. * requests. We need to make sure that we do in fact call
  3944. * update_router_descriptor_downloads() later on, once the connections
  3945. * have succeeded or failed.
  3946. */
  3947. pds_flags |= (purpose == DIR_PURPOSE_FETCH_MICRODESC) ?
  3948. PDS_NO_EXISTING_MICRODESC_FETCH :
  3949. PDS_NO_EXISTING_SERVERDESC_FETCH;
  3950. }
  3951. n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
  3952. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3953. if (n_per_request > MAX_MICRODESC_DL_PER_REQUEST)
  3954. n_per_request = MAX_MICRODESC_DL_PER_REQUEST;
  3955. } else {
  3956. if (n_per_request > MAX_DL_PER_REQUEST)
  3957. n_per_request = MAX_DL_PER_REQUEST;
  3958. }
  3959. if (n_per_request < MIN_DL_PER_REQUEST)
  3960. n_per_request = MIN_DL_PER_REQUEST;
  3961. if (n_downloadable > n_per_request)
  3962. req_plural = rtr_plural = "s";
  3963. else if (n_downloadable > 1)
  3964. rtr_plural = "s";
  3965. log_info(LD_DIR,
  3966. "Launching %d request%s for %d router%s, %d at a time",
  3967. CEIL_DIV(n_downloadable, n_per_request),
  3968. req_plural, n_downloadable, rtr_plural, n_per_request);
  3969. smartlist_sort_digests(downloadable);
  3970. for (i=0; i < n_downloadable; i += n_per_request) {
  3971. initiate_descriptor_downloads(source, purpose,
  3972. downloadable, i, i+n_per_request,
  3973. pds_flags);
  3974. }
  3975. last_routerdesc_download_attempted = now;
  3976. }
  3977. }
  3978. /** Launch downloads for router status as needed, using the strategy used by
  3979. * authorities and caches: based on the v2 networkstatuses we have, download
  3980. * every descriptor we don't have but would serve, from a random authority
  3981. * that lists it. */
  3982. static void
  3983. update_router_descriptor_cache_downloads_v2(time_t now)
  3984. {
  3985. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3986. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3987. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3988. int i, j, n;
  3989. int n_download;
  3990. or_options_t *options = get_options();
  3991. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3992. if (! directory_fetches_dir_info_early(options)) {
  3993. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
  3994. "on a non-dir-mirror?");
  3995. }
  3996. if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
  3997. return;
  3998. map = digestmap_new();
  3999. n = smartlist_len(networkstatus_v2_list);
  4000. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  4001. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  4002. /* Set map[d]=1 for the digest of every descriptor that we are currently
  4003. * downloading. */
  4004. list_pending_descriptor_downloads(map, 0);
  4005. /* For the digest of every descriptor that we don't have, and that we aren't
  4006. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  4007. * about that descriptor, and we haven't already failed to get that
  4008. * descriptor from the corresponding authority.
  4009. */
  4010. n_download = 0;
  4011. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  4012. {
  4013. trusted_dir_server_t *ds;
  4014. smartlist_t *dl;
  4015. dl = downloadable[ns_sl_idx] = smartlist_create();
  4016. download_from[ns_sl_idx] = smartlist_create();
  4017. if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
  4018. /* Don't download if the networkstatus is almost ancient. */
  4019. /* Actually, I suspect what's happening here is that we ask
  4020. * for the descriptor when we have a given networkstatus,
  4021. * and then we get a newer networkstatus, and then we receive
  4022. * the descriptor. Having a networkstatus actually expire is
  4023. * probably a rare event, and we'll probably be happiest if
  4024. * we take this clause out. -RD */
  4025. continue;
  4026. }
  4027. /* Don't try dirservers that we think are down -- we might have
  4028. * just tried them and just marked them as down. */
  4029. ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
  4030. if (ds && !ds->is_running)
  4031. continue;
  4032. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  4033. {
  4034. if (!rs->need_to_mirror)
  4035. continue;
  4036. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  4037. log_warn(LD_BUG,
  4038. "We have a router descriptor, but need_to_mirror=1.");
  4039. rs->need_to_mirror = 0;
  4040. continue;
  4041. }
  4042. if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
  4043. rs->need_to_mirror = 0;
  4044. continue;
  4045. }
  4046. if (digestmap_get(map, rs->descriptor_digest)) {
  4047. /* We're downloading it already. */
  4048. continue;
  4049. } else {
  4050. /* We could download it from this guy. */
  4051. smartlist_add(dl, rs->descriptor_digest);
  4052. ++n_download;
  4053. }
  4054. });
  4055. });
  4056. /* At random, assign descriptors to authorities such that:
  4057. * - if d is a member of some downloadable[x], d is a member of some
  4058. * download_from[y]. (Everything we want to download, we try to download
  4059. * from somebody.)
  4060. * - If d is a member of download_from[y], d is a member of downloadable[y].
  4061. * (We only try to download descriptors from authorities who claim to have
  4062. * them.)
  4063. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  4064. * (We don't try to download anything from two authorities concurrently.)
  4065. */
  4066. while (n_download) {
  4067. int which_ns = crypto_rand_int(n);
  4068. smartlist_t *dl = downloadable[which_ns];
  4069. int idx;
  4070. char *d;
  4071. if (!smartlist_len(dl))
  4072. continue;
  4073. idx = crypto_rand_int(smartlist_len(dl));
  4074. d = smartlist_get(dl, idx);
  4075. if (! digestmap_get(map, d)) {
  4076. smartlist_add(download_from[which_ns], d);
  4077. digestmap_set(map, d, (void*) 1);
  4078. }
  4079. smartlist_del(dl, idx);
  4080. --n_download;
  4081. }
  4082. /* Now, we can actually launch our requests. */
  4083. for (i=0; i<n; ++i) {
  4084. networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
  4085. trusted_dir_server_t *ds =
  4086. router_get_trusteddirserver_by_digest(ns->identity_digest);
  4087. smartlist_t *dl = download_from[i];
  4088. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  4089. if (! authdir_mode_any_nonhidserv(options))
  4090. pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
  4091. if (!ds) {
  4092. log_info(LD_DIR, "Networkstatus with no corresponding authority!");
  4093. continue;
  4094. }
  4095. if (! smartlist_len(dl))
  4096. continue;
  4097. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  4098. smartlist_len(dl), ds->nickname);
  4099. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  4100. initiate_descriptor_downloads(&(ds->fake_status),
  4101. DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
  4102. j+MAX_DL_PER_REQUEST, pds_flags);
  4103. }
  4104. }
  4105. for (i=0; i<n; ++i) {
  4106. smartlist_free(download_from[i]);
  4107. smartlist_free(downloadable[i]);
  4108. }
  4109. tor_free(download_from);
  4110. tor_free(downloadable);
  4111. digestmap_free(map,NULL);
  4112. }
  4113. /** For any descriptor that we want that's currently listed in
  4114. * <b>consensus</b>, download it as appropriate. */
  4115. void
  4116. update_consensus_router_descriptor_downloads(time_t now, int is_vote,
  4117. networkstatus_t *consensus)
  4118. {
  4119. or_options_t *options = get_options();
  4120. digestmap_t *map = NULL;
  4121. smartlist_t *no_longer_old = smartlist_create();
  4122. smartlist_t *downloadable = smartlist_create();
  4123. routerstatus_t *source = NULL;
  4124. int authdir = authdir_mode(options);
  4125. int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
  4126. n_inprogress=0, n_in_oldrouters=0;
  4127. if (directory_too_idle_to_fetch_descriptors(options, now))
  4128. goto done;
  4129. if (!consensus)
  4130. goto done;
  4131. if (is_vote) {
  4132. /* where's it from, so we know whom to ask for descriptors */
  4133. trusted_dir_server_t *ds;
  4134. networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
  4135. tor_assert(voter);
  4136. ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
  4137. if (ds)
  4138. source = &(ds->fake_status);
  4139. else
  4140. log_warn(LD_DIR, "couldn't lookup source from vote?");
  4141. }
  4142. map = digestmap_new();
  4143. list_pending_descriptor_downloads(map, 0);
  4144. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
  4145. routerstatus_t *rs =
  4146. is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
  4147. signed_descriptor_t *sd;
  4148. if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
  4149. const routerinfo_t *ri;
  4150. ++n_have;
  4151. if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
  4152. memcmp(ri->cache_info.signed_descriptor_digest,
  4153. sd->signed_descriptor_digest, DIGEST_LEN)) {
  4154. /* We have a descriptor with this digest, but either there is no
  4155. * entry in routerlist with the same ID (!ri), or there is one,
  4156. * but the identity digest differs (memcmp).
  4157. */
  4158. smartlist_add(no_longer_old, sd);
  4159. ++n_in_oldrouters; /* We have it in old_routers. */
  4160. }
  4161. continue; /* We have it already. */
  4162. }
  4163. if (digestmap_get(map, rs->descriptor_digest)) {
  4164. ++n_inprogress;
  4165. continue; /* We have an in-progress download. */
  4166. }
  4167. if (!download_status_is_ready(&rs->dl_status, now,
  4168. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  4169. ++n_delayed; /* Not ready for retry. */
  4170. continue;
  4171. }
  4172. if (authdir && dirserv_would_reject_router(rs)) {
  4173. ++n_would_reject;
  4174. continue; /* We would throw it out immediately. */
  4175. }
  4176. if (!directory_caches_dir_info(options) &&
  4177. !client_would_use_router(rs, now, options)) {
  4178. ++n_wouldnt_use;
  4179. continue; /* We would never use it ourself. */
  4180. }
  4181. if (is_vote && source) {
  4182. char time_bufnew[ISO_TIME_LEN+1];
  4183. char time_bufold[ISO_TIME_LEN+1];
  4184. const routerinfo_t *oldrouter;
  4185. oldrouter = router_get_by_id_digest(rs->identity_digest);
  4186. format_iso_time(time_bufnew, rs->published_on);
  4187. if (oldrouter)
  4188. format_iso_time(time_bufold, oldrouter->cache_info.published_on);
  4189. log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
  4190. rs->nickname, time_bufnew,
  4191. oldrouter ? time_bufold : "none",
  4192. source->nickname, oldrouter ? "known" : "unknown");
  4193. }
  4194. smartlist_add(downloadable, rs->descriptor_digest);
  4195. } SMARTLIST_FOREACH_END(rsp);
  4196. if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
  4197. && smartlist_len(no_longer_old)) {
  4198. routerlist_t *rl = router_get_routerlist();
  4199. log_info(LD_DIR, "%d router descriptors listed in consensus are "
  4200. "currently in old_routers; making them current.",
  4201. smartlist_len(no_longer_old));
  4202. SMARTLIST_FOREACH(no_longer_old, signed_descriptor_t *, sd, {
  4203. const char *msg;
  4204. was_router_added_t r;
  4205. routerinfo_t *ri = routerlist_reparse_old(rl, sd);
  4206. if (!ri) {
  4207. log_warn(LD_BUG, "Failed to re-parse a router.");
  4208. continue;
  4209. }
  4210. r = router_add_to_routerlist(ri, &msg, 1, 0);
  4211. if (WRA_WAS_OUTDATED(r)) {
  4212. log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
  4213. msg?msg:"???");
  4214. }
  4215. });
  4216. routerlist_assert_ok(rl);
  4217. }
  4218. log_info(LD_DIR,
  4219. "%d router descriptors downloadable. %d delayed; %d present "
  4220. "(%d of those were in old_routers); %d would_reject; "
  4221. "%d wouldnt_use; %d in progress.",
  4222. smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
  4223. n_would_reject, n_wouldnt_use, n_inprogress);
  4224. launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC,
  4225. downloadable, source, now);
  4226. digestmap_free(map, NULL);
  4227. done:
  4228. smartlist_free(downloadable);
  4229. smartlist_free(no_longer_old);
  4230. }
  4231. /** How often should we launch a server/authority request to be sure of getting
  4232. * a guess for our IP? */
  4233. /*XXXX021 this info should come from netinfo cells or something, or we should
  4234. * do this only when we aren't seeing incoming data. see bug 652. */
  4235. #define DUMMY_DOWNLOAD_INTERVAL (20*60)
  4236. /** Launch downloads for router status as needed. */
  4237. void
  4238. update_router_descriptor_downloads(time_t now)
  4239. {
  4240. or_options_t *options = get_options();
  4241. static time_t last_dummy_download = 0;
  4242. if (should_delay_dir_fetches(options))
  4243. return;
  4244. if (directory_fetches_dir_info_early(options)) {
  4245. update_router_descriptor_cache_downloads_v2(now);
  4246. }
  4247. update_consensus_router_descriptor_downloads(now, 0,
  4248. networkstatus_get_reasonably_live_consensus(now, FLAV_NS));
  4249. /* XXXX021 we could be smarter here; see notes on bug 652. */
  4250. /* XXXX NM Microdescs: if we're not fetching microdescriptors, we need
  4251. * to make something else invoke this. */
  4252. /* If we're a server that doesn't have a configured address, we rely on
  4253. * directory fetches to learn when our address changes. So if we haven't
  4254. * tried to get any routerdescs in a long time, try a dummy fetch now. */
  4255. if (!options->Address &&
  4256. server_mode(options) &&
  4257. last_routerdesc_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
  4258. last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
  4259. last_dummy_download = now;
  4260. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  4261. ROUTER_PURPOSE_GENERAL, "authority.z",
  4262. PDS_RETRY_IF_NO_SERVERS);
  4263. }
  4264. }
  4265. /** Launch extrainfo downloads as needed. */
  4266. void
  4267. update_extrainfo_downloads(time_t now)
  4268. {
  4269. or_options_t *options = get_options();
  4270. routerlist_t *rl;
  4271. smartlist_t *wanted;
  4272. digestmap_t *pending;
  4273. int old_routers, i;
  4274. int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
  4275. if (! options->DownloadExtraInfo)
  4276. return;
  4277. if (should_delay_dir_fetches(options))
  4278. return;
  4279. if (!router_have_minimum_dir_info())
  4280. return;
  4281. pending = digestmap_new();
  4282. list_pending_descriptor_downloads(pending, 1);
  4283. rl = router_get_routerlist();
  4284. wanted = smartlist_create();
  4285. for (old_routers = 0; old_routers < 2; ++old_routers) {
  4286. smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
  4287. for (i = 0; i < smartlist_len(lst); ++i) {
  4288. signed_descriptor_t *sd;
  4289. char *d;
  4290. if (old_routers)
  4291. sd = smartlist_get(lst, i);
  4292. else
  4293. sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
  4294. if (sd->is_extrainfo)
  4295. continue; /* This should never happen. */
  4296. if (old_routers && !router_get_by_id_digest(sd->identity_digest))
  4297. continue; /* Couldn't check the signature if we got it. */
  4298. if (sd->extrainfo_is_bogus)
  4299. continue;
  4300. d = sd->extra_info_digest;
  4301. if (tor_digest_is_zero(d)) {
  4302. ++n_no_ei;
  4303. continue;
  4304. }
  4305. if (eimap_get(rl->extra_info_map, d)) {
  4306. ++n_have;
  4307. continue;
  4308. }
  4309. if (!download_status_is_ready(&sd->ei_dl_status, now,
  4310. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  4311. ++n_delay;
  4312. continue;
  4313. }
  4314. if (digestmap_get(pending, d)) {
  4315. ++n_pending;
  4316. continue;
  4317. }
  4318. smartlist_add(wanted, d);
  4319. }
  4320. }
  4321. digestmap_free(pending, NULL);
  4322. log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
  4323. "with present ei, %d delaying, %d pending, %d downloadable.",
  4324. n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
  4325. smartlist_shuffle(wanted);
  4326. for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
  4327. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
  4328. wanted, i, i + MAX_DL_PER_REQUEST,
  4329. PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
  4330. }
  4331. smartlist_free(wanted);
  4332. }
  4333. /** True iff, the last time we checked whether we had enough directory info
  4334. * to build circuits, the answer was "yes". */
  4335. static int have_min_dir_info = 0;
  4336. /** True iff enough has changed since the last time we checked whether we had
  4337. * enough directory info to build circuits that our old answer can no longer
  4338. * be trusted. */
  4339. static int need_to_update_have_min_dir_info = 1;
  4340. /** String describing what we're missing before we have enough directory
  4341. * info. */
  4342. static char dir_info_status[128] = "";
  4343. /** Return true iff we have enough networkstatus and router information to
  4344. * start building circuits. Right now, this means "more than half the
  4345. * networkstatus documents, and at least 1/4 of expected routers." */
  4346. //XXX should consider whether we have enough exiting nodes here.
  4347. int
  4348. router_have_minimum_dir_info(void)
  4349. {
  4350. if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
  4351. update_router_have_minimum_dir_info();
  4352. need_to_update_have_min_dir_info = 0;
  4353. }
  4354. return have_min_dir_info;
  4355. }
  4356. /** Called when our internal view of the directory has changed. This can be
  4357. * when the authorities change, networkstatuses change, the list of routerdescs
  4358. * changes, or number of running routers changes.
  4359. */
  4360. void
  4361. router_dir_info_changed(void)
  4362. {
  4363. need_to_update_have_min_dir_info = 1;
  4364. rend_hsdir_routers_changed();
  4365. }
  4366. /** Return a string describing what we're missing before we have enough
  4367. * directory info. */
  4368. const char *
  4369. get_dir_info_status_string(void)
  4370. {
  4371. return dir_info_status;
  4372. }
  4373. /** Iterate over the servers listed in <b>consensus</b>, and count how many of
  4374. * them seem like ones we'd use, and how many of <em>those</em> we have
  4375. * descriptors for. Store the former in *<b>num_usable</b> and the latter in
  4376. * *<b>num_present</b>. If <b>in_set</b> is non-NULL, only consider those
  4377. * routers in <b>in_set</b>.
  4378. */
  4379. static void
  4380. count_usable_descriptors(int *num_present, int *num_usable,
  4381. const networkstatus_t *consensus,
  4382. or_options_t *options, time_t now,
  4383. routerset_t *in_set)
  4384. {
  4385. *num_present = 0, *num_usable=0;
  4386. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  4387. {
  4388. if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1))
  4389. continue;
  4390. if (client_would_use_router(rs, now, options)) {
  4391. ++*num_usable; /* the consensus says we want it. */
  4392. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  4393. /* we have the descriptor listed in the consensus. */
  4394. ++*num_present;
  4395. }
  4396. }
  4397. });
  4398. log_debug(LD_DIR, "%d usable, %d present.", *num_usable, *num_present);
  4399. }
  4400. /** We just fetched a new set of descriptors. Compute how far through
  4401. * the "loading descriptors" bootstrapping phase we are, so we can inform
  4402. * the controller of our progress. */
  4403. int
  4404. count_loading_descriptors_progress(void)
  4405. {
  4406. int num_present = 0, num_usable=0;
  4407. time_t now = time(NULL);
  4408. const networkstatus_t *consensus =
  4409. networkstatus_get_reasonably_live_consensus(now, FLAV_NS);
  4410. double fraction;
  4411. if (!consensus)
  4412. return 0; /* can't count descriptors if we have no list of them */
  4413. count_usable_descriptors(&num_present, &num_usable,
  4414. consensus, get_options(), now, NULL);
  4415. if (num_usable == 0)
  4416. return 0; /* don't div by 0 */
  4417. fraction = num_present / (num_usable/4.);
  4418. if (fraction > 1.0)
  4419. return 0; /* it's not the number of descriptors holding us back */
  4420. return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
  4421. (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
  4422. BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
  4423. }
  4424. /** Change the value of have_min_dir_info, setting it true iff we have enough
  4425. * network and router information to build circuits. Clear the value of
  4426. * need_to_update_have_min_dir_info. */
  4427. static void
  4428. update_router_have_minimum_dir_info(void)
  4429. {
  4430. int num_present = 0, num_usable=0;
  4431. time_t now = time(NULL);
  4432. int res;
  4433. or_options_t *options = get_options();
  4434. const networkstatus_t *consensus =
  4435. networkstatus_get_reasonably_live_consensus(now, FLAV_NS);
  4436. if (!consensus) {
  4437. if (!networkstatus_get_latest_consensus())
  4438. strlcpy(dir_info_status, "We have no network-status consensus.",
  4439. sizeof(dir_info_status));
  4440. else
  4441. strlcpy(dir_info_status, "We have no recent network-status consensus.",
  4442. sizeof(dir_info_status));
  4443. res = 0;
  4444. goto done;
  4445. }
  4446. if (should_delay_dir_fetches(get_options())) {
  4447. log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
  4448. strlcpy(dir_info_status, "No live bridge descriptors.",
  4449. sizeof(dir_info_status));
  4450. res = 0;
  4451. goto done;
  4452. }
  4453. count_usable_descriptors(&num_present, &num_usable, consensus, options, now,
  4454. NULL);
  4455. if (num_present < num_usable/4) {
  4456. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  4457. "We have only %d/%d usable descriptors.", num_present, num_usable);
  4458. res = 0;
  4459. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
  4460. goto done;
  4461. } else if (num_present < 2) {
  4462. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  4463. "Only %d descriptor%s here and believed reachable!",
  4464. num_present, num_present ? "" : "s");
  4465. res = 0;
  4466. goto done;
  4467. }
  4468. /* Check for entry nodes. */
  4469. if (options->EntryNodes) {
  4470. count_usable_descriptors(&num_present, &num_usable, consensus, options,
  4471. now, options->EntryNodes);
  4472. if (!num_usable || !num_present) {
  4473. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  4474. "We have only %d/%d usable entry node descriptors.",
  4475. num_present, num_usable);
  4476. res = 0;
  4477. goto done;
  4478. }
  4479. }
  4480. res = 1;
  4481. done:
  4482. if (res && !have_min_dir_info) {
  4483. log(LOG_NOTICE, LD_DIR,
  4484. "We now have enough directory information to build circuits.");
  4485. control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
  4486. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0);
  4487. }
  4488. if (!res && have_min_dir_info) {
  4489. int quiet = directory_too_idle_to_fetch_descriptors(options, now);
  4490. log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
  4491. "Our directory information is no longer up-to-date "
  4492. "enough to build circuits: %s", dir_info_status);
  4493. /* a) make us log when we next complete a circuit, so we know when Tor
  4494. * is back up and usable, and b) disable some activities that Tor
  4495. * should only do while circuits are working, like reachability tests
  4496. * and fetching bridge descriptors only over circuits. */
  4497. can_complete_circuit = 0;
  4498. control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
  4499. }
  4500. have_min_dir_info = res;
  4501. need_to_update_have_min_dir_info = 0;
  4502. }
  4503. /** Reset the descriptor download failure count on all routers, so that we
  4504. * can retry any long-failed routers immediately.
  4505. */
  4506. void
  4507. router_reset_descriptor_download_failures(void)
  4508. {
  4509. networkstatus_reset_download_failures();
  4510. last_routerdesc_download_attempted = 0;
  4511. if (!routerlist)
  4512. return;
  4513. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  4514. {
  4515. download_status_reset(&ri->cache_info.ei_dl_status);
  4516. });
  4517. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  4518. {
  4519. download_status_reset(&sd->ei_dl_status);
  4520. });
  4521. }
  4522. /** Any changes in a router descriptor's publication time larger than this are
  4523. * automatically non-cosmetic. */
  4524. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  4525. /** We allow uptime to vary from how much it ought to be by this much. */
  4526. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  4527. /** Return true iff the only differences between r1 and r2 are such that
  4528. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  4529. */
  4530. int
  4531. router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
  4532. {
  4533. time_t r1pub, r2pub;
  4534. long time_difference;
  4535. tor_assert(r1 && r2);
  4536. /* r1 should be the one that was published first. */
  4537. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  4538. const routerinfo_t *ri_tmp = r2;
  4539. r2 = r1;
  4540. r1 = ri_tmp;
  4541. }
  4542. /* If any key fields differ, they're different. */
  4543. if (strcasecmp(r1->address, r2->address) ||
  4544. strcasecmp(r1->nickname, r2->nickname) ||
  4545. r1->or_port != r2->or_port ||
  4546. r1->dir_port != r2->dir_port ||
  4547. r1->purpose != r2->purpose ||
  4548. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  4549. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  4550. strcasecmp(r1->platform, r2->platform) ||
  4551. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  4552. (!r1->contact_info && r2->contact_info) ||
  4553. (r1->contact_info && r2->contact_info &&
  4554. strcasecmp(r1->contact_info, r2->contact_info)) ||
  4555. r1->is_hibernating != r2->is_hibernating ||
  4556. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  4557. return 0;
  4558. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  4559. return 0;
  4560. if (r1->declared_family && r2->declared_family) {
  4561. int i, n;
  4562. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  4563. return 0;
  4564. n = smartlist_len(r1->declared_family);
  4565. for (i=0; i < n; ++i) {
  4566. if (strcasecmp(smartlist_get(r1->declared_family, i),
  4567. smartlist_get(r2->declared_family, i)))
  4568. return 0;
  4569. }
  4570. }
  4571. /* Did bandwidth change a lot? */
  4572. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  4573. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  4574. return 0;
  4575. /* Did the bandwidthrate or bandwidthburst change? */
  4576. if ((r1->bandwidthrate != r2->bandwidthrate) ||
  4577. (r1->bandwidthburst != r2->bandwidthburst))
  4578. return 0;
  4579. /* Did more than 12 hours pass? */
  4580. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  4581. < r2->cache_info.published_on)
  4582. return 0;
  4583. /* Did uptime fail to increase by approximately the amount we would think,
  4584. * give or take some slop? */
  4585. r1pub = r1->cache_info.published_on;
  4586. r2pub = r2->cache_info.published_on;
  4587. time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  4588. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  4589. time_difference > r1->uptime * .05 &&
  4590. time_difference > r2->uptime * .05)
  4591. return 0;
  4592. /* Otherwise, the difference is cosmetic. */
  4593. return 1;
  4594. }
  4595. /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
  4596. * extrainfo document
  4597. * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
  4598. * dropped. Return 0 for "compatible", return 1 for "reject, and inform
  4599. * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
  4600. * <b>msg</b> is present, set *<b>msg</b> to a description of the
  4601. * incompatibility (if any).
  4602. **/
  4603. int
  4604. routerinfo_incompatible_with_extrainfo(const routerinfo_t *ri,
  4605. extrainfo_t *ei,
  4606. signed_descriptor_t *sd,
  4607. const char **msg)
  4608. {
  4609. int digest_matches, r=1;
  4610. tor_assert(ri);
  4611. tor_assert(ei);
  4612. if (!sd)
  4613. sd = (signed_descriptor_t*)&ri->cache_info;
  4614. if (ei->bad_sig) {
  4615. if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
  4616. return 1;
  4617. }
  4618. digest_matches = !memcmp(ei->cache_info.signed_descriptor_digest,
  4619. sd->extra_info_digest, DIGEST_LEN);
  4620. /* The identity must match exactly to have been generated at the same time
  4621. * by the same router. */
  4622. if (memcmp(ri->cache_info.identity_digest, ei->cache_info.identity_digest,
  4623. DIGEST_LEN)) {
  4624. if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
  4625. goto err; /* different servers */
  4626. }
  4627. if (ei->pending_sig) {
  4628. char signed_digest[128];
  4629. if (crypto_pk_public_checksig(ri->identity_pkey, signed_digest,
  4630. ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
  4631. memcmp(signed_digest, ei->cache_info.signed_descriptor_digest,
  4632. DIGEST_LEN)) {
  4633. ei->bad_sig = 1;
  4634. tor_free(ei->pending_sig);
  4635. if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
  4636. goto err; /* Bad signature, or no match. */
  4637. }
  4638. ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
  4639. tor_free(ei->pending_sig);
  4640. }
  4641. if (ei->cache_info.published_on < sd->published_on) {
  4642. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4643. goto err;
  4644. } else if (ei->cache_info.published_on > sd->published_on) {
  4645. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4646. r = -1;
  4647. goto err;
  4648. }
  4649. if (!digest_matches) {
  4650. if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
  4651. goto err; /* Digest doesn't match declared value. */
  4652. }
  4653. return 0;
  4654. err:
  4655. if (digest_matches) {
  4656. /* This signature was okay, and the digest was right: This is indeed the
  4657. * corresponding extrainfo. But insanely, it doesn't match the routerinfo
  4658. * that lists it. Don't try to fetch this one again. */
  4659. sd->extrainfo_is_bogus = 1;
  4660. }
  4661. return r;
  4662. }
  4663. /** Assert that the internal representation of <b>rl</b> is
  4664. * self-consistent. */
  4665. void
  4666. routerlist_assert_ok(const routerlist_t *rl)
  4667. {
  4668. routerinfo_t *r2;
  4669. signed_descriptor_t *sd2;
  4670. if (!rl)
  4671. return;
  4672. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  4673. {
  4674. r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
  4675. tor_assert(r == r2);
  4676. sd2 = sdmap_get(rl->desc_digest_map,
  4677. r->cache_info.signed_descriptor_digest);
  4678. tor_assert(&(r->cache_info) == sd2);
  4679. tor_assert(r->cache_info.routerlist_index == r_sl_idx);
  4680. /* XXXX
  4681. *
  4682. * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
  4683. * commenting this out is just a band-aid.
  4684. *
  4685. * The problem is that, although well-behaved router descriptors
  4686. * should never have the same value for their extra_info_digest, it's
  4687. * possible for ill-behaved routers to claim whatever they like there.
  4688. *
  4689. * The real answer is to trash desc_by_eid_map and instead have
  4690. * something that indicates for a given extra-info digest we want,
  4691. * what its download status is. We'll do that as a part of routerlist
  4692. * refactoring once consensus directories are in. For now,
  4693. * this rep violation is probably harmless: an adversary can make us
  4694. * reset our retry count for an extrainfo, but that's not the end
  4695. * of the world. Changing the representation in 0.2.0.x would just
  4696. * destabilize the codebase.
  4697. if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
  4698. signed_descriptor_t *sd3 =
  4699. sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
  4700. tor_assert(sd3 == &(r->cache_info));
  4701. }
  4702. */
  4703. });
  4704. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  4705. {
  4706. r2 = rimap_get(rl->identity_map, sd->identity_digest);
  4707. tor_assert(sd != &(r2->cache_info));
  4708. sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  4709. tor_assert(sd == sd2);
  4710. tor_assert(sd->routerlist_index == sd_sl_idx);
  4711. /* XXXX see above.
  4712. if (!tor_digest_is_zero(sd->extra_info_digest)) {
  4713. signed_descriptor_t *sd3 =
  4714. sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
  4715. tor_assert(sd3 == sd);
  4716. }
  4717. */
  4718. });
  4719. RIMAP_FOREACH(rl->identity_map, d, r) {
  4720. tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
  4721. } DIGESTMAP_FOREACH_END;
  4722. SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
  4723. tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
  4724. } DIGESTMAP_FOREACH_END;
  4725. SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
  4726. tor_assert(!tor_digest_is_zero(d));
  4727. tor_assert(sd);
  4728. tor_assert(!memcmp(sd->extra_info_digest, d, DIGEST_LEN));
  4729. } DIGESTMAP_FOREACH_END;
  4730. EIMAP_FOREACH(rl->extra_info_map, d, ei) {
  4731. signed_descriptor_t *sd;
  4732. tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
  4733. d, DIGEST_LEN));
  4734. sd = sdmap_get(rl->desc_by_eid_map,
  4735. ei->cache_info.signed_descriptor_digest);
  4736. // tor_assert(sd); // XXXX see above
  4737. if (sd) {
  4738. tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
  4739. sd->extra_info_digest, DIGEST_LEN));
  4740. }
  4741. } DIGESTMAP_FOREACH_END;
  4742. }
  4743. /** Allocate and return a new string representing the contact info
  4744. * and platform string for <b>router</b>,
  4745. * surrounded by quotes and using standard C escapes.
  4746. *
  4747. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  4748. * thread. Also, each call invalidates the last-returned value, so don't
  4749. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  4750. *
  4751. * If <b>router</b> is NULL, it just frees its internal memory and returns.
  4752. */
  4753. const char *
  4754. esc_router_info(const routerinfo_t *router)
  4755. {
  4756. static char *info=NULL;
  4757. char *esc_contact, *esc_platform;
  4758. size_t len;
  4759. tor_free(info);
  4760. if (!router)
  4761. return NULL; /* we're exiting; just free the memory we use */
  4762. esc_contact = esc_for_log(router->contact_info);
  4763. esc_platform = esc_for_log(router->platform);
  4764. len = strlen(esc_contact)+strlen(esc_platform)+32;
  4765. info = tor_malloc(len);
  4766. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  4767. esc_platform);
  4768. tor_free(esc_contact);
  4769. tor_free(esc_platform);
  4770. return info;
  4771. }
  4772. /** Helper for sorting: compare two routerinfos by their identity
  4773. * digest. */
  4774. static int
  4775. _compare_routerinfo_by_id_digest(const void **a, const void **b)
  4776. {
  4777. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  4778. return memcmp(first->cache_info.identity_digest,
  4779. second->cache_info.identity_digest,
  4780. DIGEST_LEN);
  4781. }
  4782. /** Sort a list of routerinfo_t in ascending order of identity digest. */
  4783. void
  4784. routers_sort_by_identity(smartlist_t *routers)
  4785. {
  4786. smartlist_sort(routers, _compare_routerinfo_by_id_digest);
  4787. }
  4788. /** A routerset specifies constraints on a set of possible routerinfos, based
  4789. * on their names, identities, or addresses. It is optimized for determining
  4790. * whether a router is a member or not, in O(1+P) time, where P is the number
  4791. * of address policy constraints. */
  4792. struct routerset_t {
  4793. /** A list of strings for the elements of the policy. Each string is either
  4794. * a nickname, a hexadecimal identity fingerprint, or an address policy. A
  4795. * router belongs to the set if its nickname OR its identity OR its address
  4796. * matches an entry here. */
  4797. smartlist_t *list;
  4798. /** A map from lowercase nicknames of routers in the set to (void*)1 */
  4799. strmap_t *names;
  4800. /** A map from identity digests routers in the set to (void*)1 */
  4801. digestmap_t *digests;
  4802. /** An address policy for routers in the set. For implementation reasons,
  4803. * a router belongs to the set if it is _rejected_ by this policy. */
  4804. smartlist_t *policies;
  4805. /** A human-readable description of what this routerset is for. Used in
  4806. * log messages. */
  4807. char *description;
  4808. /** A list of the country codes in this set. */
  4809. smartlist_t *country_names;
  4810. /** Total number of countries we knew about when we built <b>countries</b>.*/
  4811. int n_countries;
  4812. /** Bit array mapping the return value of geoip_get_country() to 1 iff the
  4813. * country is a member of this routerset. Note that we MUST call
  4814. * routerset_refresh_countries() whenever the geoip country list is
  4815. * reloaded. */
  4816. bitarray_t *countries;
  4817. };
  4818. /** Return a new empty routerset. */
  4819. routerset_t *
  4820. routerset_new(void)
  4821. {
  4822. routerset_t *result = tor_malloc_zero(sizeof(routerset_t));
  4823. result->list = smartlist_create();
  4824. result->names = strmap_new();
  4825. result->digests = digestmap_new();
  4826. result->policies = smartlist_create();
  4827. result->country_names = smartlist_create();
  4828. return result;
  4829. }
  4830. /** If <b>c</b> is a country code in the form {cc}, return a newly allocated
  4831. * string holding the "cc" part. Else, return NULL. */
  4832. static char *
  4833. routerset_get_countryname(const char *c)
  4834. {
  4835. char *country;
  4836. if (strlen(c) < 4 || c[0] !='{' || c[3] !='}')
  4837. return NULL;
  4838. country = tor_strndup(c+1, 2);
  4839. tor_strlower(country);
  4840. return country;
  4841. }
  4842. #if 0
  4843. /** Add the GeoIP database's integer index (+1) of a valid two-character
  4844. * country code to the routerset's <b>countries</b> bitarray. Return the
  4845. * integer index if the country code is valid, -1 otherwise.*/
  4846. static int
  4847. routerset_add_country(const char *c)
  4848. {
  4849. char country[3];
  4850. country_t cc;
  4851. /* XXXX: Country codes must be of the form \{[a-z\?]{2}\} but this accepts
  4852. \{[.]{2}\}. Do we need to be strict? -RH */
  4853. /* Nope; if the country code is bad, we'll get 0 when we look it up. */
  4854. if (!geoip_is_loaded()) {
  4855. log(LOG_WARN, LD_CONFIG, "GeoIP database not loaded: Cannot add country"
  4856. "entry %s, ignoring.", c);
  4857. return -1;
  4858. }
  4859. memcpy(country, c+1, 2);
  4860. country[2] = '\0';
  4861. tor_strlower(country);
  4862. if ((cc=geoip_get_country(country))==-1) {
  4863. log(LOG_WARN, LD_CONFIG, "Country code '%s' is not valid, ignoring.",
  4864. country);
  4865. }
  4866. return cc;
  4867. }
  4868. #endif
  4869. /** Update the routerset's <b>countries</b> bitarray_t. Called whenever
  4870. * the GeoIP database is reloaded.
  4871. */
  4872. void
  4873. routerset_refresh_countries(routerset_t *target)
  4874. {
  4875. int cc;
  4876. bitarray_free(target->countries);
  4877. if (!geoip_is_loaded()) {
  4878. target->countries = NULL;
  4879. target->n_countries = 0;
  4880. return;
  4881. }
  4882. target->n_countries = geoip_get_n_countries();
  4883. target->countries = bitarray_init_zero(target->n_countries);
  4884. SMARTLIST_FOREACH_BEGIN(target->country_names, const char *, country) {
  4885. cc = geoip_get_country(country);
  4886. if (cc >= 0) {
  4887. tor_assert(cc < target->n_countries);
  4888. bitarray_set(target->countries, cc);
  4889. } else {
  4890. log(LOG_WARN, LD_CONFIG, "Country code '%s' is not recognized.",
  4891. country);
  4892. }
  4893. } SMARTLIST_FOREACH_END(country);
  4894. }
  4895. /** Parse the string <b>s</b> to create a set of routerset entries, and add
  4896. * them to <b>target</b>. In log messages, refer to the string as
  4897. * <b>description</b>. Return 0 on success, -1 on failure.
  4898. *
  4899. * Three kinds of elements are allowed in routersets: nicknames, IP address
  4900. * patterns, and fingerprints. They may be surrounded by optional space, and
  4901. * must be separated by commas.
  4902. */
  4903. int
  4904. routerset_parse(routerset_t *target, const char *s, const char *description)
  4905. {
  4906. int r = 0;
  4907. int added_countries = 0;
  4908. char *countryname;
  4909. smartlist_t *list = smartlist_create();
  4910. smartlist_split_string(list, s, ",",
  4911. SPLIT_SKIP_SPACE | SPLIT_IGNORE_BLANK, 0);
  4912. SMARTLIST_FOREACH_BEGIN(list, char *, nick) {
  4913. addr_policy_t *p;
  4914. if (is_legal_hexdigest(nick)) {
  4915. char d[DIGEST_LEN];
  4916. if (*nick == '$')
  4917. ++nick;
  4918. log_debug(LD_CONFIG, "Adding identity %s to %s", nick, description);
  4919. base16_decode(d, sizeof(d), nick, HEX_DIGEST_LEN);
  4920. digestmap_set(target->digests, d, (void*)1);
  4921. } else if (is_legal_nickname(nick)) {
  4922. log_debug(LD_CONFIG, "Adding nickname %s to %s", nick, description);
  4923. strmap_set_lc(target->names, nick, (void*)1);
  4924. } else if ((countryname = routerset_get_countryname(nick)) != NULL) {
  4925. log_debug(LD_CONFIG, "Adding country %s to %s", nick,
  4926. description);
  4927. smartlist_add(target->country_names, countryname);
  4928. added_countries = 1;
  4929. } else if ((strchr(nick,'.') || strchr(nick, '*')) &&
  4930. (p = router_parse_addr_policy_item_from_string(
  4931. nick, ADDR_POLICY_REJECT))) {
  4932. log_debug(LD_CONFIG, "Adding address %s to %s", nick, description);
  4933. smartlist_add(target->policies, p);
  4934. } else {
  4935. log_warn(LD_CONFIG, "Entry '%s' in %s is misformed.", nick,
  4936. description);
  4937. r = -1;
  4938. tor_free(nick);
  4939. SMARTLIST_DEL_CURRENT(list, nick);
  4940. }
  4941. } SMARTLIST_FOREACH_END(nick);
  4942. smartlist_add_all(target->list, list);
  4943. smartlist_free(list);
  4944. if (added_countries)
  4945. routerset_refresh_countries(target);
  4946. return r;
  4947. }
  4948. /** Called when we change a node set, or when we reload the geoip list:
  4949. * recompute all country info in all configuration node sets and in the
  4950. * routerlist. */
  4951. void
  4952. refresh_all_country_info(void)
  4953. {
  4954. or_options_t *options = get_options();
  4955. if (options->EntryNodes)
  4956. routerset_refresh_countries(options->EntryNodes);
  4957. if (options->ExitNodes)
  4958. routerset_refresh_countries(options->ExitNodes);
  4959. if (options->ExcludeNodes)
  4960. routerset_refresh_countries(options->ExcludeNodes);
  4961. if (options->ExcludeExitNodes)
  4962. routerset_refresh_countries(options->ExcludeExitNodes);
  4963. if (options->_ExcludeExitNodesUnion)
  4964. routerset_refresh_countries(options->_ExcludeExitNodesUnion);
  4965. nodelist_refresh_countries();
  4966. }
  4967. /** Add all members of the set <b>source</b> to <b>target</b>. */
  4968. void
  4969. routerset_union(routerset_t *target, const routerset_t *source)
  4970. {
  4971. char *s;
  4972. tor_assert(target);
  4973. if (!source || !source->list)
  4974. return;
  4975. s = routerset_to_string(source);
  4976. routerset_parse(target, s, "other routerset");
  4977. tor_free(s);
  4978. }
  4979. /** Return true iff <b>set</b> lists only nicknames and digests, and includes
  4980. * no IP ranges or countries. */
  4981. int
  4982. routerset_is_list(const routerset_t *set)
  4983. {
  4984. return smartlist_len(set->country_names) == 0 &&
  4985. smartlist_len(set->policies) == 0;
  4986. }
  4987. /** Return true iff we need a GeoIP IP-to-country database to make sense of
  4988. * <b>set</b>. */
  4989. int
  4990. routerset_needs_geoip(const routerset_t *set)
  4991. {
  4992. return set && smartlist_len(set->country_names);
  4993. }
  4994. /** Return true iff there are no entries in <b>set</b>. */
  4995. static int
  4996. routerset_is_empty(const routerset_t *set)
  4997. {
  4998. return !set || smartlist_len(set->list) == 0;
  4999. }
  5000. /** Helper. Return true iff <b>set</b> contains a router based on the other
  5001. * provided fields. Return higher values for more specific subentries: a
  5002. * single router is more specific than an address range of routers, which is
  5003. * more specific in turn than a country code.
  5004. *
  5005. * (If country is -1, then we take the country
  5006. * from addr.) */
  5007. static int
  5008. routerset_contains(const routerset_t *set, const tor_addr_t *addr,
  5009. uint16_t orport,
  5010. const char *nickname, const char *id_digest,
  5011. country_t country)
  5012. {
  5013. if (!set || !set->list) return 0;
  5014. if (nickname && strmap_get_lc(set->names, nickname))
  5015. return 4;
  5016. if (id_digest && digestmap_get(set->digests, id_digest))
  5017. return 4;
  5018. if (addr && compare_tor_addr_to_addr_policy(addr, orport, set->policies)
  5019. == ADDR_POLICY_REJECTED)
  5020. return 3;
  5021. if (set->countries) {
  5022. if (country < 0 && addr)
  5023. country = geoip_get_country_by_ip(tor_addr_to_ipv4h(addr));
  5024. if (country >= 0 && country < set->n_countries &&
  5025. bitarray_is_set(set->countries, country))
  5026. return 2;
  5027. }
  5028. return 0;
  5029. }
  5030. /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
  5031. int
  5032. routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
  5033. {
  5034. return routerset_contains(set,
  5035. &ei->addr,
  5036. ei->port,
  5037. ei->nickname,
  5038. ei->identity_digest,
  5039. -1 /*country*/);
  5040. }
  5041. /** Return true iff <b>ri</b> is in <b>set</b>. If country is <b>-1</b>, we
  5042. * look up the country. */
  5043. int
  5044. routerset_contains_router(const routerset_t *set, const routerinfo_t *ri,
  5045. country_t country)
  5046. {
  5047. tor_addr_t addr;
  5048. tor_addr_from_ipv4h(&addr, ri->addr);
  5049. return routerset_contains(set,
  5050. &addr,
  5051. ri->or_port,
  5052. ri->nickname,
  5053. ri->cache_info.identity_digest,
  5054. country);
  5055. }
  5056. /** Return true iff <b>rs</b> is in <b>set</b>. If country is <b>-1</b>, we
  5057. * look up the country. */
  5058. int
  5059. routerset_contains_routerstatus(const routerset_t *set,
  5060. const routerstatus_t *rs,
  5061. country_t country)
  5062. {
  5063. tor_addr_t addr;
  5064. tor_addr_from_ipv4h(&addr, rs->addr);
  5065. return routerset_contains(set,
  5066. &addr,
  5067. rs->or_port,
  5068. rs->nickname,
  5069. rs->identity_digest,
  5070. country);
  5071. }
  5072. /** Return true iff <b>node</b> is in <b>set</b>. */
  5073. int
  5074. routerset_contains_node(const routerset_t *set, const node_t *node)
  5075. {
  5076. if (node->rs)
  5077. return routerset_contains_routerstatus(set, node->rs, node->country);
  5078. else if (node->ri)
  5079. return routerset_contains_router(set, node->ri, node->country);
  5080. else
  5081. return 0;
  5082. }
  5083. /** Add every known node_t that is a member of <b>routerset</b> to
  5084. * <b>out</b>. If <b>running_only</b>, only add the running ones. */
  5085. void
  5086. routerset_get_all_nodes(smartlist_t *out, const routerset_t *routerset,
  5087. int running_only)
  5088. { /* XXXX MOVE */
  5089. tor_assert(out);
  5090. if (!routerset || !routerset->list)
  5091. return;
  5092. if (routerset_is_list(routerset)) {
  5093. /* No routers are specified by type; all are given by name or digest.
  5094. * we can do a lookup in O(len(list)). */
  5095. SMARTLIST_FOREACH(routerset->list, const char *, name, {
  5096. const node_t *node = node_get_by_nickname(name, 1);
  5097. if (node) {
  5098. if (!running_only || node->is_running)
  5099. smartlist_add(out, (void*)node);
  5100. }
  5101. });
  5102. } else {
  5103. /* We need to iterate over the routerlist to get all the ones of the
  5104. * right kind. */
  5105. smartlist_t *nodes = nodelist_get_list();
  5106. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  5107. if (running_only && !node->is_running)
  5108. continue;
  5109. if (routerset_contains_node(routerset, node))
  5110. smartlist_add(out, (void*)node);
  5111. });
  5112. }
  5113. }
  5114. /** Add to <b>target</b> every node_t from <b>source</b> except:
  5115. *
  5116. * 1) Don't add it if <b>include</b> is non-empty and the relay isn't in
  5117. * <b>include</b>; and
  5118. * 2) Don't add it if <b>exclude</b> is non-empty and the relay is
  5119. * excluded in a more specific fashion by <b>exclude</b>.
  5120. * 3) If <b>running_only</b>, don't add non-running routers.
  5121. */
  5122. void
  5123. routersets_get_node_disjunction(smartlist_t *target,
  5124. const smartlist_t *source,
  5125. const routerset_t *include,
  5126. const routerset_t *exclude, int running_only)
  5127. {
  5128. SMARTLIST_FOREACH(source, const node_t *, node, {
  5129. int include_result;
  5130. if (running_only && !node->is_running)
  5131. continue;
  5132. if (!routerset_is_empty(include))
  5133. include_result = routerset_contains_node(include, node);
  5134. else
  5135. include_result = 1;
  5136. if (include_result) {
  5137. int exclude_result = routerset_contains_node(exclude, node);
  5138. if (include_result >= exclude_result)
  5139. smartlist_add(target, (void*)node);
  5140. }
  5141. });
  5142. }
  5143. /** Remove every node_t from <b>lst</b> that is in <b>routerset</b>. */
  5144. void
  5145. routerset_subtract_nodes(smartlist_t *lst, const routerset_t *routerset)
  5146. { /*XXXX MOVE ? */
  5147. tor_assert(lst);
  5148. if (!routerset)
  5149. return;
  5150. SMARTLIST_FOREACH(lst, const node_t *, node, {
  5151. if (routerset_contains_node(routerset, node)) {
  5152. //log_debug(LD_DIR, "Subtracting %s",r->nickname);
  5153. SMARTLIST_DEL_CURRENT(lst, node);
  5154. }
  5155. });
  5156. }
  5157. /** Return a new string that when parsed by routerset_parse_string() will
  5158. * yield <b>set</b>. */
  5159. char *
  5160. routerset_to_string(const routerset_t *set)
  5161. {
  5162. if (!set || !set->list)
  5163. return tor_strdup("");
  5164. return smartlist_join_strings(set->list, ",", 0, NULL);
  5165. }
  5166. /** Helper: return true iff old and new are both NULL, or both non-NULL
  5167. * equal routersets. */
  5168. int
  5169. routerset_equal(const routerset_t *old, const routerset_t *new)
  5170. {
  5171. if (old == NULL && new == NULL)
  5172. return 1;
  5173. else if (old == NULL || new == NULL)
  5174. return 0;
  5175. if (smartlist_len(old->list) != smartlist_len(new->list))
  5176. return 0;
  5177. SMARTLIST_FOREACH(old->list, const char *, cp1, {
  5178. const char *cp2 = smartlist_get(new->list, cp1_sl_idx);
  5179. if (strcmp(cp1, cp2))
  5180. return 0;
  5181. });
  5182. return 1;
  5183. }
  5184. /** Free all storage held in <b>routerset</b>. */
  5185. void
  5186. routerset_free(routerset_t *routerset)
  5187. {
  5188. if (!routerset)
  5189. return;
  5190. SMARTLIST_FOREACH(routerset->list, char *, cp, tor_free(cp));
  5191. smartlist_free(routerset->list);
  5192. SMARTLIST_FOREACH(routerset->policies, addr_policy_t *, p,
  5193. addr_policy_free(p));
  5194. smartlist_free(routerset->policies);
  5195. SMARTLIST_FOREACH(routerset->country_names, char *, cp, tor_free(cp));
  5196. smartlist_free(routerset->country_names);
  5197. strmap_free(routerset->names, NULL);
  5198. digestmap_free(routerset->digests, NULL);
  5199. bitarray_free(routerset->countries);
  5200. tor_free(routerset);
  5201. }
  5202. /** Refresh the country code of <b>ri</b>. This function MUST be called on
  5203. * each router when the GeoIP database is reloaded, and on all new routers. */
  5204. void
  5205. node_set_country(node_t *node)
  5206. {
  5207. if (node->rs)
  5208. node->country = geoip_get_country_by_ip(node->rs->addr);
  5209. else if (node->ri)
  5210. node->country = geoip_get_country_by_ip(node->ri->addr);
  5211. else
  5212. node->country = -1;
  5213. }
  5214. /** Set the country code of all routers in the routerlist. */
  5215. void
  5216. nodelist_refresh_countries(void) /* MOVE */
  5217. {
  5218. smartlist_t *nodes = nodelist_get_list();
  5219. SMARTLIST_FOREACH(nodes, node_t *, node,
  5220. node_set_country(node));
  5221. }
  5222. /** Determine the routers that are responsible for <b>id</b> (binary) and
  5223. * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
  5224. * Return -1 if we're returning an empty smartlist, else return 0.
  5225. */
  5226. int
  5227. hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  5228. const char *id)
  5229. {
  5230. int start, found, n_added = 0, i;
  5231. networkstatus_t *c = networkstatus_get_latest_consensus();
  5232. int use_begindir = get_options()->TunnelDirConns;
  5233. if (!c || !smartlist_len(c->routerstatus_list)) {
  5234. log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
  5235. "rendezvous operations.");
  5236. return -1;
  5237. }
  5238. tor_assert(id);
  5239. start = networkstatus_vote_find_entry_idx(c, id, &found);
  5240. if (start == smartlist_len(c->routerstatus_list)) start = 0;
  5241. i = start;
  5242. do {
  5243. routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
  5244. if (r->is_hs_dir) {
  5245. if (r->dir_port || use_begindir)
  5246. smartlist_add(responsible_dirs, r);
  5247. else
  5248. log_info(LD_REND, "Not adding router '%s' to list of responsible "
  5249. "hidden service directories, because we have no way of "
  5250. "reaching it.", r->nickname);
  5251. if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
  5252. break;
  5253. }
  5254. if (++i == smartlist_len(c->routerstatus_list))
  5255. i = 0;
  5256. } while (i != start);
  5257. /* Even though we don't have the desired number of hidden service
  5258. * directories, be happy if we got any. */
  5259. return smartlist_len(responsible_dirs) ? 0 : -1;
  5260. }
  5261. /** Return true if this node is currently acting as hidden service
  5262. * directory, false otherwise. */
  5263. int
  5264. hid_serv_acting_as_directory(void)
  5265. {
  5266. const routerinfo_t *me = router_get_my_routerinfo();
  5267. networkstatus_t *c;
  5268. const routerstatus_t *rs;
  5269. if (!me)
  5270. return 0;
  5271. if (!get_options()->HidServDirectoryV2) {
  5272. log_info(LD_REND, "We are not acting as hidden service directory, "
  5273. "because we have not been configured as such.");
  5274. return 0;
  5275. }
  5276. if (!(c = networkstatus_get_latest_consensus())) {
  5277. log_info(LD_REND, "There's no consensus, so I can't tell if I'm a hidden "
  5278. "service directory");
  5279. return 0;
  5280. }
  5281. rs = networkstatus_vote_find_entry(c, me->cache_info.identity_digest);
  5282. if (!rs) {
  5283. log_info(LD_REND, "We're not listed in the consensus, so we're not "
  5284. "being a hidden service directory.");
  5285. return 0;
  5286. }
  5287. if (!rs->is_hs_dir) {
  5288. log_info(LD_REND, "We're not listed as a hidden service directory in "
  5289. "the consensus, so we won't be one.");
  5290. return 0;
  5291. }
  5292. return 1;
  5293. }
  5294. /** Return true if this node is responsible for storing the descriptor ID
  5295. * in <b>query</b> and false otherwise. */
  5296. int
  5297. hid_serv_responsible_for_desc_id(const char *query)
  5298. {
  5299. const routerinfo_t *me;
  5300. routerstatus_t *last_rs;
  5301. const char *my_id, *last_id;
  5302. int result;
  5303. smartlist_t *responsible;
  5304. if (!hid_serv_acting_as_directory())
  5305. return 0;
  5306. if (!(me = router_get_my_routerinfo()))
  5307. return 0; /* This is redundant, but let's be paranoid. */
  5308. my_id = me->cache_info.identity_digest;
  5309. responsible = smartlist_create();
  5310. if (hid_serv_get_responsible_directories(responsible, query) < 0) {
  5311. smartlist_free(responsible);
  5312. return 0;
  5313. }
  5314. last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
  5315. last_id = last_rs->identity_digest;
  5316. result = rend_id_is_in_interval(my_id, query, last_id);
  5317. smartlist_free(responsible);
  5318. return result;
  5319. }