routerlist.c 157 KB

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