routerlist.c 127 KB

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