routerlist.c 129 KB

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