routerlist.c 136 KB

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