routerlist.c 135 KB

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