routerlist.c 199 KB

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