routerlist.c 181 KB

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