routerlist.c 129 KB

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