routerlist.c 157 KB

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