routerlist.c 173 KB

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