routerlist.c 151 KB

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