routerlist.c 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerlist.c
  8. * \brief Code to
  9. * maintain and access the global list of routerinfos for known
  10. * servers.
  11. **/
  12. #define ROUTERLIST_PRIVATE
  13. #include "or.h"
  14. #include "circuitstats.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "control.h"
  18. #include "directory.h"
  19. #include "dirserv.h"
  20. #include "dirvote.h"
  21. #include "entrynodes.h"
  22. #include "geoip.h"
  23. #include "hibernate.h"
  24. #include "main.h"
  25. #include "microdesc.h"
  26. #include "networkstatus.h"
  27. #include "nodelist.h"
  28. #include "policies.h"
  29. #include "reasons.h"
  30. #include "rendcommon.h"
  31. #include "rendservice.h"
  32. #include "rephist.h"
  33. #include "router.h"
  34. #include "routerlist.h"
  35. #include "routerparse.h"
  36. #include "routerset.h"
  37. // #define DEBUG_ROUTERLIST
  38. /****************************************************************************/
  39. /* static function prototypes */
  40. static const routerstatus_t *router_pick_directory_server_impl(
  41. dirinfo_type_t auth, int flags);
  42. static const routerstatus_t *router_pick_trusteddirserver_impl(
  43. dirinfo_type_t auth, int flags, int *n_busy_out);
  44. static void mark_all_trusteddirservers_up(void);
  45. static int router_nickname_matches(const routerinfo_t *router,
  46. const char *nickname);
  47. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  48. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  49. static const char *signed_descriptor_get_body_impl(
  50. const signed_descriptor_t *desc,
  51. int with_annotations);
  52. static void list_pending_downloads(digestmap_t *result,
  53. int purpose, const char *prefix);
  54. static void launch_dummy_descriptor_download_as_needed(time_t now,
  55. const or_options_t *options);
  56. DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
  57. DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
  58. DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
  59. #define SDMAP_FOREACH(map, keyvar, valvar) \
  60. DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
  61. valvar)
  62. #define RIMAP_FOREACH(map, keyvar, valvar) \
  63. DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
  64. #define EIMAP_FOREACH(map, keyvar, valvar) \
  65. DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
  66. /****************************************************************************/
  67. /** Global list of a trusted_dir_server_t object for each trusted directory
  68. * server. */
  69. static smartlist_t *trusted_dir_servers = NULL;
  70. /** List of for a given authority, and download status for latest certificate.
  71. */
  72. typedef struct cert_list_t {
  73. download_status_t dl_status;
  74. smartlist_t *certs;
  75. } cert_list_t;
  76. /** Map from v3 identity key digest to cert_list_t. */
  77. static digestmap_t *trusted_dir_certs = NULL;
  78. /** True iff any key certificate in at least one member of
  79. * <b>trusted_dir_certs</b> has changed since we last flushed the
  80. * certificates to disk. */
  81. static int trusted_dir_servers_certs_changed = 0;
  82. /** Global list of all of the routers that we know about. */
  83. static routerlist_t *routerlist = NULL;
  84. /** List of strings for nicknames we've already warned about and that are
  85. * still unknown / unavailable. */
  86. static smartlist_t *warned_nicknames = NULL;
  87. /** The last time we tried to download any routerdesc, or 0 for "never". We
  88. * use this to rate-limit download attempts when the number of routerdescs to
  89. * download is low. */
  90. static time_t last_descriptor_download_attempted = 0;
  91. /** When we last computed the weights to use for bandwidths on directory
  92. * requests, what were the total weighted bandwidth, and our share of that
  93. * bandwidth? Used to determine what fraction of directory requests we should
  94. * expect to see.
  95. *
  96. * @{ */
  97. static uint64_t sl_last_total_weighted_bw = 0,
  98. sl_last_weighted_bw_of_me = 0;
  99. /**@}*/
  100. /** Return the number of directory authorities whose type matches some bit set
  101. * in <b>type</b> */
  102. int
  103. get_n_authorities(dirinfo_type_t type)
  104. {
  105. int n = 0;
  106. if (!trusted_dir_servers)
  107. return 0;
  108. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  109. if (ds->type & type)
  110. ++n);
  111. return n;
  112. }
  113. #define get_n_v2_authorities() get_n_authorities(V2_DIRINFO)
  114. /** Helper: Return the cert_list_t for an authority whose authority ID is
  115. * <b>id_digest</b>, allocating a new list if necessary. */
  116. static cert_list_t *
  117. get_cert_list(const char *id_digest)
  118. {
  119. cert_list_t *cl;
  120. if (!trusted_dir_certs)
  121. trusted_dir_certs = digestmap_new();
  122. cl = digestmap_get(trusted_dir_certs, id_digest);
  123. if (!cl) {
  124. cl = tor_malloc_zero(sizeof(cert_list_t));
  125. cl->dl_status.schedule = DL_SCHED_CONSENSUS;
  126. cl->certs = smartlist_new();
  127. digestmap_set(trusted_dir_certs, id_digest, cl);
  128. }
  129. return cl;
  130. }
  131. /** Reload the cached v3 key certificates from the cached-certs file in
  132. * the data directory. Return 0 on success, -1 on failure. */
  133. int
  134. trusted_dirs_reload_certs(void)
  135. {
  136. char *filename;
  137. char *contents;
  138. int r;
  139. filename = get_datadir_fname("cached-certs");
  140. contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  141. tor_free(filename);
  142. if (!contents)
  143. return 0;
  144. r = trusted_dirs_load_certs_from_string(contents, 1, 1);
  145. tor_free(contents);
  146. return r;
  147. }
  148. /** Helper: return true iff we already have loaded the exact cert
  149. * <b>cert</b>. */
  150. static INLINE int
  151. already_have_cert(authority_cert_t *cert)
  152. {
  153. cert_list_t *cl = get_cert_list(cert->cache_info.identity_digest);
  154. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  155. {
  156. if (tor_memeq(c->cache_info.signed_descriptor_digest,
  157. cert->cache_info.signed_descriptor_digest,
  158. DIGEST_LEN))
  159. return 1;
  160. });
  161. return 0;
  162. }
  163. /** Load a bunch of new key certificates from the string <b>contents</b>. If
  164. * <b>from_store</b> is true, the certificates are from the cache, and we
  165. * don't need to flush them to disk. If <b>flush</b> is true, we need
  166. * to flush any changed certificates to disk now. Return 0 on success, -1
  167. * if any certs fail to parse. */
  168. int
  169. trusted_dirs_load_certs_from_string(const char *contents, int from_store,
  170. int flush)
  171. {
  172. trusted_dir_server_t *ds;
  173. const char *s, *eos;
  174. int failure_code = 0;
  175. for (s = contents; *s; s = eos) {
  176. authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
  177. cert_list_t *cl;
  178. if (!cert) {
  179. failure_code = -1;
  180. break;
  181. }
  182. ds = trusteddirserver_get_by_v3_auth_digest(
  183. cert->cache_info.identity_digest);
  184. log_debug(LD_DIR, "Parsed certificate for %s",
  185. ds ? ds->nickname : "unknown authority");
  186. if (already_have_cert(cert)) {
  187. /* we already have this one. continue. */
  188. log_info(LD_DIR, "Skipping %s certificate for %s that we "
  189. "already have.",
  190. from_store ? "cached" : "downloaded",
  191. ds ? ds->nickname : "an old or new authority");
  192. /* a duplicate on a download should be treated as a failure, since it
  193. * probably means we wanted a different secret key or we are trying to
  194. * replace an expired cert that has not in fact been updated. */
  195. if (!from_store) {
  196. if (authdir_mode(get_options())) {
  197. log_warn(LD_DIR,
  198. "Got a certificate for %s, but we already have it. "
  199. "Maybe they haven't updated it. Waiting for a while.",
  200. ds ? ds->nickname : "an old or new authority");
  201. } else {
  202. log_info(LD_DIR,
  203. "Got a certificate for %s, but we already have it. "
  204. "Maybe they haven't updated it. Waiting for a while.",
  205. ds ? ds->nickname : "an old or new authority");
  206. }
  207. authority_cert_dl_failed(cert->cache_info.identity_digest, 404);
  208. }
  209. authority_cert_free(cert);
  210. continue;
  211. }
  212. if (ds) {
  213. log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
  214. "signing key %s", from_store ? "cached" : "downloaded",
  215. ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
  216. } else {
  217. int adding = directory_caches_unknown_auth_certs(get_options());
  218. log_info(LD_DIR, "%s %s certificate for unrecognized directory "
  219. "authority with signing key %s",
  220. adding ? "Adding" : "Not adding",
  221. from_store ? "cached" : "downloaded",
  222. hex_str(cert->signing_key_digest,DIGEST_LEN));
  223. if (!adding) {
  224. authority_cert_free(cert);
  225. continue;
  226. }
  227. }
  228. cl = get_cert_list(cert->cache_info.identity_digest);
  229. smartlist_add(cl->certs, cert);
  230. if (ds && cert->cache_info.published_on > ds->addr_current_at) {
  231. /* Check to see whether we should update our view of the authority's
  232. * address. */
  233. if (cert->addr && cert->dir_port &&
  234. (ds->addr != cert->addr ||
  235. ds->dir_port != cert->dir_port)) {
  236. char *a = tor_dup_ip(cert->addr);
  237. log_notice(LD_DIR, "Updating address for directory authority %s "
  238. "from %s:%d to %s:%d based on certificate.",
  239. ds->nickname, ds->address, (int)ds->dir_port,
  240. a, cert->dir_port);
  241. tor_free(a);
  242. ds->addr = cert->addr;
  243. ds->dir_port = cert->dir_port;
  244. }
  245. ds->addr_current_at = cert->cache_info.published_on;
  246. }
  247. if (!from_store)
  248. trusted_dir_servers_certs_changed = 1;
  249. }
  250. if (flush)
  251. trusted_dirs_flush_certs_to_disk();
  252. /* call this even if failure_code is <0, since some certs might have
  253. * succeeded. */
  254. networkstatus_note_certs_arrived();
  255. return failure_code;
  256. }
  257. /** Save all v3 key certificates to the cached-certs file. */
  258. void
  259. trusted_dirs_flush_certs_to_disk(void)
  260. {
  261. char *filename;
  262. smartlist_t *chunks;
  263. if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
  264. return;
  265. chunks = smartlist_new();
  266. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  267. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  268. {
  269. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  270. c->bytes = cert->cache_info.signed_descriptor_body;
  271. c->len = cert->cache_info.signed_descriptor_len;
  272. smartlist_add(chunks, c);
  273. });
  274. } DIGESTMAP_FOREACH_END;
  275. filename = get_datadir_fname("cached-certs");
  276. if (write_chunks_to_file(filename, chunks, 0)) {
  277. log_warn(LD_FS, "Error writing certificates to disk.");
  278. }
  279. tor_free(filename);
  280. SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
  281. smartlist_free(chunks);
  282. trusted_dir_servers_certs_changed = 0;
  283. }
  284. /** Remove all v3 authority certificates that have been superseded for more
  285. * than 48 hours. (If the most recent cert was published more than 48 hours
  286. * ago, then we aren't going to get any consensuses signed with older
  287. * keys.) */
  288. static void
  289. trusted_dirs_remove_old_certs(void)
  290. {
  291. time_t now = time(NULL);
  292. #define DEAD_CERT_LIFETIME (2*24*60*60)
  293. #define OLD_CERT_LIFETIME (7*24*60*60)
  294. #define CERT_EXPIRY_SKEW (60*60)
  295. if (!trusted_dir_certs)
  296. return;
  297. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  298. authority_cert_t *newest = NULL;
  299. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  300. if (!newest || (cert->cache_info.published_on >
  301. newest->cache_info.published_on))
  302. newest = cert);
  303. if (newest) {
  304. const time_t newest_published = newest->cache_info.published_on;
  305. SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
  306. int expired;
  307. time_t cert_published;
  308. if (newest == cert)
  309. continue;
  310. expired = now > cert->expires;
  311. cert_published = cert->cache_info.published_on;
  312. /* Store expired certs for 48 hours after a newer arrives;
  313. */
  314. if (expired ?
  315. (newest_published + DEAD_CERT_LIFETIME < now) :
  316. (cert_published + OLD_CERT_LIFETIME < newest_published)) {
  317. SMARTLIST_DEL_CURRENT(cl->certs, cert);
  318. authority_cert_free(cert);
  319. trusted_dir_servers_certs_changed = 1;
  320. }
  321. } SMARTLIST_FOREACH_END(cert);
  322. }
  323. } DIGESTMAP_FOREACH_END;
  324. #undef OLD_CERT_LIFETIME
  325. trusted_dirs_flush_certs_to_disk();
  326. }
  327. /** Return the newest v3 authority certificate whose v3 authority identity key
  328. * has digest <b>id_digest</b>. Return NULL if no such authority is known,
  329. * or it has no certificate. */
  330. authority_cert_t *
  331. authority_cert_get_newest_by_id(const char *id_digest)
  332. {
  333. cert_list_t *cl;
  334. authority_cert_t *best = NULL;
  335. if (!trusted_dir_certs ||
  336. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  337. return NULL;
  338. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  339. {
  340. if (!best || cert->cache_info.published_on > best->cache_info.published_on)
  341. best = cert;
  342. });
  343. return best;
  344. }
  345. /** Return the newest v3 authority certificate whose directory signing key has
  346. * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
  347. */
  348. authority_cert_t *
  349. authority_cert_get_by_sk_digest(const char *sk_digest)
  350. {
  351. authority_cert_t *c;
  352. if (!trusted_dir_certs)
  353. return NULL;
  354. if ((c = get_my_v3_authority_cert()) &&
  355. tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
  356. return c;
  357. if ((c = get_my_v3_legacy_cert()) &&
  358. tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
  359. return c;
  360. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  361. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  362. {
  363. if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  364. return cert;
  365. });
  366. } DIGESTMAP_FOREACH_END;
  367. return NULL;
  368. }
  369. /** Return the v3 authority certificate with signing key matching
  370. * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
  371. * Return NULL if no such authority is known. */
  372. authority_cert_t *
  373. authority_cert_get_by_digests(const char *id_digest,
  374. const char *sk_digest)
  375. {
  376. cert_list_t *cl;
  377. if (!trusted_dir_certs ||
  378. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  379. return NULL;
  380. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  381. if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  382. return cert; );
  383. return NULL;
  384. }
  385. /** Add every known authority_cert_t to <b>certs_out</b>. */
  386. void
  387. authority_cert_get_all(smartlist_t *certs_out)
  388. {
  389. tor_assert(certs_out);
  390. if (!trusted_dir_certs)
  391. return;
  392. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  393. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  394. smartlist_add(certs_out, c));
  395. } DIGESTMAP_FOREACH_END;
  396. }
  397. /** Called when an attempt to download a certificate with the authority with
  398. * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
  399. * the failure, so we don't try again immediately. */
  400. void
  401. authority_cert_dl_failed(const char *id_digest, int status)
  402. {
  403. cert_list_t *cl;
  404. if (!trusted_dir_certs ||
  405. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  406. return;
  407. download_status_failed(&cl->dl_status, status);
  408. }
  409. /** Return true iff when we've been getting enough failures when trying to
  410. * download the certificate with ID digest <b>id_digest</b> that we're willing
  411. * to start bugging the user about it. */
  412. int
  413. authority_cert_dl_looks_uncertain(const char *id_digest)
  414. {
  415. #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
  416. cert_list_t *cl;
  417. int n_failures;
  418. if (!trusted_dir_certs ||
  419. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  420. return 0;
  421. n_failures = download_status_get_n_failures(&cl->dl_status);
  422. return n_failures >= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER;
  423. }
  424. /** How many times will we try to fetch a certificate before giving up? */
  425. #define MAX_CERT_DL_FAILURES 8
  426. /** Try to download any v3 authority certificates that we may be missing. If
  427. * <b>status</b> is provided, try to get all the ones that were used to sign
  428. * <b>status</b>. Additionally, try to have a non-expired certificate for
  429. * every V3 authority in trusted_dir_servers. Don't fetch certificates we
  430. * already have.
  431. **/
  432. void
  433. authority_certs_fetch_missing(networkstatus_t *status, time_t now)
  434. {
  435. digestmap_t *pending;
  436. authority_cert_t *cert;
  437. smartlist_t *missing_digests;
  438. char *resource = NULL;
  439. cert_list_t *cl;
  440. const int cache = directory_caches_unknown_auth_certs(get_options());
  441. if (should_delay_dir_fetches(get_options()))
  442. return;
  443. pending = digestmap_new();
  444. missing_digests = smartlist_new();
  445. list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
  446. if (status) {
  447. SMARTLIST_FOREACH_BEGIN(status->voters, networkstatus_voter_info_t *,
  448. voter) {
  449. if (!smartlist_len(voter->sigs))
  450. continue; /* This authority never signed this consensus, so don't
  451. * go looking for a cert with key digest 0000000000. */
  452. if (!cache &&
  453. !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
  454. continue; /* We are not a cache, and we don't know this authority.*/
  455. cl = get_cert_list(voter->identity_digest);
  456. SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
  457. cert = authority_cert_get_by_digests(voter->identity_digest,
  458. sig->signing_key_digest);
  459. if (cert) {
  460. if (now < cert->expires)
  461. download_status_reset(&cl->dl_status);
  462. continue;
  463. }
  464. if (download_status_is_ready(&cl->dl_status, now,
  465. MAX_CERT_DL_FAILURES) &&
  466. !digestmap_get(pending, voter->identity_digest)) {
  467. log_info(LD_DIR, "We're missing a certificate from authority "
  468. "with signing key %s: launching request.",
  469. hex_str(sig->signing_key_digest, DIGEST_LEN));
  470. smartlist_add(missing_digests, sig->identity_digest);
  471. }
  472. } SMARTLIST_FOREACH_END(sig);
  473. } SMARTLIST_FOREACH_END(voter);
  474. }
  475. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds) {
  476. int found = 0;
  477. if (!(ds->type & V3_DIRINFO))
  478. continue;
  479. if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
  480. continue;
  481. cl = get_cert_list(ds->v3_identity_digest);
  482. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert, {
  483. if (now < cert->expires) {
  484. /* It's not expired, and we weren't looking for something to
  485. * verify a consensus with. Call it done. */
  486. download_status_reset(&cl->dl_status);
  487. found = 1;
  488. break;
  489. }
  490. });
  491. if (!found &&
  492. download_status_is_ready(&cl->dl_status, now,MAX_CERT_DL_FAILURES) &&
  493. !digestmap_get(pending, ds->v3_identity_digest)) {
  494. log_info(LD_DIR, "No current certificate known for authority %s; "
  495. "launching request.", ds->nickname);
  496. smartlist_add(missing_digests, ds->v3_identity_digest);
  497. }
  498. } SMARTLIST_FOREACH_END(ds);
  499. if (!smartlist_len(missing_digests)) {
  500. goto done;
  501. } else {
  502. smartlist_t *fps = smartlist_new();
  503. smartlist_add(fps, tor_strdup("fp/"));
  504. SMARTLIST_FOREACH(missing_digests, const char *, d, {
  505. char *fp;
  506. if (digestmap_get(pending, d))
  507. continue;
  508. fp = tor_malloc(HEX_DIGEST_LEN+2);
  509. base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  510. fp[HEX_DIGEST_LEN] = '+';
  511. fp[HEX_DIGEST_LEN+1] = '\0';
  512. smartlist_add(fps, fp);
  513. });
  514. if (smartlist_len(fps) == 1) {
  515. /* we didn't add any: they were all pending */
  516. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  517. smartlist_free(fps);
  518. goto done;
  519. }
  520. resource = smartlist_join_strings(fps, "", 0, NULL);
  521. resource[strlen(resource)-1] = '\0';
  522. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  523. smartlist_free(fps);
  524. }
  525. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
  526. resource, PDS_RETRY_IF_NO_SERVERS);
  527. done:
  528. tor_free(resource);
  529. smartlist_free(missing_digests);
  530. digestmap_free(pending, NULL);
  531. }
  532. /* Router descriptor storage.
  533. *
  534. * Routerdescs are stored in a big file, named "cached-descriptors". As new
  535. * routerdescs arrive, we append them to a journal file named
  536. * "cached-descriptors.new".
  537. *
  538. * From time to time, we replace "cached-descriptors" with a new file
  539. * containing only the live, non-superseded descriptors, and clear
  540. * cached-routers.new.
  541. *
  542. * On startup, we read both files.
  543. */
  544. /** Helper: return 1 iff the router log is so big we want to rebuild the
  545. * store. */
  546. static int
  547. router_should_rebuild_store(desc_store_t *store)
  548. {
  549. if (store->store_len > (1<<16))
  550. return (store->journal_len > store->store_len / 2 ||
  551. store->bytes_dropped > store->store_len / 2);
  552. else
  553. return store->journal_len > (1<<15);
  554. }
  555. /** Return the desc_store_t in <b>rl</b> that should be used to store
  556. * <b>sd</b>. */
  557. static INLINE desc_store_t *
  558. desc_get_store(routerlist_t *rl, const signed_descriptor_t *sd)
  559. {
  560. if (sd->is_extrainfo)
  561. return &rl->extrainfo_store;
  562. else
  563. return &rl->desc_store;
  564. }
  565. /** Add the signed_descriptor_t in <b>desc</b> to the router
  566. * journal; change its saved_location to SAVED_IN_JOURNAL and set its
  567. * offset appropriately. */
  568. static int
  569. signed_desc_append_to_journal(signed_descriptor_t *desc,
  570. desc_store_t *store)
  571. {
  572. char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
  573. const char *body = signed_descriptor_get_body_impl(desc,1);
  574. size_t len = desc->signed_descriptor_len + desc->annotations_len;
  575. if (append_bytes_to_file(fname, body, len, 1)) {
  576. log_warn(LD_FS, "Unable to store router descriptor");
  577. tor_free(fname);
  578. return -1;
  579. }
  580. desc->saved_location = SAVED_IN_JOURNAL;
  581. tor_free(fname);
  582. desc->saved_offset = store->journal_len;
  583. store->journal_len += len;
  584. return 0;
  585. }
  586. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  587. * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
  588. * the signed_descriptor_t* in *<b>b</b>. */
  589. static int
  590. compare_signed_descriptors_by_age_(const void **_a, const void **_b)
  591. {
  592. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  593. return (int)(r1->published_on - r2->published_on);
  594. }
  595. #define RRS_FORCE 1
  596. #define RRS_DONT_REMOVE_OLD 2
  597. /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
  598. * <b>flags</b>, then atomically replace the saved router store with the
  599. * routers currently in our routerlist, and clear the journal. Unless
  600. * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
  601. * rebuilding the store. Return 0 on success, -1 on failure.
  602. */
  603. static int
  604. router_rebuild_store(int flags, desc_store_t *store)
  605. {
  606. smartlist_t *chunk_list = NULL;
  607. char *fname = NULL, *fname_tmp = NULL;
  608. int r = -1;
  609. off_t offset = 0;
  610. smartlist_t *signed_descriptors = NULL;
  611. int nocache=0;
  612. size_t total_expected_len = 0;
  613. int had_any;
  614. int force = flags & RRS_FORCE;
  615. if (!force && !router_should_rebuild_store(store)) {
  616. r = 0;
  617. goto done;
  618. }
  619. if (!routerlist) {
  620. r = 0;
  621. goto done;
  622. }
  623. if (store->type == EXTRAINFO_STORE)
  624. had_any = !eimap_isempty(routerlist->extra_info_map);
  625. else
  626. had_any = (smartlist_len(routerlist->routers)+
  627. smartlist_len(routerlist->old_routers))>0;
  628. /* Don't save deadweight. */
  629. if (!(flags & RRS_DONT_REMOVE_OLD))
  630. routerlist_remove_old_routers();
  631. log_info(LD_DIR, "Rebuilding %s cache", store->description);
  632. fname = get_datadir_fname(store->fname_base);
  633. fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
  634. chunk_list = smartlist_new();
  635. /* We sort the routers by age to enhance locality on disk. */
  636. signed_descriptors = smartlist_new();
  637. if (store->type == EXTRAINFO_STORE) {
  638. eimap_iter_t *iter;
  639. for (iter = eimap_iter_init(routerlist->extra_info_map);
  640. !eimap_iter_done(iter);
  641. iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
  642. const char *key;
  643. extrainfo_t *ei;
  644. eimap_iter_get(iter, &key, &ei);
  645. smartlist_add(signed_descriptors, &ei->cache_info);
  646. }
  647. } else {
  648. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  649. smartlist_add(signed_descriptors, sd));
  650. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  651. smartlist_add(signed_descriptors, &ri->cache_info));
  652. }
  653. smartlist_sort(signed_descriptors, compare_signed_descriptors_by_age_);
  654. /* Now, add the appropriate members to chunk_list */
  655. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  656. sized_chunk_t *c;
  657. const char *body = signed_descriptor_get_body_impl(sd, 1);
  658. if (!body) {
  659. log_warn(LD_BUG, "No descriptor available for router.");
  660. goto done;
  661. }
  662. if (sd->do_not_cache) {
  663. ++nocache;
  664. continue;
  665. }
  666. c = tor_malloc(sizeof(sized_chunk_t));
  667. c->bytes = body;
  668. c->len = sd->signed_descriptor_len + sd->annotations_len;
  669. total_expected_len += c->len;
  670. smartlist_add(chunk_list, c);
  671. } SMARTLIST_FOREACH_END(sd);
  672. if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
  673. log_warn(LD_FS, "Error writing router store to disk.");
  674. goto done;
  675. }
  676. /* Our mmap is now invalid. */
  677. if (store->mmap) {
  678. tor_munmap_file(store->mmap);
  679. store->mmap = NULL;
  680. }
  681. if (replace_file(fname_tmp, fname)<0) {
  682. log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
  683. goto done;
  684. }
  685. errno = 0;
  686. store->mmap = tor_mmap_file(fname);
  687. if (! store->mmap) {
  688. if (errno == ERANGE) {
  689. /* empty store.*/
  690. if (total_expected_len) {
  691. log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
  692. " but when we went to mmap it, it was empty!", fname);
  693. } else if (had_any) {
  694. log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
  695. "okay if we're just starting up after a long time. "
  696. "Otherwise, it's a bug.", fname);
  697. }
  698. } else {
  699. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  700. }
  701. }
  702. log_info(LD_DIR, "Reconstructing pointers into cache");
  703. offset = 0;
  704. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  705. if (sd->do_not_cache)
  706. continue;
  707. sd->saved_location = SAVED_IN_CACHE;
  708. if (store->mmap) {
  709. tor_free(sd->signed_descriptor_body); // sets it to null
  710. sd->saved_offset = offset;
  711. }
  712. offset += sd->signed_descriptor_len + sd->annotations_len;
  713. signed_descriptor_get_body(sd); /* reconstruct and assert */
  714. } SMARTLIST_FOREACH_END(sd);
  715. tor_free(fname);
  716. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  717. write_str_to_file(fname, "", 1);
  718. r = 0;
  719. store->store_len = (size_t) offset;
  720. store->journal_len = 0;
  721. store->bytes_dropped = 0;
  722. done:
  723. smartlist_free(signed_descriptors);
  724. tor_free(fname);
  725. tor_free(fname_tmp);
  726. if (chunk_list) {
  727. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  728. smartlist_free(chunk_list);
  729. }
  730. return r;
  731. }
  732. /** Helper: Reload a cache file and its associated journal, setting metadata
  733. * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
  734. * else reload the router descriptor store. */
  735. static int
  736. router_reload_router_list_impl(desc_store_t *store)
  737. {
  738. char *fname = NULL, *altname = NULL, *contents = NULL;
  739. struct stat st;
  740. int read_from_old_location = 0;
  741. int extrainfo = (store->type == EXTRAINFO_STORE);
  742. time_t now = time(NULL);
  743. store->journal_len = store->store_len = 0;
  744. fname = get_datadir_fname(store->fname_base);
  745. if (store->fname_alt_base)
  746. altname = get_datadir_fname(store->fname_alt_base);
  747. if (store->mmap) /* get rid of it first */
  748. tor_munmap_file(store->mmap);
  749. store->mmap = NULL;
  750. store->mmap = tor_mmap_file(fname);
  751. if (!store->mmap && altname && file_status(altname) == FN_FILE) {
  752. read_from_old_location = 1;
  753. log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
  754. "location %s.", fname, altname);
  755. if ((store->mmap = tor_mmap_file(altname)))
  756. read_from_old_location = 1;
  757. }
  758. if (altname && !read_from_old_location) {
  759. remove_file_if_very_old(altname, now);
  760. }
  761. if (store->mmap) {
  762. store->store_len = store->mmap->size;
  763. if (extrainfo)
  764. router_load_extrainfo_from_string(store->mmap->data,
  765. store->mmap->data+store->mmap->size,
  766. SAVED_IN_CACHE, NULL, 0);
  767. else
  768. router_load_routers_from_string(store->mmap->data,
  769. store->mmap->data+store->mmap->size,
  770. SAVED_IN_CACHE, NULL, 0, NULL);
  771. }
  772. tor_free(fname);
  773. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  774. if (file_status(fname) == FN_FILE)
  775. contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  776. if (read_from_old_location) {
  777. tor_free(altname);
  778. altname = get_datadir_fname_suffix(store->fname_alt_base, ".new");
  779. if (!contents)
  780. contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  781. else
  782. remove_file_if_very_old(altname, now);
  783. }
  784. if (contents) {
  785. if (extrainfo)
  786. router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
  787. NULL, 0);
  788. else
  789. router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
  790. NULL, 0, NULL);
  791. store->journal_len = (size_t) st.st_size;
  792. tor_free(contents);
  793. }
  794. tor_free(fname);
  795. tor_free(altname);
  796. if (store->journal_len || read_from_old_location) {
  797. /* Always clear the journal on startup.*/
  798. router_rebuild_store(RRS_FORCE, store);
  799. } else if (!extrainfo) {
  800. /* Don't cache expired routers. (This is in an else because
  801. * router_rebuild_store() also calls remove_old_routers().) */
  802. routerlist_remove_old_routers();
  803. }
  804. return 0;
  805. }
  806. /** Load all cached router descriptors and extra-info documents from the
  807. * store. Return 0 on success and -1 on failure.
  808. */
  809. int
  810. router_reload_router_list(void)
  811. {
  812. routerlist_t *rl = router_get_routerlist();
  813. if (router_reload_router_list_impl(&rl->desc_store))
  814. return -1;
  815. if (router_reload_router_list_impl(&rl->extrainfo_store))
  816. return -1;
  817. return 0;
  818. }
  819. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  820. * known trusted dirservers. Callers must not modify the list or its
  821. * contents.
  822. */
  823. smartlist_t *
  824. router_get_trusted_dir_servers(void)
  825. {
  826. if (!trusted_dir_servers)
  827. trusted_dir_servers = smartlist_new();
  828. return trusted_dir_servers;
  829. }
  830. /** Try to find a running dirserver that supports operations of <b>type</b>.
  831. *
  832. * If there are no running dirservers in our routerlist and the
  833. * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
  834. * as running again, and pick one.
  835. *
  836. * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
  837. * dirservers that we can't reach.
  838. *
  839. * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
  840. * (if we're a dirserver).
  841. *
  842. * Don't pick an authority if any non-authority is viable; try to avoid using
  843. * servers that have returned 503 recently.
  844. */
  845. const routerstatus_t *
  846. router_pick_directory_server(dirinfo_type_t type, int flags)
  847. {
  848. const routerstatus_t *choice;
  849. if (get_options()->PreferTunneledDirConns)
  850. flags |= PDS_PREFER_TUNNELED_DIR_CONNS_;
  851. if (!routerlist)
  852. return NULL;
  853. choice = router_pick_directory_server_impl(type, flags);
  854. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  855. return choice;
  856. log_info(LD_DIR,
  857. "No reachable router entries for dirservers. "
  858. "Trying them all again.");
  859. /* mark all authdirservers as up again */
  860. mark_all_trusteddirservers_up();
  861. /* try again */
  862. choice = router_pick_directory_server_impl(type, flags);
  863. return choice;
  864. }
  865. /** Try to determine which fraction of v2 and v3 directory requests aimed at
  866. * caches will be sent to us. Set *<b>v2_share_out</b> and
  867. * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
  868. * expect to see, respectively. Return 0 on success, negative on failure. */
  869. int
  870. router_get_my_share_of_directory_requests(double *v2_share_out,
  871. double *v3_share_out)
  872. {
  873. const routerinfo_t *me = router_get_my_routerinfo();
  874. const routerstatus_t *rs;
  875. const int pds_flags = PDS_ALLOW_SELF|PDS_IGNORE_FASCISTFIREWALL;
  876. *v2_share_out = *v3_share_out = 0.0;
  877. if (!me)
  878. return -1;
  879. rs = router_get_consensus_status_by_id(me->cache_info.identity_digest);
  880. if (!rs)
  881. return -1;
  882. /* Calling for side effect */
  883. /* XXXX This is a bit of a kludge */
  884. if (rs->is_v2_dir) {
  885. sl_last_total_weighted_bw = 0;
  886. router_pick_directory_server(V2_DIRINFO, pds_flags);
  887. if (sl_last_total_weighted_bw != 0) {
  888. *v2_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  889. U64_TO_DBL(sl_last_total_weighted_bw);
  890. }
  891. }
  892. {
  893. sl_last_total_weighted_bw = 0;
  894. router_pick_directory_server(V3_DIRINFO, pds_flags);
  895. if (sl_last_total_weighted_bw != 0) {
  896. *v3_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  897. U64_TO_DBL(sl_last_total_weighted_bw);
  898. }
  899. }
  900. return 0;
  901. }
  902. /** Return the trusted_dir_server_t for the directory authority whose identity
  903. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  904. */
  905. trusted_dir_server_t *
  906. router_get_trusteddirserver_by_digest(const char *digest)
  907. {
  908. if (!trusted_dir_servers)
  909. return NULL;
  910. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  911. {
  912. if (tor_memeq(ds->digest, digest, DIGEST_LEN))
  913. return ds;
  914. });
  915. return NULL;
  916. }
  917. /** Return the trusted_dir_server_t for the directory authority whose
  918. * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
  919. * is known.
  920. */
  921. trusted_dir_server_t *
  922. trusteddirserver_get_by_v3_auth_digest(const char *digest)
  923. {
  924. if (!trusted_dir_servers)
  925. return NULL;
  926. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  927. {
  928. if (tor_memeq(ds->v3_identity_digest, digest, DIGEST_LEN) &&
  929. (ds->type & V3_DIRINFO))
  930. return ds;
  931. });
  932. return NULL;
  933. }
  934. /** Try to find a running trusted dirserver. Flags are as for
  935. * router_pick_directory_server.
  936. */
  937. const routerstatus_t *
  938. router_pick_trusteddirserver(dirinfo_type_t type, int flags)
  939. {
  940. const routerstatus_t *choice;
  941. int busy = 0;
  942. if (get_options()->PreferTunneledDirConns)
  943. flags |= PDS_PREFER_TUNNELED_DIR_CONNS_;
  944. choice = router_pick_trusteddirserver_impl(type, flags, &busy);
  945. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  946. return choice;
  947. if (busy) {
  948. /* If the reason that we got no server is that servers are "busy",
  949. * we must be excluding good servers because we already have serverdesc
  950. * fetches with them. Do not mark down servers up because of this. */
  951. tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  952. PDS_NO_EXISTING_MICRODESC_FETCH)));
  953. return NULL;
  954. }
  955. log_info(LD_DIR,
  956. "No trusted dirservers are reachable. Trying them all again.");
  957. mark_all_trusteddirservers_up();
  958. return router_pick_trusteddirserver_impl(type, flags, NULL);
  959. }
  960. /** How long do we avoid using a directory server after it's given us a 503? */
  961. #define DIR_503_TIMEOUT (60*60)
  962. /** Pick a random running valid directory server/mirror from our
  963. * routerlist. Arguments are as for router_pick_directory_server(), except
  964. * that RETRY_IF_NO_SERVERS is ignored, and:
  965. *
  966. * If the PDS_PREFER_TUNNELED_DIR_CONNS_ flag is set, prefer directory servers
  967. * that we can use with BEGINDIR.
  968. */
  969. static const routerstatus_t *
  970. router_pick_directory_server_impl(dirinfo_type_t type, int flags)
  971. {
  972. const or_options_t *options = get_options();
  973. const node_t *result;
  974. smartlist_t *direct, *tunnel;
  975. smartlist_t *trusted_direct, *trusted_tunnel;
  976. smartlist_t *overloaded_direct, *overloaded_tunnel;
  977. time_t now = time(NULL);
  978. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  979. int requireother = ! (flags & PDS_ALLOW_SELF);
  980. int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  981. int prefer_tunnel = (flags & PDS_PREFER_TUNNELED_DIR_CONNS_);
  982. int try_excluding = 1, n_excluded = 0;
  983. if (!consensus)
  984. return NULL;
  985. retry_without_exclude:
  986. direct = smartlist_new();
  987. tunnel = smartlist_new();
  988. trusted_direct = smartlist_new();
  989. trusted_tunnel = smartlist_new();
  990. overloaded_direct = smartlist_new();
  991. overloaded_tunnel = smartlist_new();
  992. /* Find all the running dirservers we know about. */
  993. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  994. int is_trusted;
  995. int is_overloaded;
  996. tor_addr_t addr;
  997. const routerstatus_t *status = node->rs;
  998. const country_t country = node->country;
  999. if (!status)
  1000. continue;
  1001. if (!node->is_running || !status->dir_port || !node->is_valid)
  1002. continue;
  1003. if (node->is_bad_directory)
  1004. continue;
  1005. if (requireother && router_digest_is_me(node->identity))
  1006. continue;
  1007. is_trusted = router_digest_is_trusted_dir(node->identity);
  1008. if ((type & V2_DIRINFO) && !(node->rs->is_v2_dir || is_trusted))
  1009. continue;
  1010. if ((type & EXTRAINFO_DIRINFO) &&
  1011. !router_supports_extrainfo(node->identity, 0))
  1012. continue;
  1013. if ((type & MICRODESC_DIRINFO) && !is_trusted &&
  1014. !node->rs->version_supports_microdesc_cache)
  1015. continue;
  1016. if (try_excluding &&
  1017. routerset_contains_routerstatus(options->ExcludeNodes, status,
  1018. country)) {
  1019. ++n_excluded;
  1020. continue;
  1021. }
  1022. /* XXXX IP6 proposal 118 */
  1023. tor_addr_from_ipv4h(&addr, node->rs->addr);
  1024. is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
  1025. if (prefer_tunnel &&
  1026. (!fascistfirewall ||
  1027. fascist_firewall_allows_address_or(&addr, status->or_port)))
  1028. smartlist_add(is_trusted ? trusted_tunnel :
  1029. is_overloaded ? overloaded_tunnel : tunnel, (void*)node);
  1030. else if (!fascistfirewall ||
  1031. fascist_firewall_allows_address_dir(&addr, status->dir_port))
  1032. smartlist_add(is_trusted ? trusted_direct :
  1033. is_overloaded ? overloaded_direct : direct, (void*)node);
  1034. } SMARTLIST_FOREACH_END(node);
  1035. if (smartlist_len(tunnel)) {
  1036. result = node_sl_choose_by_bandwidth(tunnel, WEIGHT_FOR_DIR);
  1037. } else if (smartlist_len(overloaded_tunnel)) {
  1038. result = node_sl_choose_by_bandwidth(overloaded_tunnel,
  1039. WEIGHT_FOR_DIR);
  1040. } else if (smartlist_len(trusted_tunnel)) {
  1041. /* FFFF We don't distinguish between trusteds and overloaded trusteds
  1042. * yet. Maybe one day we should. */
  1043. /* FFFF We also don't load balance over authorities yet. I think this
  1044. * is a feature, but it could easily be a bug. -RD */
  1045. result = smartlist_choose(trusted_tunnel);
  1046. } else if (smartlist_len(direct)) {
  1047. result = node_sl_choose_by_bandwidth(direct, WEIGHT_FOR_DIR);
  1048. } else if (smartlist_len(overloaded_direct)) {
  1049. result = node_sl_choose_by_bandwidth(overloaded_direct,
  1050. WEIGHT_FOR_DIR);
  1051. } else {
  1052. result = smartlist_choose(trusted_direct);
  1053. }
  1054. smartlist_free(direct);
  1055. smartlist_free(tunnel);
  1056. smartlist_free(trusted_direct);
  1057. smartlist_free(trusted_tunnel);
  1058. smartlist_free(overloaded_direct);
  1059. smartlist_free(overloaded_tunnel);
  1060. if (result == NULL && try_excluding && !options->StrictNodes && n_excluded) {
  1061. /* If we got no result, and we are excluding nodes, and StrictNodes is
  1062. * not set, try again without excluding nodes. */
  1063. try_excluding = 0;
  1064. n_excluded = 0;
  1065. goto retry_without_exclude;
  1066. }
  1067. return result ? result->rs : NULL;
  1068. }
  1069. /** Choose randomly from among the trusted dirservers that are up. Flags
  1070. * are as for router_pick_directory_server_impl().
  1071. */
  1072. static const routerstatus_t *
  1073. router_pick_trusteddirserver_impl(dirinfo_type_t type, int flags,
  1074. int *n_busy_out)
  1075. {
  1076. const or_options_t *options = get_options();
  1077. smartlist_t *direct, *tunnel;
  1078. smartlist_t *overloaded_direct, *overloaded_tunnel;
  1079. const routerinfo_t *me = router_get_my_routerinfo();
  1080. const routerstatus_t *result;
  1081. time_t now = time(NULL);
  1082. const int requireother = ! (flags & PDS_ALLOW_SELF);
  1083. const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  1084. const int prefer_tunnel = (flags & PDS_PREFER_TUNNELED_DIR_CONNS_);
  1085. const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
  1086. const int no_microdesc_fetching =(flags & PDS_NO_EXISTING_MICRODESC_FETCH);
  1087. int n_busy = 0;
  1088. int try_excluding = 1, n_excluded = 0;
  1089. if (!trusted_dir_servers)
  1090. return NULL;
  1091. retry_without_exclude:
  1092. direct = smartlist_new();
  1093. tunnel = smartlist_new();
  1094. overloaded_direct = smartlist_new();
  1095. overloaded_tunnel = smartlist_new();
  1096. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, d)
  1097. {
  1098. int is_overloaded =
  1099. d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
  1100. tor_addr_t addr;
  1101. if (!d->is_running) continue;
  1102. if ((type & d->type) == 0)
  1103. continue;
  1104. if ((type & EXTRAINFO_DIRINFO) &&
  1105. !router_supports_extrainfo(d->digest, 1))
  1106. continue;
  1107. if (requireother && me && router_digest_is_me(d->digest))
  1108. continue;
  1109. if (try_excluding &&
  1110. routerset_contains_routerstatus(options->ExcludeNodes,
  1111. &d->fake_status, -1)) {
  1112. ++n_excluded;
  1113. continue;
  1114. }
  1115. /* XXXX IP6 proposal 118 */
  1116. tor_addr_from_ipv4h(&addr, d->addr);
  1117. if (no_serverdesc_fetching) {
  1118. if (connection_get_by_type_addr_port_purpose(
  1119. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_SERVERDESC)
  1120. || connection_get_by_type_addr_port_purpose(
  1121. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_EXTRAINFO)) {
  1122. //log_debug(LD_DIR, "We have an existing connection to fetch "
  1123. // "descriptor from %s; delaying",d->description);
  1124. ++n_busy;
  1125. continue;
  1126. }
  1127. }
  1128. if (no_microdesc_fetching) {
  1129. if (connection_get_by_type_addr_port_purpose(
  1130. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_MICRODESC)) {
  1131. ++n_busy;
  1132. continue;
  1133. }
  1134. }
  1135. if (prefer_tunnel &&
  1136. d->or_port &&
  1137. (!fascistfirewall ||
  1138. fascist_firewall_allows_address_or(&addr, d->or_port)))
  1139. smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
  1140. &d->fake_status);
  1141. else if (!fascistfirewall ||
  1142. fascist_firewall_allows_address_dir(&addr, d->dir_port))
  1143. smartlist_add(is_overloaded ? overloaded_direct : direct,
  1144. &d->fake_status);
  1145. }
  1146. SMARTLIST_FOREACH_END(d);
  1147. if (smartlist_len(tunnel)) {
  1148. result = smartlist_choose(tunnel);
  1149. } else if (smartlist_len(overloaded_tunnel)) {
  1150. result = smartlist_choose(overloaded_tunnel);
  1151. } else if (smartlist_len(direct)) {
  1152. result = smartlist_choose(direct);
  1153. } else {
  1154. result = smartlist_choose(overloaded_direct);
  1155. }
  1156. if (n_busy_out)
  1157. *n_busy_out = n_busy;
  1158. smartlist_free(direct);
  1159. smartlist_free(tunnel);
  1160. smartlist_free(overloaded_direct);
  1161. smartlist_free(overloaded_tunnel);
  1162. if (result == NULL && try_excluding && !options->StrictNodes && n_excluded) {
  1163. /* If we got no result, and we are excluding nodes, and StrictNodes is
  1164. * not set, try again without excluding nodes. */
  1165. try_excluding = 0;
  1166. n_excluded = 0;
  1167. goto retry_without_exclude;
  1168. }
  1169. return result;
  1170. }
  1171. /** Go through and mark the authoritative dirservers as up. */
  1172. static void
  1173. mark_all_trusteddirservers_up(void)
  1174. {
  1175. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node, {
  1176. if (router_digest_is_trusted_dir(node->identity))
  1177. node->is_running = 1;
  1178. });
  1179. if (trusted_dir_servers) {
  1180. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, dir) {
  1181. routerstatus_t *rs;
  1182. dir->is_running = 1;
  1183. download_status_reset(&dir->v2_ns_dl_status);
  1184. rs = router_get_mutable_consensus_status_by_id(dir->digest);
  1185. if (rs) {
  1186. rs->last_dir_503_at = 0;
  1187. control_event_networkstatus_changed_single(rs);
  1188. }
  1189. } SMARTLIST_FOREACH_END(dir);
  1190. }
  1191. router_dir_info_changed();
  1192. }
  1193. /** Return true iff r1 and r2 have the same address and OR port. */
  1194. int
  1195. routers_have_same_or_addrs(const routerinfo_t *r1, const routerinfo_t *r2)
  1196. {
  1197. return r1->addr == r2->addr && r1->or_port == r2->or_port &&
  1198. tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) &&
  1199. r1->ipv6_orport == r2->ipv6_orport;
  1200. }
  1201. /** Reset all internal variables used to count failed downloads of network
  1202. * status objects. */
  1203. void
  1204. router_reset_status_download_failures(void)
  1205. {
  1206. mark_all_trusteddirservers_up();
  1207. }
  1208. /** Given a <b>router</b>, add every node_t in its family (including the
  1209. * node itself!) to <b>sl</b>.
  1210. *
  1211. * Note the type mismatch: This function takes a routerinfo, but adds nodes
  1212. * to the smartlist!
  1213. */
  1214. static void
  1215. routerlist_add_node_and_family(smartlist_t *sl, const routerinfo_t *router)
  1216. {
  1217. /* XXXX MOVE ? */
  1218. node_t fake_node;
  1219. const node_t *node = node_get_by_id(router->cache_info.identity_digest);;
  1220. if (node == NULL) {
  1221. memset(&fake_node, 0, sizeof(fake_node));
  1222. fake_node.ri = (routerinfo_t *)router;
  1223. memcpy(fake_node.identity, router->cache_info.identity_digest, DIGEST_LEN);
  1224. node = &fake_node;
  1225. }
  1226. nodelist_add_node_and_family(sl, node);
  1227. }
  1228. /** Return 1 iff any member of the (possibly NULL) comma-separated list
  1229. * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
  1230. * return 0.
  1231. */
  1232. int
  1233. router_nickname_is_in_list(const routerinfo_t *router, const char *list)
  1234. {
  1235. smartlist_t *nickname_list;
  1236. int v = 0;
  1237. if (!list)
  1238. return 0; /* definitely not */
  1239. tor_assert(router);
  1240. nickname_list = smartlist_new();
  1241. smartlist_split_string(nickname_list, list, ",",
  1242. SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1243. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  1244. if (router_nickname_matches(router, cp)) {v=1;break;});
  1245. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  1246. smartlist_free(nickname_list);
  1247. return v;
  1248. }
  1249. /** Add every suitable node from our nodelist to <b>sl</b>, so that
  1250. * we can pick a node for a circuit.
  1251. */
  1252. static void
  1253. router_add_running_nodes_to_smartlist(smartlist_t *sl, int allow_invalid,
  1254. int need_uptime, int need_capacity,
  1255. int need_guard, int need_desc)
  1256. { /* XXXX MOVE */
  1257. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  1258. if (!node->is_running ||
  1259. (!node->is_valid && !allow_invalid))
  1260. continue;
  1261. if (need_desc && !(node->ri || (node->rs && node->md)))
  1262. continue;
  1263. if (node->ri && node->ri->purpose != ROUTER_PURPOSE_GENERAL)
  1264. continue;
  1265. if (node_is_unreliable(node, need_uptime, need_capacity, need_guard))
  1266. continue;
  1267. smartlist_add(sl, (void *)node);
  1268. } SMARTLIST_FOREACH_END(node);
  1269. }
  1270. /** Look through the routerlist until we find a router that has my key.
  1271. Return it. */
  1272. const routerinfo_t *
  1273. routerlist_find_my_routerinfo(void)
  1274. {
  1275. if (!routerlist)
  1276. return NULL;
  1277. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1278. {
  1279. if (router_is_me(router))
  1280. return router;
  1281. });
  1282. return NULL;
  1283. }
  1284. /** Return the smaller of the router's configured BandwidthRate
  1285. * and its advertised capacity. */
  1286. uint32_t
  1287. router_get_advertised_bandwidth(const routerinfo_t *router)
  1288. {
  1289. if (router->bandwidthcapacity < router->bandwidthrate)
  1290. return router->bandwidthcapacity;
  1291. return router->bandwidthrate;
  1292. }
  1293. /** Do not weight any declared bandwidth more than this much when picking
  1294. * routers by bandwidth. */
  1295. #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
  1296. /** Return the smaller of the router's configured BandwidthRate
  1297. * and its advertised capacity, capped by max-believe-bw. */
  1298. uint32_t
  1299. router_get_advertised_bandwidth_capped(const routerinfo_t *router)
  1300. {
  1301. uint32_t result = router->bandwidthcapacity;
  1302. if (result > router->bandwidthrate)
  1303. result = router->bandwidthrate;
  1304. if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
  1305. result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
  1306. return result;
  1307. }
  1308. /** Given an array of double/uint64_t unions that are currently being used as
  1309. * doubles, convert them to uint64_t, and try to scale them linearly so as to
  1310. * much of the range of uint64_t. If <b>total_out</b> is provided, set it to
  1311. * the sum of all elements in the array _before_ scaling. */
  1312. /* private */ void
  1313. scale_array_elements_to_u64(u64_dbl_t *entries, int n_entries,
  1314. uint64_t *total_out)
  1315. {
  1316. double total = 0.0;
  1317. double scale_factor;
  1318. int i;
  1319. /* big, but far away from overflowing an int64_t */
  1320. #define SCALE_TO_U64_MAX (INT64_MAX / 4)
  1321. for (i = 0; i < n_entries; ++i)
  1322. total += entries[i].dbl;
  1323. scale_factor = SCALE_TO_U64_MAX / total;
  1324. for (i = 0; i < n_entries; ++i)
  1325. entries[i].u64 = tor_llround(entries[i].dbl * scale_factor);
  1326. if (total_out)
  1327. *total_out = (uint64_t) total;
  1328. #undef SCALE_TO_U64_MAX
  1329. }
  1330. /** Time-invariant 64-bit greater-than; works on two integers in the range
  1331. * (0,INT64_MAX). */
  1332. #if SIZEOF_VOID_P == 8
  1333. #define gt_i64_timei(a,b) ((a) > (b))
  1334. #else
  1335. static INLINE int
  1336. gt_i64_timei(uint64_t a, uint64_t b)
  1337. {
  1338. int64_t diff = (int64_t) (b - a);
  1339. int res = diff >> 63;
  1340. return res & 1;
  1341. }
  1342. #endif
  1343. /** Pick a random element of <b>n_entries</b>-element array <b>entries</b>,
  1344. * choosing each element with a probability proportional to its (uint64_t)
  1345. * value, and return the index of that element. If all elements are 0, choose
  1346. * an index at random. Return -1 on error.
  1347. */
  1348. /* private */ int
  1349. choose_array_element_by_weight(const u64_dbl_t *entries, int n_entries)
  1350. {
  1351. int i, i_chosen=-1, n_chosen=0;
  1352. uint64_t total_so_far = 0;
  1353. uint64_t rand_val;
  1354. uint64_t total = 0;
  1355. for (i = 0; i < n_entries; ++i)
  1356. total += entries[i].u64;
  1357. if (n_entries < 1)
  1358. return -1;
  1359. if (total == 0)
  1360. return crypto_rand_int(n_entries);
  1361. tor_assert(total < INT64_MAX);
  1362. rand_val = crypto_rand_uint64(total);
  1363. for (i = 0; i < n_entries; ++i) {
  1364. total_so_far += entries[i].u64;
  1365. if (gt_i64_timei(total_so_far, rand_val)) {
  1366. i_chosen = i;
  1367. n_chosen++;
  1368. /* Set rand_val to INT64_MAX rather than stopping the loop. This way,
  1369. * the time we spend in the loop does not leak which element we chose. */
  1370. rand_val = INT64_MAX;
  1371. }
  1372. }
  1373. tor_assert(total_so_far == total);
  1374. tor_assert(n_chosen == 1);
  1375. tor_assert(i_chosen >= 0);
  1376. tor_assert(i_chosen < n_entries);
  1377. return i_chosen;
  1378. }
  1379. /** When weighting bridges, enforce these values as lower and upper
  1380. * bound for believable bandwidth, because there is no way for us
  1381. * to verify a bridge's bandwidth currently. */
  1382. #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
  1383. #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
  1384. /** Return the smaller of the router's configured BandwidthRate
  1385. * and its advertised capacity, making sure to stay within the
  1386. * interval between bridge-min-believe-bw and
  1387. * bridge-max-believe-bw. */
  1388. static uint32_t
  1389. bridge_get_advertised_bandwidth_bounded(routerinfo_t *router)
  1390. {
  1391. uint32_t result = router->bandwidthcapacity;
  1392. if (result > router->bandwidthrate)
  1393. result = router->bandwidthrate;
  1394. if (result > BRIDGE_MAX_BELIEVABLE_BANDWIDTH)
  1395. result = BRIDGE_MAX_BELIEVABLE_BANDWIDTH;
  1396. else if (result < BRIDGE_MIN_BELIEVABLE_BANDWIDTH)
  1397. result = BRIDGE_MIN_BELIEVABLE_BANDWIDTH;
  1398. return result;
  1399. }
  1400. /** Return bw*1000, unless bw*1000 would overflow, in which case return
  1401. * INT32_MAX. */
  1402. static INLINE int32_t
  1403. kb_to_bytes(uint32_t bw)
  1404. {
  1405. return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
  1406. }
  1407. /** Helper function:
  1408. * choose a random element of smartlist <b>sl</b> of nodes, weighted by
  1409. * the advertised bandwidth of each element using the consensus
  1410. * bandwidth weights.
  1411. *
  1412. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1413. * nodes' bandwidth equally regardless of their Exit status, since there may
  1414. * be some in the list because they exit to obscure ports. If
  1415. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1416. * exit-node's bandwidth less depending on the smallness of the fraction of
  1417. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1418. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1419. * guards proportionally less.
  1420. */
  1421. static const node_t *
  1422. smartlist_choose_node_by_bandwidth_weights(smartlist_t *sl,
  1423. bandwidth_weight_rule_t rule)
  1424. {
  1425. int64_t weight_scale;
  1426. double Wg = -1, Wm = -1, We = -1, Wd = -1;
  1427. double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
  1428. uint64_t weighted_bw = 0;
  1429. u64_dbl_t *bandwidths;
  1430. /* Can't choose exit and guard at same time */
  1431. tor_assert(rule == NO_WEIGHTING ||
  1432. rule == WEIGHT_FOR_EXIT ||
  1433. rule == WEIGHT_FOR_GUARD ||
  1434. rule == WEIGHT_FOR_MID ||
  1435. rule == WEIGHT_FOR_DIR);
  1436. if (smartlist_len(sl) == 0) {
  1437. log_info(LD_CIRC,
  1438. "Empty routerlist passed in to consensus weight node "
  1439. "selection for rule %s",
  1440. bandwidth_weight_rule_to_string(rule));
  1441. return NULL;
  1442. }
  1443. weight_scale = circuit_build_times_get_bw_scale(NULL);
  1444. if (rule == WEIGHT_FOR_GUARD) {
  1445. Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
  1446. Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
  1447. We = 0;
  1448. Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
  1449. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1450. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1451. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1452. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1453. } else if (rule == WEIGHT_FOR_MID) {
  1454. Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
  1455. Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
  1456. We = networkstatus_get_bw_weight(NULL, "Wme", -1);
  1457. Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
  1458. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1459. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1460. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1461. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1462. } else if (rule == WEIGHT_FOR_EXIT) {
  1463. // Guards CAN be exits if they have weird exit policies
  1464. // They are d then I guess...
  1465. We = networkstatus_get_bw_weight(NULL, "Wee", -1);
  1466. Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
  1467. Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
  1468. Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
  1469. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1470. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1471. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1472. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1473. } else if (rule == WEIGHT_FOR_DIR) {
  1474. We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
  1475. Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
  1476. Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
  1477. Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
  1478. Wgb = Wmb = Web = Wdb = weight_scale;
  1479. } else if (rule == NO_WEIGHTING) {
  1480. Wg = Wm = We = Wd = weight_scale;
  1481. Wgb = Wmb = Web = Wdb = weight_scale;
  1482. }
  1483. if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
  1484. || Web < 0) {
  1485. log_debug(LD_CIRC,
  1486. "Got negative bandwidth weights. Defaulting to old selection"
  1487. " algorithm.");
  1488. return NULL; // Use old algorithm.
  1489. }
  1490. Wg /= weight_scale;
  1491. Wm /= weight_scale;
  1492. We /= weight_scale;
  1493. Wd /= weight_scale;
  1494. Wgb /= weight_scale;
  1495. Wmb /= weight_scale;
  1496. Web /= weight_scale;
  1497. Wdb /= weight_scale;
  1498. bandwidths = tor_malloc_zero(sizeof(u64_dbl_t)*smartlist_len(sl));
  1499. // Cycle through smartlist and total the bandwidth.
  1500. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1501. int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0, is_me = 0;
  1502. double weight = 1;
  1503. is_exit = node->is_exit && ! node->is_bad_exit;
  1504. is_guard = node->is_possible_guard;
  1505. is_dir = node_is_dir(node);
  1506. if (node->rs) {
  1507. if (!node->rs->has_bandwidth) {
  1508. tor_free(bandwidths);
  1509. /* This should never happen, unless all the authorites downgrade
  1510. * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
  1511. log_warn(LD_BUG,
  1512. "Consensus is not listing bandwidths. Defaulting back to "
  1513. "old router selection algorithm.");
  1514. return NULL;
  1515. }
  1516. this_bw = kb_to_bytes(node->rs->bandwidth);
  1517. } else if (node->ri) {
  1518. /* bridge or other descriptor not in our consensus */
  1519. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1520. } else {
  1521. /* We can't use this one. */
  1522. continue;
  1523. }
  1524. is_me = router_digest_is_me(node->identity);
  1525. if (is_guard && is_exit) {
  1526. weight = (is_dir ? Wdb*Wd : Wd);
  1527. } else if (is_guard) {
  1528. weight = (is_dir ? Wgb*Wg : Wg);
  1529. } else if (is_exit) {
  1530. weight = (is_dir ? Web*We : We);
  1531. } else { // middle
  1532. weight = (is_dir ? Wmb*Wm : Wm);
  1533. }
  1534. /* These should be impossible; but overflows here would be bad, so let's
  1535. * make sure. */
  1536. if (this_bw < 0)
  1537. this_bw = 0;
  1538. if (weight < 0.0)
  1539. weight = 0.0;
  1540. bandwidths[node_sl_idx].dbl = weight*this_bw + 0.5;
  1541. if (is_me)
  1542. sl_last_weighted_bw_of_me = (uint64_t) bandwidths[node_sl_idx].dbl;
  1543. } SMARTLIST_FOREACH_END(node);
  1544. log_debug(LD_CIRC, "Choosing node for rule %s based on weights "
  1545. "Wg=%f Wm=%f We=%f Wd=%f with total bw "U64_FORMAT,
  1546. bandwidth_weight_rule_to_string(rule),
  1547. Wg, Wm, We, Wd, U64_PRINTF_ARG(weighted_bw));
  1548. scale_array_elements_to_u64(bandwidths, smartlist_len(sl),
  1549. &sl_last_total_weighted_bw);
  1550. {
  1551. int idx = choose_array_element_by_weight(bandwidths,
  1552. smartlist_len(sl));
  1553. tor_free(bandwidths);
  1554. return idx < 0 ? NULL : smartlist_get(sl, idx);
  1555. }
  1556. }
  1557. /** Helper function:
  1558. * choose a random node_t element of smartlist <b>sl</b>, weighted by
  1559. * the advertised bandwidth of each element.
  1560. *
  1561. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1562. * nodes' bandwidth equally regardless of their Exit status, since there may
  1563. * be some in the list because they exit to obscure ports. If
  1564. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1565. * exit-node's bandwidth less depending on the smallness of the fraction of
  1566. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1567. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1568. * guards proportionally less.
  1569. */
  1570. static const node_t *
  1571. smartlist_choose_node_by_bandwidth(smartlist_t *sl,
  1572. bandwidth_weight_rule_t rule)
  1573. {
  1574. unsigned int i;
  1575. u64_dbl_t *bandwidths;
  1576. int is_exit;
  1577. int is_guard;
  1578. int is_fast;
  1579. double total_nonexit_bw = 0, total_exit_bw = 0;
  1580. double total_nonguard_bw = 0, total_guard_bw = 0;
  1581. double exit_weight;
  1582. double guard_weight;
  1583. int n_unknown = 0;
  1584. bitarray_t *fast_bits;
  1585. bitarray_t *exit_bits;
  1586. bitarray_t *guard_bits;
  1587. int me_idx = -1;
  1588. // This function does not support WEIGHT_FOR_DIR
  1589. // or WEIGHT_FOR_MID
  1590. if (rule == WEIGHT_FOR_DIR || rule == WEIGHT_FOR_MID) {
  1591. rule = NO_WEIGHTING;
  1592. }
  1593. /* Can't choose exit and guard at same time */
  1594. tor_assert(rule == NO_WEIGHTING ||
  1595. rule == WEIGHT_FOR_EXIT ||
  1596. rule == WEIGHT_FOR_GUARD);
  1597. if (smartlist_len(sl) == 0) {
  1598. log_info(LD_CIRC,
  1599. "Empty routerlist passed in to old node selection for rule %s",
  1600. bandwidth_weight_rule_to_string(rule));
  1601. return NULL;
  1602. }
  1603. /* First count the total bandwidth weight, and make a list
  1604. * of each value. We use UINT64_MAX to indicate "unknown". */
  1605. bandwidths = tor_malloc_zero(sizeof(u64_dbl_t)*smartlist_len(sl));
  1606. fast_bits = bitarray_init_zero(smartlist_len(sl));
  1607. exit_bits = bitarray_init_zero(smartlist_len(sl));
  1608. guard_bits = bitarray_init_zero(smartlist_len(sl));
  1609. /* Iterate over all the routerinfo_t or routerstatus_t, and */
  1610. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1611. /* first, learn what bandwidth we think i has */
  1612. int is_known = 1;
  1613. uint32_t this_bw = 0;
  1614. i = node_sl_idx;
  1615. if (router_digest_is_me(node->identity))
  1616. me_idx = node_sl_idx;
  1617. is_exit = node->is_exit;
  1618. is_guard = node->is_possible_guard;
  1619. if (node->rs) {
  1620. if (node->rs->has_bandwidth) {
  1621. this_bw = kb_to_bytes(node->rs->bandwidth);
  1622. } else { /* guess */
  1623. is_known = 0;
  1624. }
  1625. } else if (node->ri) {
  1626. /* Must be a bridge if we're willing to use it */
  1627. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1628. }
  1629. if (is_exit)
  1630. bitarray_set(exit_bits, i);
  1631. if (is_guard)
  1632. bitarray_set(guard_bits, i);
  1633. if (node->is_fast)
  1634. bitarray_set(fast_bits, i);
  1635. if (is_known) {
  1636. bandwidths[i].dbl = this_bw;
  1637. if (is_guard)
  1638. total_guard_bw += this_bw;
  1639. else
  1640. total_nonguard_bw += this_bw;
  1641. if (is_exit)
  1642. total_exit_bw += this_bw;
  1643. else
  1644. total_nonexit_bw += this_bw;
  1645. } else {
  1646. ++n_unknown;
  1647. bandwidths[i].dbl = -1.0;
  1648. }
  1649. } SMARTLIST_FOREACH_END(node);
  1650. #define EPSILON .1
  1651. /* Now, fill in the unknown values. */
  1652. if (n_unknown) {
  1653. int32_t avg_fast, avg_slow;
  1654. if (total_exit_bw+total_nonexit_bw < EPSILON) {
  1655. /* if there's some bandwidth, there's at least one known router,
  1656. * so no worries about div by 0 here */
  1657. int n_known = smartlist_len(sl)-n_unknown;
  1658. avg_fast = avg_slow = (int32_t)
  1659. ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
  1660. } else {
  1661. avg_fast = 40000;
  1662. avg_slow = 20000;
  1663. }
  1664. for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
  1665. if (bandwidths[i].dbl >= 0.0)
  1666. continue;
  1667. is_fast = bitarray_is_set(fast_bits, i);
  1668. is_exit = bitarray_is_set(exit_bits, i);
  1669. is_guard = bitarray_is_set(guard_bits, i);
  1670. bandwidths[i].dbl = is_fast ? avg_fast : avg_slow;
  1671. if (is_exit)
  1672. total_exit_bw += bandwidths[i].dbl;
  1673. else
  1674. total_nonexit_bw += bandwidths[i].dbl;
  1675. if (is_guard)
  1676. total_guard_bw += bandwidths[i].dbl;
  1677. else
  1678. total_nonguard_bw += bandwidths[i].dbl;
  1679. }
  1680. }
  1681. /* If there's no bandwidth at all, pick at random. */
  1682. if (total_exit_bw+total_nonexit_bw < EPSILON) {
  1683. tor_free(bandwidths);
  1684. tor_free(fast_bits);
  1685. tor_free(exit_bits);
  1686. tor_free(guard_bits);
  1687. return smartlist_choose(sl);
  1688. }
  1689. /* Figure out how to weight exits and guards */
  1690. {
  1691. double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
  1692. double exit_bw = U64_TO_DBL(total_exit_bw);
  1693. double guard_bw = U64_TO_DBL(total_guard_bw);
  1694. /*
  1695. * For detailed derivation of this formula, see
  1696. * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
  1697. */
  1698. if (rule == WEIGHT_FOR_EXIT || total_exit_bw<EPSILON)
  1699. exit_weight = 1.0;
  1700. else
  1701. exit_weight = 1.0 - all_bw/(3.0*exit_bw);
  1702. if (rule == WEIGHT_FOR_GUARD || total_guard_bw<EPSILON)
  1703. guard_weight = 1.0;
  1704. else
  1705. guard_weight = 1.0 - all_bw/(3.0*guard_bw);
  1706. if (exit_weight <= 0.0)
  1707. exit_weight = 0.0;
  1708. if (guard_weight <= 0.0)
  1709. guard_weight = 0.0;
  1710. sl_last_weighted_bw_of_me = 0;
  1711. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1712. tor_assert(bandwidths[i].dbl >= 0.0);
  1713. is_exit = bitarray_is_set(exit_bits, i);
  1714. is_guard = bitarray_is_set(guard_bits, i);
  1715. if (is_exit && is_guard)
  1716. bandwidths[i].dbl *= exit_weight * guard_weight;
  1717. else if (is_guard)
  1718. bandwidths[i].dbl *= guard_weight;
  1719. else if (is_exit)
  1720. bandwidths[i].dbl *= exit_weight;
  1721. if (i == (unsigned) me_idx)
  1722. sl_last_weighted_bw_of_me = (uint64_t) bandwidths[i].dbl;
  1723. }
  1724. }
  1725. #if 0
  1726. log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
  1727. ", exit bw = "U64_FORMAT
  1728. ", nonexit bw = "U64_FORMAT", exit weight = %f "
  1729. "(for exit == %d)"
  1730. ", guard bw = "U64_FORMAT
  1731. ", nonguard bw = "U64_FORMAT", guard weight = %f "
  1732. "(for guard == %d)",
  1733. U64_PRINTF_ARG(total_bw),
  1734. U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
  1735. exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
  1736. U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
  1737. guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
  1738. #endif
  1739. scale_array_elements_to_u64(bandwidths, smartlist_len(sl),
  1740. &sl_last_total_weighted_bw);
  1741. {
  1742. int idx = choose_array_element_by_weight(bandwidths,
  1743. smartlist_len(sl));
  1744. tor_free(bandwidths);
  1745. tor_free(fast_bits);
  1746. tor_free(exit_bits);
  1747. tor_free(guard_bits);
  1748. return idx < 0 ? NULL : smartlist_get(sl, idx);
  1749. }
  1750. }
  1751. /** Choose a random element of status list <b>sl</b>, weighted by
  1752. * the advertised bandwidth of each node */
  1753. const node_t *
  1754. node_sl_choose_by_bandwidth(smartlist_t *sl,
  1755. bandwidth_weight_rule_t rule)
  1756. { /*XXXX MOVE */
  1757. const node_t *ret;
  1758. if ((ret = smartlist_choose_node_by_bandwidth_weights(sl, rule))) {
  1759. return ret;
  1760. } else {
  1761. return smartlist_choose_node_by_bandwidth(sl, rule);
  1762. }
  1763. }
  1764. /** Return a random running node from the nodelist. Never
  1765. * pick a node that is in
  1766. * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
  1767. * even if they are the only nodes available.
  1768. * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
  1769. * a minimum uptime, return one of those.
  1770. * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
  1771. * advertised capacity of each router.
  1772. * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
  1773. * routers.
  1774. * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
  1775. * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
  1776. * picking an exit node, otherwise we weight bandwidths for picking a relay
  1777. * node (that is, possibly discounting exit nodes).
  1778. * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
  1779. * have a routerinfo or microdescriptor -- that is, enough info to be
  1780. * used to build a circuit.
  1781. */
  1782. const node_t *
  1783. router_choose_random_node(smartlist_t *excludedsmartlist,
  1784. routerset_t *excludedset,
  1785. router_crn_flags_t flags)
  1786. { /* XXXX MOVE */
  1787. const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
  1788. const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
  1789. const int need_guard = (flags & CRN_NEED_GUARD) != 0;
  1790. const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
  1791. const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
  1792. const int need_desc = (flags & CRN_NEED_DESC) != 0;
  1793. smartlist_t *sl=smartlist_new(),
  1794. *excludednodes=smartlist_new();
  1795. const node_t *choice = NULL;
  1796. const routerinfo_t *r;
  1797. bandwidth_weight_rule_t rule;
  1798. tor_assert(!(weight_for_exit && need_guard));
  1799. rule = weight_for_exit ? WEIGHT_FOR_EXIT :
  1800. (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
  1801. /* Exclude relays that allow single hop exit circuits, if the user
  1802. * wants to (such relays might be risky) */
  1803. if (get_options()->ExcludeSingleHopRelays) {
  1804. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
  1805. if (node_allows_single_hop_exits(node)) {
  1806. smartlist_add(excludednodes, node);
  1807. });
  1808. }
  1809. if ((r = routerlist_find_my_routerinfo()))
  1810. routerlist_add_node_and_family(excludednodes, r);
  1811. router_add_running_nodes_to_smartlist(sl, allow_invalid,
  1812. need_uptime, need_capacity,
  1813. need_guard, need_desc);
  1814. smartlist_subtract(sl,excludednodes);
  1815. if (excludedsmartlist)
  1816. smartlist_subtract(sl,excludedsmartlist);
  1817. if (excludedset)
  1818. routerset_subtract_nodes(sl,excludedset);
  1819. // Always weight by bandwidth
  1820. choice = node_sl_choose_by_bandwidth(sl, rule);
  1821. smartlist_free(sl);
  1822. if (!choice && (need_uptime || need_capacity || need_guard)) {
  1823. /* try once more -- recurse but with fewer restrictions. */
  1824. log_info(LD_CIRC,
  1825. "We couldn't find any live%s%s%s routers; falling back "
  1826. "to list of all routers.",
  1827. need_capacity?", fast":"",
  1828. need_uptime?", stable":"",
  1829. need_guard?", guard":"");
  1830. flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
  1831. choice = router_choose_random_node(
  1832. excludedsmartlist, excludedset, flags);
  1833. }
  1834. smartlist_free(excludednodes);
  1835. if (!choice) {
  1836. log_warn(LD_CIRC,
  1837. "No available nodes when trying to choose node. Failing.");
  1838. }
  1839. return choice;
  1840. }
  1841. /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
  1842. * Return 0 on success, -1 on failure. Store the result into the
  1843. * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
  1844. * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
  1845. * at <b>nickname_out</b>.
  1846. *
  1847. * The recognized format is:
  1848. * HexName = Dollar? HexDigest NamePart?
  1849. * Dollar = '?'
  1850. * HexDigest = HexChar*20
  1851. * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
  1852. * NamePart = QualChar Name
  1853. * QualChar = '=' | '~'
  1854. * Name = NameChar*(1..MAX_NICKNAME_LEN)
  1855. * NameChar = Any ASCII alphanumeric character
  1856. */
  1857. int
  1858. hex_digest_nickname_decode(const char *hexdigest,
  1859. char *digest_out,
  1860. char *nickname_qualifier_char_out,
  1861. char *nickname_out)
  1862. {
  1863. size_t len;
  1864. tor_assert(hexdigest);
  1865. if (hexdigest[0] == '$')
  1866. ++hexdigest;
  1867. len = strlen(hexdigest);
  1868. if (len < HEX_DIGEST_LEN) {
  1869. return -1;
  1870. } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
  1871. hexdigest[HEX_DIGEST_LEN] == '~') &&
  1872. len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
  1873. *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
  1874. strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
  1875. } else if (len == HEX_DIGEST_LEN) {
  1876. ;
  1877. } else {
  1878. return -1;
  1879. }
  1880. if (base16_decode(digest_out, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  1881. return -1;
  1882. return 0;
  1883. }
  1884. /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
  1885. * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
  1886. * (which is optionally prefixed with a single dollar sign). Return false if
  1887. * <b>hexdigest</b> is malformed, or it doesn't match. */
  1888. int
  1889. hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest,
  1890. const char *nickname, int is_named)
  1891. {
  1892. char digest[DIGEST_LEN];
  1893. char nn_char='\0';
  1894. char nn_buf[MAX_NICKNAME_LEN+1];
  1895. if (hex_digest_nickname_decode(hexdigest, digest, &nn_char, nn_buf) == -1)
  1896. return 0;
  1897. if (nn_char == '=' || nn_char == '~') {
  1898. if (!nickname)
  1899. return 0;
  1900. if (strcasecmp(nn_buf, nickname))
  1901. return 0;
  1902. if (nn_char == '=' && !is_named)
  1903. return 0;
  1904. }
  1905. return tor_memeq(digest, identity_digest, DIGEST_LEN);
  1906. }
  1907. /** Return true iff <b>router</b> is listed as named in the current
  1908. * consensus. */
  1909. int
  1910. router_is_named(const routerinfo_t *router)
  1911. {
  1912. const char *digest =
  1913. networkstatus_get_router_digest_by_nickname(router->nickname);
  1914. return (digest &&
  1915. tor_memeq(digest, router->cache_info.identity_digest, DIGEST_LEN));
  1916. }
  1917. /** Return true iff the digest of <b>router</b>'s identity key,
  1918. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  1919. * optionally prefixed with a single dollar sign). Return false if
  1920. * <b>hexdigest</b> is malformed, or it doesn't match. */
  1921. static INLINE int
  1922. router_hex_digest_matches(const routerinfo_t *router, const char *hexdigest)
  1923. {
  1924. return hex_digest_nickname_matches(hexdigest,
  1925. router->cache_info.identity_digest,
  1926. router->nickname,
  1927. router_is_named(router));
  1928. }
  1929. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  1930. * (case-insensitive), or if <b>router's</b> identity key digest
  1931. * matches a hexadecimal value stored in <b>nickname</b>. Return
  1932. * false otherwise. */
  1933. static int
  1934. router_nickname_matches(const routerinfo_t *router, const char *nickname)
  1935. {
  1936. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  1937. return 1;
  1938. return router_hex_digest_matches(router, nickname);
  1939. }
  1940. /** Return true iff <b>digest</b> is the digest of the identity key of a
  1941. * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
  1942. * is zero, any authority is okay. */
  1943. int
  1944. router_digest_is_trusted_dir_type(const char *digest, dirinfo_type_t type)
  1945. {
  1946. if (!trusted_dir_servers)
  1947. return 0;
  1948. if (authdir_mode(get_options()) && router_digest_is_me(digest))
  1949. return 1;
  1950. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1951. if (tor_memeq(digest, ent->digest, DIGEST_LEN)) {
  1952. return (!type) || ((type & ent->type) != 0);
  1953. });
  1954. return 0;
  1955. }
  1956. /** Return true iff <b>addr</b> is the address of one of our trusted
  1957. * directory authorities. */
  1958. int
  1959. router_addr_is_trusted_dir(uint32_t addr)
  1960. {
  1961. if (!trusted_dir_servers)
  1962. return 0;
  1963. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1964. if (ent->addr == addr)
  1965. return 1;
  1966. );
  1967. return 0;
  1968. }
  1969. /** If hexdigest is correctly formed, base16_decode it into
  1970. * digest, which must have DIGEST_LEN space in it.
  1971. * Return 0 on success, -1 on failure.
  1972. */
  1973. int
  1974. hexdigest_to_digest(const char *hexdigest, char *digest)
  1975. {
  1976. if (hexdigest[0]=='$')
  1977. ++hexdigest;
  1978. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1979. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  1980. return -1;
  1981. return 0;
  1982. }
  1983. /** As router_get_by_id_digest,but return a pointer that you're allowed to
  1984. * modify */
  1985. routerinfo_t *
  1986. router_get_mutable_by_digest(const char *digest)
  1987. {
  1988. tor_assert(digest);
  1989. if (!routerlist) return NULL;
  1990. // routerlist_assert_ok(routerlist);
  1991. return rimap_get(routerlist->identity_map, digest);
  1992. }
  1993. /** Return the router in our routerlist whose 20-byte key digest
  1994. * is <b>digest</b>. Return NULL if no such router is known. */
  1995. const routerinfo_t *
  1996. router_get_by_id_digest(const char *digest)
  1997. {
  1998. return router_get_mutable_by_digest(digest);
  1999. }
  2000. /** Return the router in our routerlist whose 20-byte descriptor
  2001. * is <b>digest</b>. Return NULL if no such router is known. */
  2002. signed_descriptor_t *
  2003. router_get_by_descriptor_digest(const char *digest)
  2004. {
  2005. tor_assert(digest);
  2006. if (!routerlist) return NULL;
  2007. return sdmap_get(routerlist->desc_digest_map, digest);
  2008. }
  2009. /** Return the signed descriptor for the router in our routerlist whose
  2010. * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
  2011. * is known. */
  2012. signed_descriptor_t *
  2013. router_get_by_extrainfo_digest(const char *digest)
  2014. {
  2015. tor_assert(digest);
  2016. if (!routerlist) return NULL;
  2017. return sdmap_get(routerlist->desc_by_eid_map, digest);
  2018. }
  2019. /** Return the signed descriptor for the extrainfo_t in our routerlist whose
  2020. * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
  2021. * document is known. */
  2022. signed_descriptor_t *
  2023. extrainfo_get_by_descriptor_digest(const char *digest)
  2024. {
  2025. extrainfo_t *ei;
  2026. tor_assert(digest);
  2027. if (!routerlist) return NULL;
  2028. ei = eimap_get(routerlist->extra_info_map, digest);
  2029. return ei ? &ei->cache_info : NULL;
  2030. }
  2031. /** Return a pointer to the signed textual representation of a descriptor.
  2032. * The returned string is not guaranteed to be NUL-terminated: the string's
  2033. * length will be in desc-\>signed_descriptor_len.
  2034. *
  2035. * If <b>with_annotations</b> is set, the returned string will include
  2036. * the annotations
  2037. * (if any) preceding the descriptor. This will increase the length of the
  2038. * string by desc-\>annotations_len.
  2039. *
  2040. * The caller must not free the string returned.
  2041. */
  2042. static const char *
  2043. signed_descriptor_get_body_impl(const signed_descriptor_t *desc,
  2044. int with_annotations)
  2045. {
  2046. const char *r = NULL;
  2047. size_t len = desc->signed_descriptor_len;
  2048. off_t offset = desc->saved_offset;
  2049. if (with_annotations)
  2050. len += desc->annotations_len;
  2051. else
  2052. offset += desc->annotations_len;
  2053. tor_assert(len > 32);
  2054. if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
  2055. desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
  2056. if (store && store->mmap) {
  2057. tor_assert(desc->saved_offset + len <= store->mmap->size);
  2058. r = store->mmap->data + offset;
  2059. } else if (store) {
  2060. log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
  2061. "mmaped in our cache. Is another process running in our data "
  2062. "directory? Exiting.");
  2063. exit(1);
  2064. }
  2065. }
  2066. if (!r) /* no mmap, or not in cache. */
  2067. r = desc->signed_descriptor_body +
  2068. (with_annotations ? 0 : desc->annotations_len);
  2069. tor_assert(r);
  2070. if (!with_annotations) {
  2071. if (fast_memcmp("router ", r, 7) && fast_memcmp("extra-info ", r, 11)) {
  2072. char *cp = tor_strndup(r, 64);
  2073. log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
  2074. "Is another process running in our data directory? Exiting.",
  2075. desc, escaped(cp));
  2076. exit(1);
  2077. }
  2078. }
  2079. return r;
  2080. }
  2081. /** Return a pointer to the signed textual representation of a descriptor.
  2082. * The returned string is not guaranteed to be NUL-terminated: the string's
  2083. * length will be in desc-\>signed_descriptor_len.
  2084. *
  2085. * The caller must not free the string returned.
  2086. */
  2087. const char *
  2088. signed_descriptor_get_body(const signed_descriptor_t *desc)
  2089. {
  2090. return signed_descriptor_get_body_impl(desc, 0);
  2091. }
  2092. /** As signed_descriptor_get_body(), but points to the beginning of the
  2093. * annotations section rather than the beginning of the descriptor. */
  2094. const char *
  2095. signed_descriptor_get_annotations(const signed_descriptor_t *desc)
  2096. {
  2097. return signed_descriptor_get_body_impl(desc, 1);
  2098. }
  2099. /** Return the current list of all known routers. */
  2100. routerlist_t *
  2101. router_get_routerlist(void)
  2102. {
  2103. if (PREDICT_UNLIKELY(!routerlist)) {
  2104. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  2105. routerlist->routers = smartlist_new();
  2106. routerlist->old_routers = smartlist_new();
  2107. routerlist->identity_map = rimap_new();
  2108. routerlist->desc_digest_map = sdmap_new();
  2109. routerlist->desc_by_eid_map = sdmap_new();
  2110. routerlist->extra_info_map = eimap_new();
  2111. routerlist->desc_store.fname_base = "cached-descriptors";
  2112. routerlist->desc_store.fname_alt_base = "cached-routers";
  2113. routerlist->extrainfo_store.fname_base = "cached-extrainfo";
  2114. routerlist->desc_store.type = ROUTER_STORE;
  2115. routerlist->extrainfo_store.type = EXTRAINFO_STORE;
  2116. routerlist->desc_store.description = "router descriptors";
  2117. routerlist->extrainfo_store.description = "extra-info documents";
  2118. }
  2119. return routerlist;
  2120. }
  2121. /** Free all storage held by <b>router</b>. */
  2122. void
  2123. routerinfo_free(routerinfo_t *router)
  2124. {
  2125. if (!router)
  2126. return;
  2127. tor_free(router->cache_info.signed_descriptor_body);
  2128. tor_free(router->address);
  2129. tor_free(router->nickname);
  2130. tor_free(router->platform);
  2131. tor_free(router->contact_info);
  2132. if (router->onion_pkey)
  2133. crypto_pk_free(router->onion_pkey);
  2134. if (router->identity_pkey)
  2135. crypto_pk_free(router->identity_pkey);
  2136. if (router->declared_family) {
  2137. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  2138. smartlist_free(router->declared_family);
  2139. }
  2140. addr_policy_list_free(router->exit_policy);
  2141. memset(router, 77, sizeof(routerinfo_t));
  2142. tor_free(router);
  2143. }
  2144. /** Release all storage held by <b>extrainfo</b> */
  2145. void
  2146. extrainfo_free(extrainfo_t *extrainfo)
  2147. {
  2148. if (!extrainfo)
  2149. return;
  2150. tor_free(extrainfo->cache_info.signed_descriptor_body);
  2151. tor_free(extrainfo->pending_sig);
  2152. memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  2153. tor_free(extrainfo);
  2154. }
  2155. /** Release storage held by <b>sd</b>. */
  2156. static void
  2157. signed_descriptor_free(signed_descriptor_t *sd)
  2158. {
  2159. if (!sd)
  2160. return;
  2161. tor_free(sd->signed_descriptor_body);
  2162. memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
  2163. tor_free(sd);
  2164. }
  2165. /** Extract a signed_descriptor_t from a general routerinfo, and free the
  2166. * routerinfo.
  2167. */
  2168. static signed_descriptor_t *
  2169. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  2170. {
  2171. signed_descriptor_t *sd;
  2172. tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
  2173. sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  2174. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  2175. sd->routerlist_index = -1;
  2176. ri->cache_info.signed_descriptor_body = NULL;
  2177. routerinfo_free(ri);
  2178. return sd;
  2179. }
  2180. /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
  2181. static void
  2182. extrainfo_free_(void *e)
  2183. {
  2184. extrainfo_free(e);
  2185. }
  2186. /** Free all storage held by a routerlist <b>rl</b>. */
  2187. void
  2188. routerlist_free(routerlist_t *rl)
  2189. {
  2190. if (!rl)
  2191. return;
  2192. rimap_free(rl->identity_map, NULL);
  2193. sdmap_free(rl->desc_digest_map, NULL);
  2194. sdmap_free(rl->desc_by_eid_map, NULL);
  2195. eimap_free(rl->extra_info_map, extrainfo_free_);
  2196. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2197. routerinfo_free(r));
  2198. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  2199. signed_descriptor_free(sd));
  2200. smartlist_free(rl->routers);
  2201. smartlist_free(rl->old_routers);
  2202. if (routerlist->desc_store.mmap)
  2203. tor_munmap_file(routerlist->desc_store.mmap);
  2204. if (routerlist->extrainfo_store.mmap)
  2205. tor_munmap_file(routerlist->extrainfo_store.mmap);
  2206. tor_free(rl);
  2207. router_dir_info_changed();
  2208. }
  2209. /** Log information about how much memory is being used for routerlist,
  2210. * at log level <b>severity</b>. */
  2211. void
  2212. dump_routerlist_mem_usage(int severity)
  2213. {
  2214. uint64_t livedescs = 0;
  2215. uint64_t olddescs = 0;
  2216. if (!routerlist)
  2217. return;
  2218. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  2219. livedescs += r->cache_info.signed_descriptor_len);
  2220. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  2221. olddescs += sd->signed_descriptor_len);
  2222. log(severity, LD_DIR,
  2223. "In %d live descriptors: "U64_FORMAT" bytes. "
  2224. "In %d old descriptors: "U64_FORMAT" bytes.",
  2225. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  2226. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  2227. }
  2228. /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
  2229. * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
  2230. * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
  2231. * is not in <b>sl</b>. */
  2232. static INLINE int
  2233. routerlist_find_elt_(smartlist_t *sl, void *ri, int idx)
  2234. {
  2235. if (idx < 0) {
  2236. idx = -1;
  2237. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  2238. if (r == ri) {
  2239. idx = r_sl_idx;
  2240. break;
  2241. });
  2242. } else {
  2243. tor_assert(idx < smartlist_len(sl));
  2244. tor_assert(smartlist_get(sl, idx) == ri);
  2245. };
  2246. return idx;
  2247. }
  2248. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  2249. * as needed. There must be no previous member of <b>rl</b> with the same
  2250. * identity digest as <b>ri</b>: If there is, call routerlist_replace
  2251. * instead.
  2252. */
  2253. static void
  2254. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  2255. {
  2256. routerinfo_t *ri_old;
  2257. signed_descriptor_t *sd_old;
  2258. {
  2259. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2260. tor_assert(ri_generated != ri);
  2261. }
  2262. tor_assert(ri->cache_info.routerlist_index == -1);
  2263. ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  2264. tor_assert(!ri_old);
  2265. sd_old = sdmap_set(rl->desc_digest_map,
  2266. ri->cache_info.signed_descriptor_digest,
  2267. &(ri->cache_info));
  2268. if (sd_old) {
  2269. int idx = sd_old->routerlist_index;
  2270. sd_old->routerlist_index = -1;
  2271. smartlist_del(rl->old_routers, idx);
  2272. if (idx < smartlist_len(rl->old_routers)) {
  2273. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2274. d->routerlist_index = idx;
  2275. }
  2276. rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
  2277. sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
  2278. signed_descriptor_free(sd_old);
  2279. }
  2280. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2281. sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
  2282. &ri->cache_info);
  2283. smartlist_add(rl->routers, ri);
  2284. ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
  2285. nodelist_set_routerinfo(ri, NULL);
  2286. router_dir_info_changed();
  2287. #ifdef DEBUG_ROUTERLIST
  2288. routerlist_assert_ok(rl);
  2289. #endif
  2290. }
  2291. /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
  2292. * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
  2293. * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
  2294. static int
  2295. extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
  2296. {
  2297. int r = 0;
  2298. routerinfo_t *ri = rimap_get(rl->identity_map,
  2299. ei->cache_info.identity_digest);
  2300. signed_descriptor_t *sd =
  2301. sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
  2302. extrainfo_t *ei_tmp;
  2303. {
  2304. extrainfo_t *ei_generated = router_get_my_extrainfo();
  2305. tor_assert(ei_generated != ei);
  2306. }
  2307. if (!ri) {
  2308. /* This router is unknown; we can't even verify the signature. Give up.*/
  2309. goto done;
  2310. }
  2311. if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
  2312. goto done;
  2313. }
  2314. /* Okay, if we make it here, we definitely have a router corresponding to
  2315. * this extrainfo. */
  2316. ei_tmp = eimap_set(rl->extra_info_map,
  2317. ei->cache_info.signed_descriptor_digest,
  2318. ei);
  2319. r = 1;
  2320. if (ei_tmp) {
  2321. rl->extrainfo_store.bytes_dropped +=
  2322. ei_tmp->cache_info.signed_descriptor_len;
  2323. extrainfo_free(ei_tmp);
  2324. }
  2325. done:
  2326. if (r == 0)
  2327. extrainfo_free(ei);
  2328. #ifdef DEBUG_ROUTERLIST
  2329. routerlist_assert_ok(rl);
  2330. #endif
  2331. return r;
  2332. }
  2333. #define should_cache_old_descriptors() \
  2334. directory_caches_dir_info(get_options())
  2335. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  2336. * a copy of router <b>ri</b> yet, add it to the list of old (not
  2337. * recommended but still served) descriptors. Else free it. */
  2338. static void
  2339. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  2340. {
  2341. {
  2342. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2343. tor_assert(ri_generated != ri);
  2344. }
  2345. tor_assert(ri->cache_info.routerlist_index == -1);
  2346. if (should_cache_old_descriptors() &&
  2347. ri->purpose == ROUTER_PURPOSE_GENERAL &&
  2348. !sdmap_get(rl->desc_digest_map,
  2349. ri->cache_info.signed_descriptor_digest)) {
  2350. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  2351. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2352. smartlist_add(rl->old_routers, sd);
  2353. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2354. if (!tor_digest_is_zero(sd->extra_info_digest))
  2355. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2356. } else {
  2357. routerinfo_free(ri);
  2358. }
  2359. #ifdef DEBUG_ROUTERLIST
  2360. routerlist_assert_ok(rl);
  2361. #endif
  2362. }
  2363. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  2364. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  2365. * idx) == ri, we don't need to do a linear search over the list to decide
  2366. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  2367. * the list, if any exists. <b>ri</b> is freed.
  2368. *
  2369. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  2370. * it to rl-&gt;old_routers. */
  2371. void
  2372. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
  2373. {
  2374. routerinfo_t *ri_tmp;
  2375. extrainfo_t *ei_tmp;
  2376. int idx = ri->cache_info.routerlist_index;
  2377. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2378. tor_assert(smartlist_get(rl->routers, idx) == ri);
  2379. nodelist_remove_routerinfo(ri);
  2380. /* make sure the rephist module knows that it's not running */
  2381. rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
  2382. ri->cache_info.routerlist_index = -1;
  2383. smartlist_del(rl->routers, idx);
  2384. if (idx < smartlist_len(rl->routers)) {
  2385. routerinfo_t *r = smartlist_get(rl->routers, idx);
  2386. r->cache_info.routerlist_index = idx;
  2387. }
  2388. ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  2389. router_dir_info_changed();
  2390. tor_assert(ri_tmp == ri);
  2391. if (make_old && should_cache_old_descriptors() &&
  2392. ri->purpose == ROUTER_PURPOSE_GENERAL) {
  2393. signed_descriptor_t *sd;
  2394. sd = signed_descriptor_from_routerinfo(ri);
  2395. smartlist_add(rl->old_routers, sd);
  2396. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2397. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2398. if (!tor_digest_is_zero(sd->extra_info_digest))
  2399. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2400. } else {
  2401. signed_descriptor_t *sd_tmp;
  2402. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2403. ri->cache_info.signed_descriptor_digest);
  2404. tor_assert(sd_tmp == &(ri->cache_info));
  2405. rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
  2406. ei_tmp = eimap_remove(rl->extra_info_map,
  2407. ri->cache_info.extra_info_digest);
  2408. if (ei_tmp) {
  2409. rl->extrainfo_store.bytes_dropped +=
  2410. ei_tmp->cache_info.signed_descriptor_len;
  2411. extrainfo_free(ei_tmp);
  2412. }
  2413. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2414. sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
  2415. routerinfo_free(ri);
  2416. }
  2417. #ifdef DEBUG_ROUTERLIST
  2418. routerlist_assert_ok(rl);
  2419. #endif
  2420. }
  2421. /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
  2422. * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
  2423. * <b>sd</b>. */
  2424. static void
  2425. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  2426. {
  2427. signed_descriptor_t *sd_tmp;
  2428. extrainfo_t *ei_tmp;
  2429. desc_store_t *store;
  2430. if (idx == -1) {
  2431. idx = sd->routerlist_index;
  2432. }
  2433. tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
  2434. /* XXXX edmanm's bridge relay triggered the following assert while
  2435. * running 0.2.0.12-alpha. If anybody triggers this again, see if we
  2436. * can get a backtrace. */
  2437. tor_assert(smartlist_get(rl->old_routers, idx) == sd);
  2438. tor_assert(idx == sd->routerlist_index);
  2439. sd->routerlist_index = -1;
  2440. smartlist_del(rl->old_routers, idx);
  2441. if (idx < smartlist_len(rl->old_routers)) {
  2442. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2443. d->routerlist_index = idx;
  2444. }
  2445. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2446. sd->signed_descriptor_digest);
  2447. tor_assert(sd_tmp == sd);
  2448. store = desc_get_store(rl, sd);
  2449. if (store)
  2450. store->bytes_dropped += sd->signed_descriptor_len;
  2451. ei_tmp = eimap_remove(rl->extra_info_map,
  2452. sd->extra_info_digest);
  2453. if (ei_tmp) {
  2454. rl->extrainfo_store.bytes_dropped +=
  2455. ei_tmp->cache_info.signed_descriptor_len;
  2456. extrainfo_free(ei_tmp);
  2457. }
  2458. if (!tor_digest_is_zero(sd->extra_info_digest))
  2459. sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
  2460. signed_descriptor_free(sd);
  2461. #ifdef DEBUG_ROUTERLIST
  2462. routerlist_assert_ok(rl);
  2463. #endif
  2464. }
  2465. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  2466. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  2467. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  2468. * search over the list to decide which to remove. We put ri_new in the same
  2469. * index as ri_old, if possible. ri is freed as appropriate.
  2470. *
  2471. * If should_cache_descriptors() is true, instead of deleting the router,
  2472. * we add it to rl-&gt;old_routers. */
  2473. static void
  2474. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  2475. routerinfo_t *ri_new)
  2476. {
  2477. int idx;
  2478. int same_descriptors;
  2479. routerinfo_t *ri_tmp;
  2480. extrainfo_t *ei_tmp;
  2481. {
  2482. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2483. tor_assert(ri_generated != ri_new);
  2484. }
  2485. tor_assert(ri_old != ri_new);
  2486. tor_assert(ri_new->cache_info.routerlist_index == -1);
  2487. idx = ri_old->cache_info.routerlist_index;
  2488. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2489. tor_assert(smartlist_get(rl->routers, idx) == ri_old);
  2490. {
  2491. routerinfo_t *ri_old_tmp=NULL;
  2492. nodelist_set_routerinfo(ri_new, &ri_old_tmp);
  2493. tor_assert(ri_old == ri_old_tmp);
  2494. }
  2495. router_dir_info_changed();
  2496. if (idx >= 0) {
  2497. smartlist_set(rl->routers, idx, ri_new);
  2498. ri_old->cache_info.routerlist_index = -1;
  2499. ri_new->cache_info.routerlist_index = idx;
  2500. /* Check that ri_old is not in rl->routers anymore: */
  2501. tor_assert( routerlist_find_elt_(rl->routers, ri_old, -1) == -1 );
  2502. } else {
  2503. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  2504. routerlist_insert(rl, ri_new);
  2505. return;
  2506. }
  2507. if (tor_memneq(ri_old->cache_info.identity_digest,
  2508. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  2509. /* digests don't match; digestmap_set won't replace */
  2510. rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  2511. }
  2512. ri_tmp = rimap_set(rl->identity_map,
  2513. ri_new->cache_info.identity_digest, ri_new);
  2514. tor_assert(!ri_tmp || ri_tmp == ri_old);
  2515. sdmap_set(rl->desc_digest_map,
  2516. ri_new->cache_info.signed_descriptor_digest,
  2517. &(ri_new->cache_info));
  2518. if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
  2519. sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
  2520. &ri_new->cache_info);
  2521. }
  2522. same_descriptors = tor_memeq(ri_old->cache_info.signed_descriptor_digest,
  2523. ri_new->cache_info.signed_descriptor_digest,
  2524. DIGEST_LEN);
  2525. if (should_cache_old_descriptors() &&
  2526. ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
  2527. !same_descriptors) {
  2528. /* ri_old is going to become a signed_descriptor_t and go into
  2529. * old_routers */
  2530. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  2531. smartlist_add(rl->old_routers, sd);
  2532. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2533. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2534. if (!tor_digest_is_zero(sd->extra_info_digest))
  2535. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2536. } else {
  2537. /* We're dropping ri_old. */
  2538. if (!same_descriptors) {
  2539. /* digests don't match; The sdmap_set above didn't replace */
  2540. sdmap_remove(rl->desc_digest_map,
  2541. ri_old->cache_info.signed_descriptor_digest);
  2542. if (tor_memneq(ri_old->cache_info.extra_info_digest,
  2543. ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
  2544. ei_tmp = eimap_remove(rl->extra_info_map,
  2545. ri_old->cache_info.extra_info_digest);
  2546. if (ei_tmp) {
  2547. rl->extrainfo_store.bytes_dropped +=
  2548. ei_tmp->cache_info.signed_descriptor_len;
  2549. extrainfo_free(ei_tmp);
  2550. }
  2551. }
  2552. if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
  2553. sdmap_remove(rl->desc_by_eid_map,
  2554. ri_old->cache_info.extra_info_digest);
  2555. }
  2556. }
  2557. rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
  2558. routerinfo_free(ri_old);
  2559. }
  2560. #ifdef DEBUG_ROUTERLIST
  2561. routerlist_assert_ok(rl);
  2562. #endif
  2563. }
  2564. /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
  2565. * it as a fresh routerinfo_t. */
  2566. static routerinfo_t *
  2567. routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
  2568. {
  2569. routerinfo_t *ri;
  2570. const char *body;
  2571. body = signed_descriptor_get_annotations(sd);
  2572. ri = router_parse_entry_from_string(body,
  2573. body+sd->signed_descriptor_len+sd->annotations_len,
  2574. 0, 1, NULL);
  2575. if (!ri)
  2576. return NULL;
  2577. memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
  2578. sd->signed_descriptor_body = NULL; /* Steal reference. */
  2579. ri->cache_info.routerlist_index = -1;
  2580. routerlist_remove_old(rl, sd, -1);
  2581. return ri;
  2582. }
  2583. /** Free all memory held by the routerlist module. */
  2584. void
  2585. routerlist_free_all(void)
  2586. {
  2587. routerlist_free(routerlist);
  2588. routerlist = NULL;
  2589. if (warned_nicknames) {
  2590. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2591. smartlist_free(warned_nicknames);
  2592. warned_nicknames = NULL;
  2593. }
  2594. if (trusted_dir_servers) {
  2595. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2596. trusted_dir_server_free(ds));
  2597. smartlist_free(trusted_dir_servers);
  2598. trusted_dir_servers = NULL;
  2599. }
  2600. if (trusted_dir_certs) {
  2601. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  2602. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  2603. authority_cert_free(cert));
  2604. smartlist_free(cl->certs);
  2605. tor_free(cl);
  2606. } DIGESTMAP_FOREACH_END;
  2607. digestmap_free(trusted_dir_certs, NULL);
  2608. trusted_dir_certs = NULL;
  2609. }
  2610. }
  2611. /** Forget that we have issued any router-related warnings, so that we'll
  2612. * warn again if we see the same errors. */
  2613. void
  2614. routerlist_reset_warnings(void)
  2615. {
  2616. if (!warned_nicknames)
  2617. warned_nicknames = smartlist_new();
  2618. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2619. smartlist_clear(warned_nicknames); /* now the list is empty. */
  2620. networkstatus_reset_warnings();
  2621. }
  2622. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  2623. * older entries (if any) with the same key. Note: Callers should not hold
  2624. * their pointers to <b>router</b> if this function fails; <b>router</b>
  2625. * will either be inserted into the routerlist or freed. Similarly, even
  2626. * if this call succeeds, they should not hold their pointers to
  2627. * <b>router</b> after subsequent calls with other routerinfo's -- they
  2628. * might cause the original routerinfo to get freed.
  2629. *
  2630. * Returns the status for the operation. Might set *<b>msg</b> if it wants
  2631. * the poster of the router to know something.
  2632. *
  2633. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  2634. * <b>from_fetch</b>, we received it in response to a request we made.
  2635. * (If both are false, that means it was uploaded to us as an auth dir
  2636. * server or via the controller.)
  2637. *
  2638. * This function should be called *after*
  2639. * routers_update_status_from_consensus_networkstatus; subsequently, you
  2640. * should call router_rebuild_store and routerlist_descriptors_added.
  2641. */
  2642. was_router_added_t
  2643. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  2644. int from_cache, int from_fetch)
  2645. {
  2646. const char *id_digest;
  2647. const or_options_t *options = get_options();
  2648. int authdir = authdir_mode_handles_descs(options, router->purpose);
  2649. int authdir_believes_valid = 0;
  2650. routerinfo_t *old_router;
  2651. networkstatus_t *consensus =
  2652. networkstatus_get_latest_consensus_by_flavor(FLAV_NS);
  2653. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2654. int in_consensus = 0;
  2655. tor_assert(msg);
  2656. if (!routerlist)
  2657. router_get_routerlist();
  2658. id_digest = router->cache_info.identity_digest;
  2659. old_router = router_get_mutable_by_digest(id_digest);
  2660. /* Make sure that we haven't already got this exact descriptor. */
  2661. if (sdmap_get(routerlist->desc_digest_map,
  2662. router->cache_info.signed_descriptor_digest)) {
  2663. /* If we have this descriptor already and the new descriptor is a bridge
  2664. * descriptor, replace it. If we had a bridge descriptor before and the
  2665. * new one is not a bridge descriptor, don't replace it. */
  2666. /* Only members of routerlist->identity_map can be bridges; we don't
  2667. * put bridges in old_routers. */
  2668. const int was_bridge = old_router &&
  2669. old_router->purpose == ROUTER_PURPOSE_BRIDGE;
  2670. if (routerinfo_is_a_configured_bridge(router) &&
  2671. router->purpose == ROUTER_PURPOSE_BRIDGE &&
  2672. !was_bridge) {
  2673. log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
  2674. "descriptor for router %s",
  2675. router_describe(router));
  2676. } else {
  2677. log_info(LD_DIR,
  2678. "Dropping descriptor that we already have for router %s",
  2679. router_describe(router));
  2680. *msg = "Router descriptor was not new.";
  2681. routerinfo_free(router);
  2682. return ROUTER_WAS_NOT_NEW;
  2683. }
  2684. }
  2685. if (authdir) {
  2686. if (authdir_wants_to_reject_router(router, msg,
  2687. !from_cache && !from_fetch,
  2688. &authdir_believes_valid)) {
  2689. tor_assert(*msg);
  2690. routerinfo_free(router);
  2691. return ROUTER_AUTHDIR_REJECTS;
  2692. }
  2693. } else if (from_fetch) {
  2694. /* Only check the descriptor digest against the network statuses when
  2695. * we are receiving in response to a fetch. */
  2696. if (!signed_desc_digest_is_recognized(&router->cache_info) &&
  2697. !routerinfo_is_a_configured_bridge(router)) {
  2698. /* We asked for it, so some networkstatus must have listed it when we
  2699. * did. Save it if we're a cache in case somebody else asks for it. */
  2700. log_info(LD_DIR,
  2701. "Received a no-longer-recognized descriptor for router %s",
  2702. router_describe(router));
  2703. *msg = "Router descriptor is not referenced by any network-status.";
  2704. /* Only journal this desc if we'll be serving it. */
  2705. if (!from_cache && should_cache_old_descriptors())
  2706. signed_desc_append_to_journal(&router->cache_info,
  2707. &routerlist->desc_store);
  2708. routerlist_insert_old(routerlist, router);
  2709. return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
  2710. }
  2711. }
  2712. /* We no longer need a router with this descriptor digest. */
  2713. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2714. {
  2715. routerstatus_t *rs =
  2716. networkstatus_v2_find_mutable_entry(ns, id_digest);
  2717. if (rs && tor_memeq(rs->descriptor_digest,
  2718. router->cache_info.signed_descriptor_digest,
  2719. DIGEST_LEN))
  2720. rs->need_to_mirror = 0;
  2721. });
  2722. if (consensus) {
  2723. routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
  2724. consensus, id_digest);
  2725. if (rs && tor_memeq(rs->descriptor_digest,
  2726. router->cache_info.signed_descriptor_digest,
  2727. DIGEST_LEN)) {
  2728. in_consensus = 1;
  2729. rs->need_to_mirror = 0;
  2730. }
  2731. }
  2732. if (router->purpose == ROUTER_PURPOSE_GENERAL &&
  2733. consensus && !in_consensus && !authdir) {
  2734. /* If it's a general router not listed in the consensus, then don't
  2735. * consider replacing the latest router with it. */
  2736. if (!from_cache && should_cache_old_descriptors())
  2737. signed_desc_append_to_journal(&router->cache_info,
  2738. &routerlist->desc_store);
  2739. routerlist_insert_old(routerlist, router);
  2740. *msg = "Skipping router descriptor: not in consensus.";
  2741. return ROUTER_NOT_IN_CONSENSUS;
  2742. }
  2743. /* If we're reading a bridge descriptor from our cache, and we don't
  2744. * recognize it as one of our currently configured bridges, drop the
  2745. * descriptor. Otherwise we could end up using it as one of our entry
  2746. * guards even if it isn't in our Bridge config lines. */
  2747. if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
  2748. !authdir_mode_bridge(options) &&
  2749. !routerinfo_is_a_configured_bridge(router)) {
  2750. log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
  2751. "no bridge configured at that address.",
  2752. safe_str_client(router_describe(router)));
  2753. *msg = "Router descriptor was not a configured bridge.";
  2754. routerinfo_free(router);
  2755. return ROUTER_WAS_NOT_WANTED;
  2756. }
  2757. /* If we have a router with the same identity key, choose the newer one. */
  2758. if (old_router) {
  2759. if (!in_consensus && (router->cache_info.published_on <=
  2760. old_router->cache_info.published_on)) {
  2761. /* Same key, but old. This one is not listed in the consensus. */
  2762. log_debug(LD_DIR, "Not-new descriptor for router %s",
  2763. router_describe(router));
  2764. /* Only journal this desc if we'll be serving it. */
  2765. if (!from_cache && should_cache_old_descriptors())
  2766. signed_desc_append_to_journal(&router->cache_info,
  2767. &routerlist->desc_store);
  2768. routerlist_insert_old(routerlist, router);
  2769. *msg = "Router descriptor was not new.";
  2770. return ROUTER_WAS_NOT_NEW;
  2771. } else {
  2772. /* Same key, and either new, or listed in the consensus. */
  2773. log_debug(LD_DIR, "Replacing entry for router %s",
  2774. router_describe(router));
  2775. routerlist_replace(routerlist, old_router, router);
  2776. if (!from_cache) {
  2777. signed_desc_append_to_journal(&router->cache_info,
  2778. &routerlist->desc_store);
  2779. }
  2780. directory_set_dirty();
  2781. *msg = authdir_believes_valid ? "Valid server updated" :
  2782. ("Invalid server updated. (This dirserver is marking your "
  2783. "server as unapproved.)");
  2784. return ROUTER_ADDED_SUCCESSFULLY;
  2785. }
  2786. }
  2787. if (!in_consensus && from_cache &&
  2788. router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
  2789. *msg = "Router descriptor was really old.";
  2790. routerinfo_free(router);
  2791. return ROUTER_WAS_NOT_NEW;
  2792. }
  2793. /* We haven't seen a router with this identity before. Add it to the end of
  2794. * the list. */
  2795. routerlist_insert(routerlist, router);
  2796. if (!from_cache) {
  2797. signed_desc_append_to_journal(&router->cache_info,
  2798. &routerlist->desc_store);
  2799. }
  2800. directory_set_dirty();
  2801. return ROUTER_ADDED_SUCCESSFULLY;
  2802. }
  2803. /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
  2804. * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
  2805. * we actually inserted it, ROUTER_BAD_EI otherwise.
  2806. */
  2807. was_router_added_t
  2808. router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
  2809. int from_cache, int from_fetch)
  2810. {
  2811. int inserted;
  2812. (void)from_fetch;
  2813. if (msg) *msg = NULL;
  2814. /*XXXX023 Do something with msg */
  2815. inserted = extrainfo_insert(router_get_routerlist(), ei);
  2816. if (inserted && !from_cache)
  2817. signed_desc_append_to_journal(&ei->cache_info,
  2818. &routerlist->extrainfo_store);
  2819. if (inserted)
  2820. return ROUTER_ADDED_SUCCESSFULLY;
  2821. else
  2822. return ROUTER_BAD_EI;
  2823. }
  2824. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  2825. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  2826. * to, or later than that of *<b>b</b>. */
  2827. static int
  2828. compare_old_routers_by_identity_(const void **_a, const void **_b)
  2829. {
  2830. int i;
  2831. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  2832. if ((i = fast_memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  2833. return i;
  2834. return (int)(r1->published_on - r2->published_on);
  2835. }
  2836. /** Internal type used to represent how long an old descriptor was valid,
  2837. * where it appeared in the list of old descriptors, and whether it's extra
  2838. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  2839. struct duration_idx_t {
  2840. int duration;
  2841. int idx;
  2842. int old;
  2843. };
  2844. /** Sorting helper: compare two duration_idx_t by their duration. */
  2845. static int
  2846. compare_duration_idx_(const void *_d1, const void *_d2)
  2847. {
  2848. const struct duration_idx_t *d1 = _d1;
  2849. const struct duration_idx_t *d2 = _d2;
  2850. return d1->duration - d2->duration;
  2851. }
  2852. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  2853. * must contain routerinfo_t with the same identity and with publication time
  2854. * in ascending order. Remove members from this range until there are no more
  2855. * than max_descriptors_per_router() remaining. Start by removing the oldest
  2856. * members from before <b>cutoff</b>, then remove members which were current
  2857. * for the lowest amount of time. The order of members of old_routers at
  2858. * indices <b>lo</b> or higher may be changed.
  2859. */
  2860. static void
  2861. routerlist_remove_old_cached_routers_with_id(time_t now,
  2862. time_t cutoff, int lo, int hi,
  2863. digestset_t *retain)
  2864. {
  2865. int i, n = hi-lo+1;
  2866. unsigned n_extra, n_rmv = 0;
  2867. struct duration_idx_t *lifespans;
  2868. uint8_t *rmv, *must_keep;
  2869. smartlist_t *lst = routerlist->old_routers;
  2870. #if 1
  2871. const char *ident;
  2872. tor_assert(hi < smartlist_len(lst));
  2873. tor_assert(lo <= hi);
  2874. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  2875. for (i = lo+1; i <= hi; ++i) {
  2876. signed_descriptor_t *r = smartlist_get(lst, i);
  2877. tor_assert(tor_memeq(ident, r->identity_digest, DIGEST_LEN));
  2878. }
  2879. #endif
  2880. /* Check whether we need to do anything at all. */
  2881. {
  2882. int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
  2883. if (n <= mdpr)
  2884. return;
  2885. n_extra = n - mdpr;
  2886. }
  2887. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  2888. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  2889. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  2890. /* Set lifespans to contain the lifespan and index of each server. */
  2891. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  2892. for (i = lo; i <= hi; ++i) {
  2893. signed_descriptor_t *r = smartlist_get(lst, i);
  2894. signed_descriptor_t *r_next;
  2895. lifespans[i-lo].idx = i;
  2896. if (r->last_listed_as_valid_until >= now ||
  2897. (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
  2898. must_keep[i-lo] = 1;
  2899. }
  2900. if (i < hi) {
  2901. r_next = smartlist_get(lst, i+1);
  2902. tor_assert(r->published_on <= r_next->published_on);
  2903. lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
  2904. } else {
  2905. r_next = NULL;
  2906. lifespans[i-lo].duration = INT_MAX;
  2907. }
  2908. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  2909. ++n_rmv;
  2910. lifespans[i-lo].old = 1;
  2911. rmv[i-lo] = 1;
  2912. }
  2913. }
  2914. if (n_rmv < n_extra) {
  2915. /**
  2916. * We aren't removing enough servers for being old. Sort lifespans by
  2917. * the duration of liveness, and remove the ones we're not already going to
  2918. * remove based on how long they were alive.
  2919. **/
  2920. qsort(lifespans, n, sizeof(struct duration_idx_t), compare_duration_idx_);
  2921. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  2922. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  2923. rmv[lifespans[i].idx-lo] = 1;
  2924. ++n_rmv;
  2925. }
  2926. }
  2927. }
  2928. i = hi;
  2929. do {
  2930. if (rmv[i-lo])
  2931. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  2932. } while (--i >= lo);
  2933. tor_free(must_keep);
  2934. tor_free(rmv);
  2935. tor_free(lifespans);
  2936. }
  2937. /** Deactivate any routers from the routerlist that are more than
  2938. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  2939. * remove old routers from the list of cached routers if we have too many.
  2940. */
  2941. void
  2942. routerlist_remove_old_routers(void)
  2943. {
  2944. int i, hi=-1;
  2945. const char *cur_id = NULL;
  2946. time_t now = time(NULL);
  2947. time_t cutoff;
  2948. routerinfo_t *router;
  2949. signed_descriptor_t *sd;
  2950. digestset_t *retain;
  2951. int caches = directory_caches_dir_info(get_options());
  2952. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  2953. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2954. int have_enough_v2;
  2955. const or_options_t *options = get_options();
  2956. trusted_dirs_remove_old_certs();
  2957. if (!routerlist || !consensus)
  2958. return;
  2959. // routerlist_assert_ok(routerlist);
  2960. /* We need to guess how many router descriptors we will wind up wanting to
  2961. retain, so that we can be sure to allocate a large enough Bloom filter
  2962. to hold the digest set. Overestimating is fine; underestimating is bad.
  2963. */
  2964. {
  2965. /* We'll probably retain everything in the consensus. */
  2966. int n_max_retain = smartlist_len(consensus->routerstatus_list);
  2967. if (caches && networkstatus_v2_list) {
  2968. /* If we care about v2 statuses, we'll retain at most as many as are
  2969. listed any of the v2 statues. This will be at least the length of
  2970. the largest v2 networkstatus, and in the worst case, this set will be
  2971. equal to the sum of the lengths of all v2 consensuses. Take the
  2972. worst case.
  2973. */
  2974. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2975. n_max_retain += smartlist_len(ns->entries));
  2976. }
  2977. retain = digestset_new(n_max_retain);
  2978. }
  2979. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  2980. /* Build a list of all the descriptors that _anybody_ lists. */
  2981. if (caches && networkstatus_v2_list) {
  2982. SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
  2983. /* XXXX The inner loop here gets pretty expensive, and actually shows up
  2984. * on some profiles. It may be the reason digestmap_set shows up in
  2985. * profiles too. If instead we kept a per-descriptor digest count of
  2986. * how many networkstatuses recommended each descriptor, and changed
  2987. * that only when the networkstatuses changed, that would be a speed
  2988. * improvement, possibly 1-4% if it also removes digestmap_set from the
  2989. * profile. Not worth it for 0.1.2.x, though. The new directory
  2990. * system will obsolete this whole thing in 0.2.0.x. */
  2991. SMARTLIST_FOREACH_BEGIN(ns->entries, routerstatus_t *, rs) {
  2992. if (rs->published_on >= cutoff)
  2993. digestset_add(retain, rs->descriptor_digest);
  2994. } SMARTLIST_FOREACH_END(rs);
  2995. } SMARTLIST_FOREACH_END(ns);
  2996. }
  2997. /* Retain anything listed in the consensus. */
  2998. if (consensus) {
  2999. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  3000. if (rs->published_on >= cutoff)
  3001. digestset_add(retain, rs->descriptor_digest));
  3002. }
  3003. /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
  3004. * we should consider pruning current routers that are too old and that
  3005. * nobody recommends. (If we don't have a consensus or enough v2
  3006. * networkstatuses, then we should get more before we decide to kill
  3007. * routers.) */
  3008. /* we set this to true iff we don't care about v2 info, or we have enough. */
  3009. have_enough_v2 = !caches ||
  3010. !(authdir_mode_any_main(options) || options->FetchV2Networkstatus) ||
  3011. (networkstatus_v2_list &&
  3012. smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
  3013. if (have_enough_v2 && consensus) {
  3014. cutoff = now - ROUTER_MAX_AGE;
  3015. /* Remove too-old unrecommended members of routerlist->routers. */
  3016. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  3017. router = smartlist_get(routerlist->routers, i);
  3018. if (router->cache_info.published_on <= cutoff &&
  3019. router->cache_info.last_listed_as_valid_until < now &&
  3020. !digestset_isin(retain,
  3021. router->cache_info.signed_descriptor_digest)) {
  3022. /* Too old: remove it. (If we're a cache, just move it into
  3023. * old_routers.) */
  3024. log_info(LD_DIR,
  3025. "Forgetting obsolete (too old) routerinfo for router %s",
  3026. router_describe(router));
  3027. routerlist_remove(routerlist, router, 1, now);
  3028. i--;
  3029. }
  3030. }
  3031. }
  3032. //routerlist_assert_ok(routerlist);
  3033. /* Remove far-too-old members of routerlist->old_routers. */
  3034. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3035. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3036. sd = smartlist_get(routerlist->old_routers, i);
  3037. if (sd->published_on <= cutoff &&
  3038. sd->last_listed_as_valid_until < now &&
  3039. !digestset_isin(retain, sd->signed_descriptor_digest)) {
  3040. /* Too old. Remove it. */
  3041. routerlist_remove_old(routerlist, sd, i--);
  3042. }
  3043. }
  3044. //routerlist_assert_ok(routerlist);
  3045. log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
  3046. smartlist_len(routerlist->routers),
  3047. smartlist_len(routerlist->old_routers));
  3048. /* Now we might have to look at routerlist->old_routers for extraneous
  3049. * members. (We'd keep all the members if we could, but we need to save
  3050. * space.) First, check whether we have too many router descriptors, total.
  3051. * We're okay with having too many for some given router, so long as the
  3052. * total number doesn't approach max_descriptors_per_router()*len(router).
  3053. */
  3054. if (smartlist_len(routerlist->old_routers) <
  3055. smartlist_len(routerlist->routers))
  3056. goto done;
  3057. /* Sort by identity, then fix indices. */
  3058. smartlist_sort(routerlist->old_routers, compare_old_routers_by_identity_);
  3059. /* Fix indices. */
  3060. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3061. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3062. r->routerlist_index = i;
  3063. }
  3064. /* Iterate through the list from back to front, so when we remove descriptors
  3065. * we don't mess up groups we haven't gotten to. */
  3066. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  3067. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3068. if (!cur_id) {
  3069. cur_id = r->identity_digest;
  3070. hi = i;
  3071. }
  3072. if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
  3073. routerlist_remove_old_cached_routers_with_id(now,
  3074. cutoff, i+1, hi, retain);
  3075. cur_id = r->identity_digest;
  3076. hi = i;
  3077. }
  3078. }
  3079. if (hi>=0)
  3080. routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
  3081. //routerlist_assert_ok(routerlist);
  3082. done:
  3083. digestset_free(retain);
  3084. router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
  3085. router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
  3086. }
  3087. /** We just added a new set of descriptors. Take whatever extra steps
  3088. * we need. */
  3089. void
  3090. routerlist_descriptors_added(smartlist_t *sl, int from_cache)
  3091. {
  3092. tor_assert(sl);
  3093. control_event_descriptors_changed(sl);
  3094. SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
  3095. if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
  3096. learned_bridge_descriptor(ri, from_cache);
  3097. if (ri->needs_retest_if_added) {
  3098. ri->needs_retest_if_added = 0;
  3099. dirserv_single_reachability_test(approx_time(), ri);
  3100. }
  3101. } SMARTLIST_FOREACH_END(ri);
  3102. }
  3103. /**
  3104. * Code to parse a single router descriptor and insert it into the
  3105. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  3106. * descriptor was well-formed but could not be added; and 1 if the
  3107. * descriptor was added.
  3108. *
  3109. * If we don't add it and <b>msg</b> is not NULL, then assign to
  3110. * *<b>msg</b> a static string describing the reason for refusing the
  3111. * descriptor.
  3112. *
  3113. * This is used only by the controller.
  3114. */
  3115. int
  3116. router_load_single_router(const char *s, uint8_t purpose, int cache,
  3117. const char **msg)
  3118. {
  3119. routerinfo_t *ri;
  3120. was_router_added_t r;
  3121. smartlist_t *lst;
  3122. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  3123. tor_assert(msg);
  3124. *msg = NULL;
  3125. tor_snprintf(annotation_buf, sizeof(annotation_buf),
  3126. "@source controller\n"
  3127. "@purpose %s\n", router_purpose_to_string(purpose));
  3128. if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
  3129. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  3130. *msg = "Couldn't parse router descriptor.";
  3131. return -1;
  3132. }
  3133. tor_assert(ri->purpose == purpose);
  3134. if (router_is_me(ri)) {
  3135. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  3136. *msg = "Router's identity key matches mine.";
  3137. routerinfo_free(ri);
  3138. return 0;
  3139. }
  3140. if (!cache) /* obey the preference of the controller */
  3141. ri->cache_info.do_not_cache = 1;
  3142. lst = smartlist_new();
  3143. smartlist_add(lst, ri);
  3144. routers_update_status_from_consensus_networkstatus(lst, 0);
  3145. r = router_add_to_routerlist(ri, msg, 0, 0);
  3146. if (!WRA_WAS_ADDED(r)) {
  3147. /* we've already assigned to *msg now, and ri is already freed */
  3148. tor_assert(*msg);
  3149. if (r == ROUTER_AUTHDIR_REJECTS)
  3150. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  3151. smartlist_free(lst);
  3152. return 0;
  3153. } else {
  3154. routerlist_descriptors_added(lst, 0);
  3155. smartlist_free(lst);
  3156. log_debug(LD_DIR, "Added router to list");
  3157. return 1;
  3158. }
  3159. }
  3160. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  3161. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  3162. * are in response to a query to the network: cache them by adding them to
  3163. * the journal.
  3164. *
  3165. * Return the number of routers actually added.
  3166. *
  3167. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  3168. * uppercased fingerprints. Do not update any router whose
  3169. * fingerprint is not on the list; after updating a router, remove its
  3170. * fingerprint from the list.
  3171. *
  3172. * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
  3173. * are descriptor digests. Otherwise they are identity digests.
  3174. */
  3175. int
  3176. router_load_routers_from_string(const char *s, const char *eos,
  3177. saved_location_t saved_location,
  3178. smartlist_t *requested_fingerprints,
  3179. int descriptor_digests,
  3180. const char *prepend_annotations)
  3181. {
  3182. smartlist_t *routers = smartlist_new(), *changed = smartlist_new();
  3183. char fp[HEX_DIGEST_LEN+1];
  3184. const char *msg;
  3185. int from_cache = (saved_location != SAVED_NOWHERE);
  3186. int allow_annotations = (saved_location != SAVED_NOWHERE);
  3187. int any_changed = 0;
  3188. router_parse_list_from_string(&s, eos, routers, saved_location, 0,
  3189. allow_annotations, prepend_annotations);
  3190. routers_update_status_from_consensus_networkstatus(routers, !from_cache);
  3191. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  3192. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  3193. was_router_added_t r;
  3194. char d[DIGEST_LEN];
  3195. if (requested_fingerprints) {
  3196. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3197. ri->cache_info.signed_descriptor_digest :
  3198. ri->cache_info.identity_digest,
  3199. DIGEST_LEN);
  3200. if (smartlist_string_isin(requested_fingerprints, fp)) {
  3201. smartlist_string_remove(requested_fingerprints, fp);
  3202. } else {
  3203. char *requested =
  3204. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  3205. log_warn(LD_DIR,
  3206. "We received a router descriptor with a fingerprint (%s) "
  3207. "that we never requested. (We asked for: %s.) Dropping.",
  3208. fp, requested);
  3209. tor_free(requested);
  3210. routerinfo_free(ri);
  3211. continue;
  3212. }
  3213. }
  3214. memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
  3215. r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
  3216. if (WRA_WAS_ADDED(r)) {
  3217. any_changed++;
  3218. smartlist_add(changed, ri);
  3219. routerlist_descriptors_added(changed, from_cache);
  3220. smartlist_clear(changed);
  3221. } else if (WRA_WAS_REJECTED(r)) {
  3222. download_status_t *dl_status;
  3223. dl_status = router_get_dl_status_by_descriptor_digest(d);
  3224. if (dl_status) {
  3225. log_info(LD_GENERAL, "Marking router %s as never downloadable",
  3226. hex_str(d, DIGEST_LEN));
  3227. download_status_mark_impossible(dl_status);
  3228. }
  3229. }
  3230. } SMARTLIST_FOREACH_END(ri);
  3231. routerlist_assert_ok(routerlist);
  3232. if (any_changed)
  3233. router_rebuild_store(0, &routerlist->desc_store);
  3234. smartlist_free(routers);
  3235. smartlist_free(changed);
  3236. return any_changed;
  3237. }
  3238. /** Parse one or more extrainfos from <b>s</b> (ending immediately before
  3239. * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
  3240. * router_load_routers_from_string(). */
  3241. void
  3242. router_load_extrainfo_from_string(const char *s, const char *eos,
  3243. saved_location_t saved_location,
  3244. smartlist_t *requested_fingerprints,
  3245. int descriptor_digests)
  3246. {
  3247. smartlist_t *extrainfo_list = smartlist_new();
  3248. const char *msg;
  3249. int from_cache = (saved_location != SAVED_NOWHERE);
  3250. router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
  3251. NULL);
  3252. log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
  3253. SMARTLIST_FOREACH_BEGIN(extrainfo_list, extrainfo_t *, ei) {
  3254. was_router_added_t added =
  3255. router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
  3256. if (WRA_WAS_ADDED(added) && requested_fingerprints) {
  3257. char fp[HEX_DIGEST_LEN+1];
  3258. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3259. ei->cache_info.signed_descriptor_digest :
  3260. ei->cache_info.identity_digest,
  3261. DIGEST_LEN);
  3262. smartlist_string_remove(requested_fingerprints, fp);
  3263. /* We silently let people stuff us with extrainfos we didn't ask for,
  3264. * so long as we would have wanted them anyway. Since we always fetch
  3265. * all the extrainfos we want, and we never actually act on them
  3266. * inside Tor, this should be harmless. */
  3267. }
  3268. } SMARTLIST_FOREACH_END(ei);
  3269. routerlist_assert_ok(routerlist);
  3270. router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
  3271. smartlist_free(extrainfo_list);
  3272. }
  3273. /** Return true iff any networkstatus includes a descriptor whose digest
  3274. * is that of <b>desc</b>. */
  3275. static int
  3276. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  3277. {
  3278. const routerstatus_t *rs;
  3279. networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3280. int caches = directory_caches_dir_info(get_options());
  3281. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3282. if (consensus) {
  3283. rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
  3284. if (rs && tor_memeq(rs->descriptor_digest,
  3285. desc->signed_descriptor_digest, DIGEST_LEN))
  3286. return 1;
  3287. }
  3288. if (caches && networkstatus_v2_list) {
  3289. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3290. {
  3291. if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
  3292. continue;
  3293. if (tor_memeq(rs->descriptor_digest,
  3294. desc->signed_descriptor_digest, DIGEST_LEN))
  3295. return 1;
  3296. });
  3297. }
  3298. return 0;
  3299. }
  3300. /** Update downloads for router descriptors and/or microdescriptors as
  3301. * appropriate. */
  3302. void
  3303. update_all_descriptor_downloads(time_t now)
  3304. {
  3305. if (get_options()->DisableNetwork)
  3306. return;
  3307. update_router_descriptor_downloads(now);
  3308. update_microdesc_downloads(now);
  3309. launch_dummy_descriptor_download_as_needed(now, get_options());
  3310. }
  3311. /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
  3312. * give it all a try again. */
  3313. void
  3314. routerlist_retry_directory_downloads(time_t now)
  3315. {
  3316. router_reset_status_download_failures();
  3317. router_reset_descriptor_download_failures();
  3318. if (get_options()->DisableNetwork)
  3319. return;
  3320. update_networkstatus_downloads(now);
  3321. update_all_descriptor_downloads(now);
  3322. }
  3323. /** Return true iff <b>router</b> does not permit exit streams.
  3324. */
  3325. int
  3326. router_exit_policy_rejects_all(const routerinfo_t *router)
  3327. {
  3328. return router->policy_is_reject_star;
  3329. }
  3330. /** Add to the list of authoritative directory servers one at
  3331. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  3332. * <b>address</b> is NULL, add ourself. Return the new trusted directory
  3333. * server entry on success or NULL if we couldn't add it. */
  3334. trusted_dir_server_t *
  3335. add_trusted_dir_server(const char *nickname, const char *address,
  3336. uint16_t dir_port, uint16_t or_port,
  3337. const char *digest, const char *v3_auth_digest,
  3338. dirinfo_type_t type)
  3339. {
  3340. trusted_dir_server_t *ent;
  3341. uint32_t a;
  3342. char *hostname = NULL;
  3343. if (!trusted_dir_servers)
  3344. trusted_dir_servers = smartlist_new();
  3345. if (!address) { /* The address is us; we should guess. */
  3346. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  3347. log_warn(LD_CONFIG,
  3348. "Couldn't find a suitable address when adding ourself as a "
  3349. "trusted directory server.");
  3350. return NULL;
  3351. }
  3352. } else {
  3353. if (tor_lookup_hostname(address, &a)) {
  3354. log_warn(LD_CONFIG,
  3355. "Unable to lookup address for directory server at '%s'",
  3356. address);
  3357. return NULL;
  3358. }
  3359. hostname = tor_strdup(address);
  3360. }
  3361. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  3362. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  3363. ent->address = hostname;
  3364. ent->addr = a;
  3365. ent->dir_port = dir_port;
  3366. ent->or_port = or_port;
  3367. ent->is_running = 1;
  3368. ent->type = type;
  3369. memcpy(ent->digest, digest, DIGEST_LEN);
  3370. if (v3_auth_digest && (type & V3_DIRINFO))
  3371. memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
  3372. if (nickname)
  3373. tor_asprintf(&ent->description, "directory server \"%s\" at %s:%d",
  3374. nickname, hostname, (int)dir_port);
  3375. else
  3376. tor_asprintf(&ent->description, "directory server at %s:%d",
  3377. hostname, (int)dir_port);
  3378. ent->fake_status.addr = ent->addr;
  3379. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  3380. if (nickname)
  3381. strlcpy(ent->fake_status.nickname, nickname,
  3382. sizeof(ent->fake_status.nickname));
  3383. else
  3384. ent->fake_status.nickname[0] = '\0';
  3385. ent->fake_status.dir_port = ent->dir_port;
  3386. ent->fake_status.or_port = ent->or_port;
  3387. smartlist_add(trusted_dir_servers, ent);
  3388. router_dir_info_changed();
  3389. return ent;
  3390. }
  3391. /** Free storage held in <b>cert</b>. */
  3392. void
  3393. authority_cert_free(authority_cert_t *cert)
  3394. {
  3395. if (!cert)
  3396. return;
  3397. tor_free(cert->cache_info.signed_descriptor_body);
  3398. crypto_pk_free(cert->signing_key);
  3399. crypto_pk_free(cert->identity_key);
  3400. tor_free(cert);
  3401. }
  3402. /** Free storage held in <b>ds</b>. */
  3403. static void
  3404. trusted_dir_server_free(trusted_dir_server_t *ds)
  3405. {
  3406. if (!ds)
  3407. return;
  3408. tor_free(ds->nickname);
  3409. tor_free(ds->description);
  3410. tor_free(ds->address);
  3411. tor_free(ds);
  3412. }
  3413. /** Remove all members from the list of trusted dir servers. */
  3414. void
  3415. clear_trusted_dir_servers(void)
  3416. {
  3417. if (trusted_dir_servers) {
  3418. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  3419. trusted_dir_server_free(ent));
  3420. smartlist_clear(trusted_dir_servers);
  3421. } else {
  3422. trusted_dir_servers = smartlist_new();
  3423. }
  3424. router_dir_info_changed();
  3425. }
  3426. /** Return 1 if any trusted dir server supports v1 directories,
  3427. * else return 0. */
  3428. int
  3429. any_trusted_dir_is_v1_authority(void)
  3430. {
  3431. if (trusted_dir_servers)
  3432. return get_n_authorities(V1_DIRINFO) > 0;
  3433. return 0;
  3434. }
  3435. /** For every current directory connection whose purpose is <b>purpose</b>,
  3436. * and where the resource being downloaded begins with <b>prefix</b>, split
  3437. * rest of the resource into base16 fingerprints (or base64 fingerprints if
  3438. * purpose==DIR_PURPPOSE_FETCH_MICRODESC), decode them, and set the
  3439. * corresponding elements of <b>result</b> to a nonzero value.
  3440. */
  3441. static void
  3442. list_pending_downloads(digestmap_t *result,
  3443. int purpose, const char *prefix)
  3444. {
  3445. const size_t p_len = strlen(prefix);
  3446. smartlist_t *tmp = smartlist_new();
  3447. smartlist_t *conns = get_connection_array();
  3448. int flags = DSR_HEX;
  3449. if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
  3450. flags = DSR_DIGEST256|DSR_BASE64;
  3451. tor_assert(result);
  3452. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3453. if (conn->type == CONN_TYPE_DIR &&
  3454. conn->purpose == purpose &&
  3455. !conn->marked_for_close) {
  3456. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3457. if (!strcmpstart(resource, prefix))
  3458. dir_split_resource_into_fingerprints(resource + p_len,
  3459. tmp, NULL, flags);
  3460. }
  3461. } SMARTLIST_FOREACH_END(conn);
  3462. SMARTLIST_FOREACH(tmp, char *, d,
  3463. {
  3464. digestmap_set(result, d, (void*)1);
  3465. tor_free(d);
  3466. });
  3467. smartlist_free(tmp);
  3468. }
  3469. /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
  3470. * true) we are currently downloading by descriptor digest, set result[d] to
  3471. * (void*)1. */
  3472. static void
  3473. list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
  3474. {
  3475. int purpose =
  3476. extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
  3477. list_pending_downloads(result, purpose, "d/");
  3478. }
  3479. /** For every microdescriptor we are currently downloading by descriptor
  3480. * digest, set result[d] to (void*)1. (Note that microdescriptor digests
  3481. * are 256-bit, and digestmap_t only holds 160-bit digests, so we're only
  3482. * getting the first 20 bytes of each digest here.)
  3483. *
  3484. * XXXX Let there be a digestmap256_t, and use that instead.
  3485. */
  3486. void
  3487. list_pending_microdesc_downloads(digestmap_t *result)
  3488. {
  3489. list_pending_downloads(result, DIR_PURPOSE_FETCH_MICRODESC, "d/");
  3490. }
  3491. /** Launch downloads for all the descriptors whose digests or digests256
  3492. * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
  3493. * range.) If <b>source</b> is given, download from <b>source</b>;
  3494. * otherwise, download from an appropriate random directory server.
  3495. */
  3496. static void
  3497. initiate_descriptor_downloads(const routerstatus_t *source,
  3498. int purpose,
  3499. smartlist_t *digests,
  3500. int lo, int hi, int pds_flags)
  3501. {
  3502. int i, n = hi-lo;
  3503. char *resource, *cp;
  3504. size_t r_len;
  3505. int digest_len = DIGEST_LEN, enc_digest_len = HEX_DIGEST_LEN;
  3506. char sep = '+';
  3507. int b64_256 = 0;
  3508. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3509. /* Microdescriptors are downloaded by "-"-separated base64-encoded
  3510. * 256-bit digests. */
  3511. digest_len = DIGEST256_LEN;
  3512. enc_digest_len = BASE64_DIGEST256_LEN;
  3513. sep = '-';
  3514. b64_256 = 1;
  3515. }
  3516. if (n <= 0)
  3517. return;
  3518. if (lo < 0)
  3519. lo = 0;
  3520. if (hi > smartlist_len(digests))
  3521. hi = smartlist_len(digests);
  3522. r_len = 8 + (enc_digest_len+1)*n;
  3523. cp = resource = tor_malloc(r_len);
  3524. memcpy(cp, "d/", 2);
  3525. cp += 2;
  3526. for (i = lo; i < hi; ++i) {
  3527. if (b64_256) {
  3528. digest256_to_base64(cp, smartlist_get(digests, i));
  3529. } else {
  3530. base16_encode(cp, r_len-(cp-resource),
  3531. smartlist_get(digests,i), digest_len);
  3532. }
  3533. cp += enc_digest_len;
  3534. *cp++ = sep;
  3535. }
  3536. memcpy(cp-1, ".z", 3);
  3537. if (source) {
  3538. /* We know which authority we want. */
  3539. directory_initiate_command_routerstatus(source, purpose,
  3540. ROUTER_PURPOSE_GENERAL,
  3541. DIRIND_ONEHOP,
  3542. resource, NULL, 0, 0);
  3543. } else {
  3544. directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
  3545. pds_flags);
  3546. }
  3547. tor_free(resource);
  3548. }
  3549. /** Max amount of hashes to download per request.
  3550. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3551. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3552. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3553. * So use 96 because it's a nice number.
  3554. */
  3555. #define MAX_DL_PER_REQUEST 96
  3556. #define MAX_MICRODESC_DL_PER_REQUEST 92
  3557. /** Don't split our requests so finely that we are requesting fewer than
  3558. * this number per server. */
  3559. #define MIN_DL_PER_REQUEST 4
  3560. /** To prevent a single screwy cache from confusing us by selective reply,
  3561. * try to split our requests into at least this many requests. */
  3562. #define MIN_REQUESTS 3
  3563. /** If we want fewer than this many descriptors, wait until we
  3564. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3565. * passed. */
  3566. #define MAX_DL_TO_DELAY 16
  3567. /** When directory clients have only a few servers to request, they batch
  3568. * them until they have more, or until this amount of time has passed. */
  3569. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3570. /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
  3571. * router descriptor digests or microdescriptor digest256s in
  3572. * <b>downloadable</b>, decide whether to delay fetching until we have more.
  3573. * If we don't want to delay, launch one or more requests to the appropriate
  3574. * directory authorities.
  3575. */
  3576. void
  3577. launch_descriptor_downloads(int purpose,
  3578. smartlist_t *downloadable,
  3579. const routerstatus_t *source, time_t now)
  3580. {
  3581. int should_delay = 0, n_downloadable;
  3582. const or_options_t *options = get_options();
  3583. const char *descname;
  3584. tor_assert(purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  3585. purpose == DIR_PURPOSE_FETCH_MICRODESC);
  3586. descname = (purpose == DIR_PURPOSE_FETCH_SERVERDESC) ?
  3587. "routerdesc" : "microdesc";
  3588. n_downloadable = smartlist_len(downloadable);
  3589. if (!directory_fetches_dir_info_early(options)) {
  3590. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3591. log_debug(LD_DIR,
  3592. "There are enough downloadable %ss to launch requests.",
  3593. descname);
  3594. should_delay = 0;
  3595. } else {
  3596. should_delay = (last_descriptor_download_attempted +
  3597. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3598. if (!should_delay && n_downloadable) {
  3599. if (last_descriptor_download_attempted) {
  3600. log_info(LD_DIR,
  3601. "There are not many downloadable %ss, but we've "
  3602. "been waiting long enough (%d seconds). Downloading.",
  3603. descname,
  3604. (int)(now-last_descriptor_download_attempted));
  3605. } else {
  3606. log_info(LD_DIR,
  3607. "There are not many downloadable %ss, but we haven't "
  3608. "tried downloading descriptors recently. Downloading.",
  3609. descname);
  3610. }
  3611. }
  3612. }
  3613. }
  3614. if (! should_delay && n_downloadable) {
  3615. int i, n_per_request;
  3616. const char *req_plural = "", *rtr_plural = "";
  3617. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3618. if (! authdir_mode_any_nonhidserv(options)) {
  3619. /* If we wind up going to the authorities, we want to only open one
  3620. * connection to each authority at a time, so that we don't overload
  3621. * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
  3622. * regardless of whether we're a cache or not; it gets ignored if we're
  3623. * not calling router_pick_trusteddirserver.
  3624. *
  3625. * Setting this flag can make initiate_descriptor_downloads() ignore
  3626. * requests. We need to make sure that we do in fact call
  3627. * update_router_descriptor_downloads() later on, once the connections
  3628. * have succeeded or failed.
  3629. */
  3630. pds_flags |= (purpose == DIR_PURPOSE_FETCH_MICRODESC) ?
  3631. PDS_NO_EXISTING_MICRODESC_FETCH :
  3632. PDS_NO_EXISTING_SERVERDESC_FETCH;
  3633. }
  3634. n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
  3635. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3636. if (n_per_request > MAX_MICRODESC_DL_PER_REQUEST)
  3637. n_per_request = MAX_MICRODESC_DL_PER_REQUEST;
  3638. } else {
  3639. if (n_per_request > MAX_DL_PER_REQUEST)
  3640. n_per_request = MAX_DL_PER_REQUEST;
  3641. }
  3642. if (n_per_request < MIN_DL_PER_REQUEST)
  3643. n_per_request = MIN_DL_PER_REQUEST;
  3644. if (n_downloadable > n_per_request)
  3645. req_plural = rtr_plural = "s";
  3646. else if (n_downloadable > 1)
  3647. rtr_plural = "s";
  3648. log_info(LD_DIR,
  3649. "Launching %d request%s for %d %s%s, %d at a time",
  3650. CEIL_DIV(n_downloadable, n_per_request), req_plural,
  3651. n_downloadable, descname, rtr_plural, n_per_request);
  3652. smartlist_sort_digests(downloadable);
  3653. for (i=0; i < n_downloadable; i += n_per_request) {
  3654. initiate_descriptor_downloads(source, purpose,
  3655. downloadable, i, i+n_per_request,
  3656. pds_flags);
  3657. }
  3658. last_descriptor_download_attempted = now;
  3659. }
  3660. }
  3661. /** Launch downloads for router status as needed, using the strategy used by
  3662. * authorities and caches: based on the v2 networkstatuses we have, download
  3663. * every descriptor we don't have but would serve, from a random authority
  3664. * that lists it. */
  3665. static void
  3666. update_router_descriptor_cache_downloads_v2(time_t now)
  3667. {
  3668. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3669. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3670. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3671. int i, j, n;
  3672. int n_download;
  3673. const or_options_t *options = get_options();
  3674. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3675. if (! directory_fetches_dir_info_early(options)) {
  3676. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
  3677. "on a non-dir-mirror?");
  3678. }
  3679. if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
  3680. return;
  3681. map = digestmap_new();
  3682. n = smartlist_len(networkstatus_v2_list);
  3683. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3684. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3685. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3686. * downloading. */
  3687. list_pending_descriptor_downloads(map, 0);
  3688. /* For the digest of every descriptor that we don't have, and that we aren't
  3689. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3690. * about that descriptor, and we haven't already failed to get that
  3691. * descriptor from the corresponding authority.
  3692. */
  3693. n_download = 0;
  3694. SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
  3695. trusted_dir_server_t *ds;
  3696. smartlist_t *dl;
  3697. dl = downloadable[ns_sl_idx] = smartlist_new();
  3698. download_from[ns_sl_idx] = smartlist_new();
  3699. if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
  3700. /* Don't download if the networkstatus is almost ancient. */
  3701. /* Actually, I suspect what's happening here is that we ask
  3702. * for the descriptor when we have a given networkstatus,
  3703. * and then we get a newer networkstatus, and then we receive
  3704. * the descriptor. Having a networkstatus actually expire is
  3705. * probably a rare event, and we'll probably be happiest if
  3706. * we take this clause out. -RD */
  3707. continue;
  3708. }
  3709. /* Don't try dirservers that we think are down -- we might have
  3710. * just tried them and just marked them as down. */
  3711. ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
  3712. if (ds && !ds->is_running)
  3713. continue;
  3714. SMARTLIST_FOREACH_BEGIN(ns->entries, routerstatus_t * , rs) {
  3715. if (!rs->need_to_mirror)
  3716. continue;
  3717. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3718. log_warn(LD_BUG,
  3719. "We have a router descriptor, but need_to_mirror=1.");
  3720. rs->need_to_mirror = 0;
  3721. continue;
  3722. }
  3723. if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
  3724. rs->need_to_mirror = 0;
  3725. continue;
  3726. }
  3727. if (digestmap_get(map, rs->descriptor_digest)) {
  3728. /* We're downloading it already. */
  3729. continue;
  3730. } else {
  3731. /* We could download it from this guy. */
  3732. smartlist_add(dl, rs->descriptor_digest);
  3733. ++n_download;
  3734. }
  3735. } SMARTLIST_FOREACH_END(rs);
  3736. } SMARTLIST_FOREACH_END(ns);
  3737. /* At random, assign descriptors to authorities such that:
  3738. * - if d is a member of some downloadable[x], d is a member of some
  3739. * download_from[y]. (Everything we want to download, we try to download
  3740. * from somebody.)
  3741. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3742. * (We only try to download descriptors from authorities who claim to have
  3743. * them.)
  3744. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3745. * (We don't try to download anything from two authorities concurrently.)
  3746. */
  3747. while (n_download) {
  3748. int which_ns = crypto_rand_int(n);
  3749. smartlist_t *dl = downloadable[which_ns];
  3750. int idx;
  3751. char *d;
  3752. if (!smartlist_len(dl))
  3753. continue;
  3754. idx = crypto_rand_int(smartlist_len(dl));
  3755. d = smartlist_get(dl, idx);
  3756. if (! digestmap_get(map, d)) {
  3757. smartlist_add(download_from[which_ns], d);
  3758. digestmap_set(map, d, (void*) 1);
  3759. }
  3760. smartlist_del(dl, idx);
  3761. --n_download;
  3762. }
  3763. /* Now, we can actually launch our requests. */
  3764. for (i=0; i<n; ++i) {
  3765. networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
  3766. trusted_dir_server_t *ds =
  3767. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3768. smartlist_t *dl = download_from[i];
  3769. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3770. if (! authdir_mode_any_nonhidserv(options))
  3771. pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
  3772. if (!ds) {
  3773. log_info(LD_DIR, "Networkstatus with no corresponding authority!");
  3774. continue;
  3775. }
  3776. if (! smartlist_len(dl))
  3777. continue;
  3778. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3779. smartlist_len(dl), ds->nickname);
  3780. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3781. initiate_descriptor_downloads(&(ds->fake_status),
  3782. DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
  3783. j+MAX_DL_PER_REQUEST, pds_flags);
  3784. }
  3785. }
  3786. for (i=0; i<n; ++i) {
  3787. smartlist_free(download_from[i]);
  3788. smartlist_free(downloadable[i]);
  3789. }
  3790. tor_free(download_from);
  3791. tor_free(downloadable);
  3792. digestmap_free(map,NULL);
  3793. }
  3794. /** For any descriptor that we want that's currently listed in
  3795. * <b>consensus</b>, download it as appropriate. */
  3796. void
  3797. update_consensus_router_descriptor_downloads(time_t now, int is_vote,
  3798. networkstatus_t *consensus)
  3799. {
  3800. const or_options_t *options = get_options();
  3801. digestmap_t *map = NULL;
  3802. smartlist_t *no_longer_old = smartlist_new();
  3803. smartlist_t *downloadable = smartlist_new();
  3804. routerstatus_t *source = NULL;
  3805. int authdir = authdir_mode(options);
  3806. int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
  3807. n_inprogress=0, n_in_oldrouters=0;
  3808. if (directory_too_idle_to_fetch_descriptors(options, now))
  3809. goto done;
  3810. if (!consensus)
  3811. goto done;
  3812. if (is_vote) {
  3813. /* where's it from, so we know whom to ask for descriptors */
  3814. trusted_dir_server_t *ds;
  3815. networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
  3816. tor_assert(voter);
  3817. ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
  3818. if (ds)
  3819. source = &(ds->fake_status);
  3820. else
  3821. log_warn(LD_DIR, "couldn't lookup source from vote?");
  3822. }
  3823. map = digestmap_new();
  3824. list_pending_descriptor_downloads(map, 0);
  3825. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
  3826. routerstatus_t *rs =
  3827. is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
  3828. signed_descriptor_t *sd;
  3829. if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
  3830. const routerinfo_t *ri;
  3831. ++n_have;
  3832. if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
  3833. tor_memneq(ri->cache_info.signed_descriptor_digest,
  3834. sd->signed_descriptor_digest, DIGEST_LEN)) {
  3835. /* We have a descriptor with this digest, but either there is no
  3836. * entry in routerlist with the same ID (!ri), or there is one,
  3837. * but the identity digest differs (memcmp).
  3838. */
  3839. smartlist_add(no_longer_old, sd);
  3840. ++n_in_oldrouters; /* We have it in old_routers. */
  3841. }
  3842. continue; /* We have it already. */
  3843. }
  3844. if (digestmap_get(map, rs->descriptor_digest)) {
  3845. ++n_inprogress;
  3846. continue; /* We have an in-progress download. */
  3847. }
  3848. if (!download_status_is_ready(&rs->dl_status, now,
  3849. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  3850. ++n_delayed; /* Not ready for retry. */
  3851. continue;
  3852. }
  3853. if (authdir && dirserv_would_reject_router(rs)) {
  3854. ++n_would_reject;
  3855. continue; /* We would throw it out immediately. */
  3856. }
  3857. if (!directory_caches_dir_info(options) &&
  3858. !client_would_use_router(rs, now, options)) {
  3859. ++n_wouldnt_use;
  3860. continue; /* We would never use it ourself. */
  3861. }
  3862. if (is_vote && source) {
  3863. char time_bufnew[ISO_TIME_LEN+1];
  3864. char time_bufold[ISO_TIME_LEN+1];
  3865. const routerinfo_t *oldrouter;
  3866. oldrouter = router_get_by_id_digest(rs->identity_digest);
  3867. format_iso_time(time_bufnew, rs->published_on);
  3868. if (oldrouter)
  3869. format_iso_time(time_bufold, oldrouter->cache_info.published_on);
  3870. log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
  3871. routerstatus_describe(rs),
  3872. time_bufnew,
  3873. oldrouter ? time_bufold : "none",
  3874. source->nickname, oldrouter ? "known" : "unknown");
  3875. }
  3876. smartlist_add(downloadable, rs->descriptor_digest);
  3877. } SMARTLIST_FOREACH_END(rsp);
  3878. if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
  3879. && smartlist_len(no_longer_old)) {
  3880. routerlist_t *rl = router_get_routerlist();
  3881. log_info(LD_DIR, "%d router descriptors listed in consensus are "
  3882. "currently in old_routers; making them current.",
  3883. smartlist_len(no_longer_old));
  3884. SMARTLIST_FOREACH_BEGIN(no_longer_old, signed_descriptor_t *, sd) {
  3885. const char *msg;
  3886. was_router_added_t r;
  3887. routerinfo_t *ri = routerlist_reparse_old(rl, sd);
  3888. if (!ri) {
  3889. log_warn(LD_BUG, "Failed to re-parse a router.");
  3890. continue;
  3891. }
  3892. r = router_add_to_routerlist(ri, &msg, 1, 0);
  3893. if (WRA_WAS_OUTDATED(r)) {
  3894. log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
  3895. msg?msg:"???");
  3896. }
  3897. } SMARTLIST_FOREACH_END(sd);
  3898. routerlist_assert_ok(rl);
  3899. }
  3900. log_info(LD_DIR,
  3901. "%d router descriptors downloadable. %d delayed; %d present "
  3902. "(%d of those were in old_routers); %d would_reject; "
  3903. "%d wouldnt_use; %d in progress.",
  3904. smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
  3905. n_would_reject, n_wouldnt_use, n_inprogress);
  3906. launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC,
  3907. downloadable, source, now);
  3908. digestmap_free(map, NULL);
  3909. done:
  3910. smartlist_free(downloadable);
  3911. smartlist_free(no_longer_old);
  3912. }
  3913. /** How often should we launch a server/authority request to be sure of getting
  3914. * a guess for our IP? */
  3915. /*XXXX024 this info should come from netinfo cells or something, or we should
  3916. * do this only when we aren't seeing incoming data. see bug 652. */
  3917. #define DUMMY_DOWNLOAD_INTERVAL (20*60)
  3918. /** As needed, launch a dummy router descriptor fetch to see if our
  3919. * address has changed. */
  3920. static void
  3921. launch_dummy_descriptor_download_as_needed(time_t now,
  3922. const or_options_t *options)
  3923. {
  3924. static time_t last_dummy_download = 0;
  3925. /* XXXX024 we could be smarter here; see notes on bug 652. */
  3926. /* If we're a server that doesn't have a configured address, we rely on
  3927. * directory fetches to learn when our address changes. So if we haven't
  3928. * tried to get any routerdescs in a long time, try a dummy fetch now. */
  3929. if (!options->Address &&
  3930. server_mode(options) &&
  3931. last_descriptor_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
  3932. last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
  3933. last_dummy_download = now;
  3934. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  3935. ROUTER_PURPOSE_GENERAL, "authority.z",
  3936. PDS_RETRY_IF_NO_SERVERS);
  3937. }
  3938. }
  3939. /** Launch downloads for router status as needed. */
  3940. void
  3941. update_router_descriptor_downloads(time_t now)
  3942. {
  3943. const or_options_t *options = get_options();
  3944. if (should_delay_dir_fetches(options))
  3945. return;
  3946. if (!we_fetch_router_descriptors(options))
  3947. return;
  3948. if (directory_fetches_dir_info_early(options)) {
  3949. update_router_descriptor_cache_downloads_v2(now);
  3950. }
  3951. update_consensus_router_descriptor_downloads(now, 0,
  3952. networkstatus_get_reasonably_live_consensus(now, FLAV_NS));
  3953. }
  3954. /** Launch extrainfo downloads as needed. */
  3955. void
  3956. update_extrainfo_downloads(time_t now)
  3957. {
  3958. const or_options_t *options = get_options();
  3959. routerlist_t *rl;
  3960. smartlist_t *wanted;
  3961. digestmap_t *pending;
  3962. int old_routers, i;
  3963. int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
  3964. if (! options->DownloadExtraInfo)
  3965. return;
  3966. if (should_delay_dir_fetches(options))
  3967. return;
  3968. if (!router_have_minimum_dir_info())
  3969. return;
  3970. pending = digestmap_new();
  3971. list_pending_descriptor_downloads(pending, 1);
  3972. rl = router_get_routerlist();
  3973. wanted = smartlist_new();
  3974. for (old_routers = 0; old_routers < 2; ++old_routers) {
  3975. smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
  3976. for (i = 0; i < smartlist_len(lst); ++i) {
  3977. signed_descriptor_t *sd;
  3978. char *d;
  3979. if (old_routers)
  3980. sd = smartlist_get(lst, i);
  3981. else
  3982. sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
  3983. if (sd->is_extrainfo)
  3984. continue; /* This should never happen. */
  3985. if (old_routers && !router_get_by_id_digest(sd->identity_digest))
  3986. continue; /* Couldn't check the signature if we got it. */
  3987. if (sd->extrainfo_is_bogus)
  3988. continue;
  3989. d = sd->extra_info_digest;
  3990. if (tor_digest_is_zero(d)) {
  3991. ++n_no_ei;
  3992. continue;
  3993. }
  3994. if (eimap_get(rl->extra_info_map, d)) {
  3995. ++n_have;
  3996. continue;
  3997. }
  3998. if (!download_status_is_ready(&sd->ei_dl_status, now,
  3999. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  4000. ++n_delay;
  4001. continue;
  4002. }
  4003. if (digestmap_get(pending, d)) {
  4004. ++n_pending;
  4005. continue;
  4006. }
  4007. smartlist_add(wanted, d);
  4008. }
  4009. }
  4010. digestmap_free(pending, NULL);
  4011. log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
  4012. "with present ei, %d delaying, %d pending, %d downloadable.",
  4013. n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
  4014. smartlist_shuffle(wanted);
  4015. for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
  4016. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
  4017. wanted, i, i + MAX_DL_PER_REQUEST,
  4018. PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
  4019. }
  4020. smartlist_free(wanted);
  4021. }
  4022. /** Reset the descriptor download failure count on all routers, so that we
  4023. * can retry any long-failed routers immediately.
  4024. */
  4025. void
  4026. router_reset_descriptor_download_failures(void)
  4027. {
  4028. networkstatus_reset_download_failures();
  4029. last_descriptor_download_attempted = 0;
  4030. if (!routerlist)
  4031. return;
  4032. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  4033. {
  4034. download_status_reset(&ri->cache_info.ei_dl_status);
  4035. });
  4036. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  4037. {
  4038. download_status_reset(&sd->ei_dl_status);
  4039. });
  4040. }
  4041. /** Any changes in a router descriptor's publication time larger than this are
  4042. * automatically non-cosmetic. */
  4043. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
  4044. /** We allow uptime to vary from how much it ought to be by this much. */
  4045. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  4046. /** Return true iff the only differences between r1 and r2 are such that
  4047. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  4048. */
  4049. int
  4050. router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
  4051. {
  4052. time_t r1pub, r2pub;
  4053. long time_difference;
  4054. tor_assert(r1 && r2);
  4055. /* r1 should be the one that was published first. */
  4056. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  4057. const routerinfo_t *ri_tmp = r2;
  4058. r2 = r1;
  4059. r1 = ri_tmp;
  4060. }
  4061. /* If any key fields differ, they're different. */
  4062. if (strcasecmp(r1->address, r2->address) ||
  4063. strcasecmp(r1->nickname, r2->nickname) ||
  4064. r1->or_port != r2->or_port ||
  4065. !tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) ||
  4066. r1->ipv6_orport != r2->ipv6_orport ||
  4067. r1->dir_port != r2->dir_port ||
  4068. r1->purpose != r2->purpose ||
  4069. !crypto_pk_eq_keys(r1->onion_pkey, r2->onion_pkey) ||
  4070. !crypto_pk_eq_keys(r1->identity_pkey, r2->identity_pkey) ||
  4071. strcasecmp(r1->platform, r2->platform) ||
  4072. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  4073. (!r1->contact_info && r2->contact_info) ||
  4074. (r1->contact_info && r2->contact_info &&
  4075. strcasecmp(r1->contact_info, r2->contact_info)) ||
  4076. r1->is_hibernating != r2->is_hibernating ||
  4077. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  4078. return 0;
  4079. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  4080. return 0;
  4081. if (r1->declared_family && r2->declared_family) {
  4082. int i, n;
  4083. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  4084. return 0;
  4085. n = smartlist_len(r1->declared_family);
  4086. for (i=0; i < n; ++i) {
  4087. if (strcasecmp(smartlist_get(r1->declared_family, i),
  4088. smartlist_get(r2->declared_family, i)))
  4089. return 0;
  4090. }
  4091. }
  4092. /* Did bandwidth change a lot? */
  4093. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  4094. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  4095. return 0;
  4096. /* Did the bandwidthrate or bandwidthburst change? */
  4097. if ((r1->bandwidthrate != r2->bandwidthrate) ||
  4098. (r1->bandwidthburst != r2->bandwidthburst))
  4099. return 0;
  4100. /* Did more than 12 hours pass? */
  4101. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  4102. < r2->cache_info.published_on)
  4103. return 0;
  4104. /* Did uptime fail to increase by approximately the amount we would think,
  4105. * give or take some slop? */
  4106. r1pub = r1->cache_info.published_on;
  4107. r2pub = r2->cache_info.published_on;
  4108. time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  4109. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  4110. time_difference > r1->uptime * .05 &&
  4111. time_difference > r2->uptime * .05)
  4112. return 0;
  4113. /* Otherwise, the difference is cosmetic. */
  4114. return 1;
  4115. }
  4116. /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
  4117. * extrainfo document
  4118. * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
  4119. * dropped. Return 0 for "compatible", return 1 for "reject, and inform
  4120. * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
  4121. * <b>msg</b> is present, set *<b>msg</b> to a description of the
  4122. * incompatibility (if any).
  4123. **/
  4124. int
  4125. routerinfo_incompatible_with_extrainfo(const routerinfo_t *ri,
  4126. extrainfo_t *ei,
  4127. signed_descriptor_t *sd,
  4128. const char **msg)
  4129. {
  4130. int digest_matches, r=1;
  4131. tor_assert(ri);
  4132. tor_assert(ei);
  4133. if (!sd)
  4134. sd = (signed_descriptor_t*)&ri->cache_info;
  4135. if (ei->bad_sig) {
  4136. if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
  4137. return 1;
  4138. }
  4139. digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
  4140. sd->extra_info_digest, DIGEST_LEN);
  4141. /* The identity must match exactly to have been generated at the same time
  4142. * by the same router. */
  4143. if (tor_memneq(ri->cache_info.identity_digest,
  4144. ei->cache_info.identity_digest,
  4145. DIGEST_LEN)) {
  4146. if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
  4147. goto err; /* different servers */
  4148. }
  4149. if (ei->pending_sig) {
  4150. char signed_digest[128];
  4151. if (crypto_pk_public_checksig(ri->identity_pkey,
  4152. signed_digest, sizeof(signed_digest),
  4153. ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
  4154. tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
  4155. DIGEST_LEN)) {
  4156. ei->bad_sig = 1;
  4157. tor_free(ei->pending_sig);
  4158. if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
  4159. goto err; /* Bad signature, or no match. */
  4160. }
  4161. ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
  4162. tor_free(ei->pending_sig);
  4163. }
  4164. if (ei->cache_info.published_on < sd->published_on) {
  4165. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4166. goto err;
  4167. } else if (ei->cache_info.published_on > sd->published_on) {
  4168. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4169. r = -1;
  4170. goto err;
  4171. }
  4172. if (!digest_matches) {
  4173. if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
  4174. goto err; /* Digest doesn't match declared value. */
  4175. }
  4176. return 0;
  4177. err:
  4178. if (digest_matches) {
  4179. /* This signature was okay, and the digest was right: This is indeed the
  4180. * corresponding extrainfo. But insanely, it doesn't match the routerinfo
  4181. * that lists it. Don't try to fetch this one again. */
  4182. sd->extrainfo_is_bogus = 1;
  4183. }
  4184. return r;
  4185. }
  4186. /** Assert that the internal representation of <b>rl</b> is
  4187. * self-consistent. */
  4188. void
  4189. routerlist_assert_ok(const routerlist_t *rl)
  4190. {
  4191. routerinfo_t *r2;
  4192. signed_descriptor_t *sd2;
  4193. if (!rl)
  4194. return;
  4195. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, r) {
  4196. r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
  4197. tor_assert(r == r2);
  4198. sd2 = sdmap_get(rl->desc_digest_map,
  4199. r->cache_info.signed_descriptor_digest);
  4200. tor_assert(&(r->cache_info) == sd2);
  4201. tor_assert(r->cache_info.routerlist_index == r_sl_idx);
  4202. /* XXXX
  4203. *
  4204. * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
  4205. * commenting this out is just a band-aid.
  4206. *
  4207. * The problem is that, although well-behaved router descriptors
  4208. * should never have the same value for their extra_info_digest, it's
  4209. * possible for ill-behaved routers to claim whatever they like there.
  4210. *
  4211. * The real answer is to trash desc_by_eid_map and instead have
  4212. * something that indicates for a given extra-info digest we want,
  4213. * what its download status is. We'll do that as a part of routerlist
  4214. * refactoring once consensus directories are in. For now,
  4215. * this rep violation is probably harmless: an adversary can make us
  4216. * reset our retry count for an extrainfo, but that's not the end
  4217. * of the world. Changing the representation in 0.2.0.x would just
  4218. * destabilize the codebase.
  4219. if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
  4220. signed_descriptor_t *sd3 =
  4221. sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
  4222. tor_assert(sd3 == &(r->cache_info));
  4223. }
  4224. */
  4225. } SMARTLIST_FOREACH_END(r);
  4226. SMARTLIST_FOREACH_BEGIN(rl->old_routers, signed_descriptor_t *, sd) {
  4227. r2 = rimap_get(rl->identity_map, sd->identity_digest);
  4228. tor_assert(sd != &(r2->cache_info));
  4229. sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  4230. tor_assert(sd == sd2);
  4231. tor_assert(sd->routerlist_index == sd_sl_idx);
  4232. /* XXXX see above.
  4233. if (!tor_digest_is_zero(sd->extra_info_digest)) {
  4234. signed_descriptor_t *sd3 =
  4235. sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
  4236. tor_assert(sd3 == sd);
  4237. }
  4238. */
  4239. } SMARTLIST_FOREACH_END(sd);
  4240. RIMAP_FOREACH(rl->identity_map, d, r) {
  4241. tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
  4242. } DIGESTMAP_FOREACH_END;
  4243. SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
  4244. tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
  4245. } DIGESTMAP_FOREACH_END;
  4246. SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
  4247. tor_assert(!tor_digest_is_zero(d));
  4248. tor_assert(sd);
  4249. tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
  4250. } DIGESTMAP_FOREACH_END;
  4251. EIMAP_FOREACH(rl->extra_info_map, d, ei) {
  4252. signed_descriptor_t *sd;
  4253. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4254. d, DIGEST_LEN));
  4255. sd = sdmap_get(rl->desc_by_eid_map,
  4256. ei->cache_info.signed_descriptor_digest);
  4257. // tor_assert(sd); // XXXX see above
  4258. if (sd) {
  4259. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4260. sd->extra_info_digest, DIGEST_LEN));
  4261. }
  4262. } DIGESTMAP_FOREACH_END;
  4263. }
  4264. /** Allocate and return a new string representing the contact info
  4265. * and platform string for <b>router</b>,
  4266. * surrounded by quotes and using standard C escapes.
  4267. *
  4268. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  4269. * thread. Also, each call invalidates the last-returned value, so don't
  4270. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  4271. *
  4272. * If <b>router</b> is NULL, it just frees its internal memory and returns.
  4273. */
  4274. const char *
  4275. esc_router_info(const routerinfo_t *router)
  4276. {
  4277. static char *info=NULL;
  4278. char *esc_contact, *esc_platform;
  4279. tor_free(info);
  4280. if (!router)
  4281. return NULL; /* we're exiting; just free the memory we use */
  4282. esc_contact = esc_for_log(router->contact_info);
  4283. esc_platform = esc_for_log(router->platform);
  4284. tor_asprintf(&info, "Contact %s, Platform %s", esc_contact, esc_platform);
  4285. tor_free(esc_contact);
  4286. tor_free(esc_platform);
  4287. return info;
  4288. }
  4289. /** Helper for sorting: compare two routerinfos by their identity
  4290. * digest. */
  4291. static int
  4292. compare_routerinfo_by_id_digest_(const void **a, const void **b)
  4293. {
  4294. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  4295. return fast_memcmp(first->cache_info.identity_digest,
  4296. second->cache_info.identity_digest,
  4297. DIGEST_LEN);
  4298. }
  4299. /** Sort a list of routerinfo_t in ascending order of identity digest. */
  4300. void
  4301. routers_sort_by_identity(smartlist_t *routers)
  4302. {
  4303. smartlist_sort(routers, compare_routerinfo_by_id_digest_);
  4304. }
  4305. /** Called when we change a node set, or when we reload the geoip list:
  4306. * recompute all country info in all configuration node sets and in the
  4307. * routerlist. */
  4308. void
  4309. refresh_all_country_info(void)
  4310. {
  4311. const or_options_t *options = get_options();
  4312. if (options->EntryNodes)
  4313. routerset_refresh_countries(options->EntryNodes);
  4314. if (options->ExitNodes)
  4315. routerset_refresh_countries(options->ExitNodes);
  4316. if (options->ExcludeNodes)
  4317. routerset_refresh_countries(options->ExcludeNodes);
  4318. if (options->ExcludeExitNodes)
  4319. routerset_refresh_countries(options->ExcludeExitNodes);
  4320. if (options->ExcludeExitNodesUnion_)
  4321. routerset_refresh_countries(options->ExcludeExitNodesUnion_);
  4322. nodelist_refresh_countries();
  4323. }
  4324. /** Determine the routers that are responsible for <b>id</b> (binary) and
  4325. * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
  4326. * Return -1 if we're returning an empty smartlist, else return 0.
  4327. */
  4328. int
  4329. hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  4330. const char *id)
  4331. {
  4332. int start, found, n_added = 0, i;
  4333. networkstatus_t *c = networkstatus_get_latest_consensus();
  4334. if (!c || !smartlist_len(c->routerstatus_list)) {
  4335. log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
  4336. "rendezvous operations.");
  4337. return -1;
  4338. }
  4339. tor_assert(id);
  4340. start = networkstatus_vote_find_entry_idx(c, id, &found);
  4341. if (start == smartlist_len(c->routerstatus_list)) start = 0;
  4342. i = start;
  4343. do {
  4344. routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
  4345. if (r->is_hs_dir) {
  4346. smartlist_add(responsible_dirs, r);
  4347. if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
  4348. return 0;
  4349. }
  4350. if (++i == smartlist_len(c->routerstatus_list))
  4351. i = 0;
  4352. } while (i != start);
  4353. /* Even though we don't have the desired number of hidden service
  4354. * directories, be happy if we got any. */
  4355. return smartlist_len(responsible_dirs) ? 0 : -1;
  4356. }
  4357. /** Return true if this node is currently acting as hidden service
  4358. * directory, false otherwise. */
  4359. int
  4360. hid_serv_acting_as_directory(void)
  4361. {
  4362. const routerinfo_t *me = router_get_my_routerinfo();
  4363. if (!me)
  4364. return 0;
  4365. if (!get_options()->HidServDirectoryV2) {
  4366. log_info(LD_REND, "We are not acting as hidden service directory, "
  4367. "because we have not been configured as such.");
  4368. return 0;
  4369. }
  4370. return 1;
  4371. }
  4372. /** Return true if this node is responsible for storing the descriptor ID
  4373. * in <b>query</b> and false otherwise. */
  4374. int
  4375. hid_serv_responsible_for_desc_id(const char *query)
  4376. {
  4377. const routerinfo_t *me;
  4378. routerstatus_t *last_rs;
  4379. const char *my_id, *last_id;
  4380. int result;
  4381. smartlist_t *responsible;
  4382. if (!hid_serv_acting_as_directory())
  4383. return 0;
  4384. if (!(me = router_get_my_routerinfo()))
  4385. return 0; /* This is redundant, but let's be paranoid. */
  4386. my_id = me->cache_info.identity_digest;
  4387. responsible = smartlist_new();
  4388. if (hid_serv_get_responsible_directories(responsible, query) < 0) {
  4389. smartlist_free(responsible);
  4390. return 0;
  4391. }
  4392. last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
  4393. last_id = last_rs->identity_digest;
  4394. result = rend_id_is_in_interval(my_id, query, last_id);
  4395. smartlist_free(responsible);
  4396. return result;
  4397. }