routerlist.c 147 KB

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