routerlist.c 186 KB

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