routerlist.c 158 KB

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