routerlist.c 153 KB

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