routerlist.c 202 KB

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