routerlist.c 171 KB

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