routerlist.c 149 KB

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