routerlist.c 186 KB

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