routerlist.c 147 KB

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