routerlist.c 153 KB

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