routerlist.c 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792
  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. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  269. * known trusted dirservers. Callers must not modify the list or its
  270. * contents.
  271. */
  272. smartlist_t *
  273. router_get_trusted_dir_servers(void)
  274. {
  275. if (!trusted_dir_servers)
  276. trusted_dir_servers = smartlist_create();
  277. return 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. if (get_options()->AuthoritativeDir &&
  932. router_digest_is_me(digest))
  933. return 1;
  934. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  935. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  936. return 0;
  937. }
  938. /** Return the router in our routerlist whose hexadecimal key digest
  939. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  940. routerinfo_t *
  941. router_get_by_hexdigest(const char *hexdigest)
  942. {
  943. char digest[DIGEST_LEN];
  944. tor_assert(hexdigest);
  945. if (!routerlist)
  946. return NULL;
  947. if (hexdigest[0]=='$')
  948. ++hexdigest;
  949. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  950. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  951. return NULL;
  952. return router_get_by_digest(digest);
  953. }
  954. /** Return the router in our routerlist whose 20-byte key digest
  955. * is <b>digest</b>. Return NULL if no such router is known. */
  956. routerinfo_t *
  957. router_get_by_digest(const char *digest)
  958. {
  959. tor_assert(digest);
  960. if (!routerlist) return NULL;
  961. // routerlist_assert_ok(routerlist);
  962. return digestmap_get(routerlist->identity_map, digest);
  963. }
  964. /** Return the router in our routerlist whose 20-byte descriptor
  965. * is <b>digest</b>. Return NULL if no such router is known. */
  966. signed_descriptor_t *
  967. router_get_by_descriptor_digest(const char *digest)
  968. {
  969. tor_assert(digest);
  970. if (!routerlist) return NULL;
  971. return digestmap_get(routerlist->desc_digest_map, digest);
  972. }
  973. const char *
  974. signed_descriptor_get_body(signed_descriptor_t *desc)
  975. {
  976. return desc->signed_descriptor_body;
  977. }
  978. /** Return the current list of all known routers. */
  979. routerlist_t *
  980. router_get_routerlist(void)
  981. {
  982. if (!routerlist) {
  983. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  984. routerlist->routers = smartlist_create();
  985. routerlist->old_routers = smartlist_create();
  986. routerlist->identity_map = digestmap_new();
  987. routerlist->desc_digest_map = digestmap_new();
  988. }
  989. return routerlist;
  990. }
  991. /** Free all storage held by <b>router</b>. */
  992. void
  993. routerinfo_free(routerinfo_t *router)
  994. {
  995. if (!router)
  996. return;
  997. tor_free(router->cache_info.signed_descriptor_body);
  998. tor_free(router->address);
  999. tor_free(router->nickname);
  1000. tor_free(router->platform);
  1001. tor_free(router->contact_info);
  1002. if (router->onion_pkey)
  1003. crypto_free_pk_env(router->onion_pkey);
  1004. if (router->identity_pkey)
  1005. crypto_free_pk_env(router->identity_pkey);
  1006. if (router->declared_family) {
  1007. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  1008. smartlist_free(router->declared_family);
  1009. }
  1010. addr_policy_free(router->exit_policy);
  1011. tor_free(router);
  1012. }
  1013. /** Release storage held by <b>sd</b>. */
  1014. static void
  1015. signed_descriptor_free(signed_descriptor_t *sd)
  1016. {
  1017. tor_free(sd->signed_descriptor_body);
  1018. tor_free(sd);
  1019. }
  1020. /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
  1021. */
  1022. static signed_descriptor_t *
  1023. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  1024. {
  1025. signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  1026. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  1027. ri->cache_info.signed_descriptor_body = NULL;
  1028. routerinfo_free(ri);
  1029. return sd;
  1030. }
  1031. /** Free all storage held by a routerlist <b>rl</b> */
  1032. void
  1033. routerlist_free(routerlist_t *rl)
  1034. {
  1035. tor_assert(rl);
  1036. digestmap_free(rl->identity_map, NULL);
  1037. digestmap_free(rl->desc_digest_map, NULL);
  1038. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1039. routerinfo_free(r));
  1040. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  1041. signed_descriptor_free(sd));
  1042. smartlist_free(rl->routers);
  1043. smartlist_free(rl->old_routers);
  1044. tor_free(rl);
  1045. }
  1046. void
  1047. dump_routerlist_mem_usage(int severity)
  1048. {
  1049. uint64_t livedescs = 0;
  1050. uint64_t olddescs = 0;
  1051. if (!routerlist)
  1052. return;
  1053. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  1054. livedescs += r->cache_info.signed_descriptor_len);
  1055. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  1056. olddescs += sd->signed_descriptor_len);
  1057. log(severity, LD_GENERAL,
  1058. "In %d live descriptors: "U64_FORMAT" bytes. "
  1059. "In %d old descriptors: "U64_FORMAT" bytes.",
  1060. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  1061. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  1062. }
  1063. /** Return the greatest number of routerdescs we'll hold for any given router.
  1064. */
  1065. static int
  1066. max_descriptors_per_router(void)
  1067. {
  1068. int n_authorities = 0;
  1069. if (trusted_dir_servers)
  1070. n_authorities = smartlist_len(trusted_dir_servers);
  1071. return (n_authorities < 5) ? 5 : n_authorities;
  1072. }
  1073. /** Return non-zero if we have a lot of extra descriptors in our
  1074. * routerlist, and should get rid of some of them. Else return 0.
  1075. *
  1076. * We should be careful to not return true too eagerly, since we
  1077. * could churn. By using "+1" below, we make sure this function
  1078. * only returns true at most every smartlist_len(rl-\>routers)
  1079. * new descriptors.
  1080. */
  1081. static INLINE int
  1082. routerlist_is_overfull(routerlist_t *rl)
  1083. {
  1084. return smartlist_len(rl->old_routers) >
  1085. smartlist_len(rl->routers)*(max_descriptors_per_router()+1);
  1086. }
  1087. static INLINE int
  1088. _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
  1089. {
  1090. if (idx < 0 || smartlist_get(sl, idx) != ri) {
  1091. idx = -1;
  1092. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  1093. if (r == ri) {
  1094. idx = r_sl_idx;
  1095. break;
  1096. });
  1097. }
  1098. return idx;
  1099. }
  1100. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  1101. * as needed. */
  1102. static void
  1103. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  1104. {
  1105. digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  1106. digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
  1107. &(ri->cache_info));
  1108. smartlist_add(rl->routers, ri);
  1109. // routerlist_assert_ok(rl);
  1110. }
  1111. static void
  1112. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  1113. {
  1114. if (get_options()->DirPort &&
  1115. !digestmap_get(rl->desc_digest_map,
  1116. ri->cache_info.signed_descriptor_digest)) {
  1117. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  1118. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1119. smartlist_add(rl->old_routers, sd);
  1120. } else {
  1121. routerinfo_free(ri);
  1122. }
  1123. // routerlist_assert_ok(rl);
  1124. }
  1125. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  1126. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  1127. * idx) == ri, we don't need to do a linear search over the list to decide
  1128. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  1129. * the list, if any exists. <b>ri</b> is freed. */
  1130. void
  1131. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
  1132. {
  1133. routerinfo_t *ri_tmp;
  1134. idx = _routerlist_find_elt(rl->routers, ri, idx);
  1135. if (idx < 0)
  1136. return;
  1137. smartlist_del(rl->routers, idx);
  1138. ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
  1139. tor_assert(ri_tmp == ri);
  1140. if (make_old && get_options()->DirPort) {
  1141. signed_descriptor_t *sd;
  1142. sd = signed_descriptor_from_routerinfo(ri);
  1143. smartlist_add(rl->old_routers, sd);
  1144. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1145. } else {
  1146. ri_tmp = digestmap_remove(rl->desc_digest_map,
  1147. ri->cache_info.signed_descriptor_digest);
  1148. tor_assert(ri_tmp == ri);
  1149. router_bytes_dropped += ri->cache_info.signed_descriptor_len;
  1150. routerinfo_free(ri);
  1151. }
  1152. // routerlist_assert_ok(rl);
  1153. }
  1154. static void
  1155. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  1156. {
  1157. signed_descriptor_t *sd_tmp;
  1158. idx = _routerlist_find_elt(rl->old_routers, sd, idx);
  1159. if (idx < 0)
  1160. return;
  1161. smartlist_del(rl->old_routers, idx);
  1162. sd_tmp = digestmap_remove(rl->desc_digest_map,
  1163. sd->signed_descriptor_digest);
  1164. tor_assert(sd_tmp == sd);
  1165. router_bytes_dropped += sd->signed_descriptor_len;
  1166. signed_descriptor_free(sd);
  1167. // routerlist_assert_ok(rl);
  1168. }
  1169. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  1170. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  1171. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  1172. * search over the list to decide which to remove. We put ri_new in the same
  1173. * index as ri_old, if possible. ri is freed as appropriate. */
  1174. static void
  1175. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  1176. routerinfo_t *ri_new, int idx, int make_old)
  1177. {
  1178. tor_assert(ri_old != ri_new);
  1179. idx = _routerlist_find_elt(rl->routers, ri_old, idx);
  1180. if (idx >= 0) {
  1181. smartlist_set(rl->routers, idx, ri_new);
  1182. } else {
  1183. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  1184. routerlist_insert(rl, ri_new);
  1185. return;
  1186. }
  1187. if (memcmp(ri_old->cache_info.identity_digest,
  1188. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  1189. /* digests don't match; digestmap_set won't replace */
  1190. digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  1191. }
  1192. digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
  1193. digestmap_set(rl->desc_digest_map,
  1194. ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
  1195. if (make_old && get_options()->DirPort) {
  1196. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  1197. smartlist_add(rl->old_routers, sd);
  1198. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1199. } else {
  1200. if (memcmp(ri_old->cache_info.signed_descriptor_digest,
  1201. ri_new->cache_info.signed_descriptor_digest,
  1202. DIGEST_LEN)) {
  1203. /* digests don't match; digestmap_set didn't replace */
  1204. digestmap_remove(rl->desc_digest_map,
  1205. ri_old->cache_info.signed_descriptor_digest);
  1206. }
  1207. routerinfo_free(ri_old);
  1208. }
  1209. // routerlist_assert_ok(rl);
  1210. }
  1211. /** Free all memory held by the routerlist module. */
  1212. void
  1213. routerlist_free_all(void)
  1214. {
  1215. if (routerlist)
  1216. routerlist_free(routerlist);
  1217. routerlist = NULL;
  1218. if (warned_nicknames) {
  1219. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1220. smartlist_free(warned_nicknames);
  1221. warned_nicknames = NULL;
  1222. }
  1223. if (warned_conflicts) {
  1224. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1225. smartlist_free(warned_conflicts);
  1226. warned_conflicts = NULL;
  1227. }
  1228. if (trusted_dir_servers) {
  1229. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1230. trusted_dir_server_free(ds));
  1231. smartlist_free(trusted_dir_servers);
  1232. trusted_dir_servers = NULL;
  1233. }
  1234. if (networkstatus_list) {
  1235. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1236. networkstatus_free(ns));
  1237. smartlist_free(networkstatus_list);
  1238. networkstatus_list = NULL;
  1239. }
  1240. if (routerstatus_list) {
  1241. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1242. local_routerstatus_free(rs));
  1243. smartlist_free(routerstatus_list);
  1244. routerstatus_list = NULL;
  1245. }
  1246. }
  1247. /** Free all storage held by the routerstatus object <b>rs</b>. */
  1248. void
  1249. routerstatus_free(routerstatus_t *rs)
  1250. {
  1251. tor_free(rs);
  1252. }
  1253. /** Free all storage held by the local_routerstatus object <b>rs</b>. */
  1254. static void
  1255. local_routerstatus_free(local_routerstatus_t *rs)
  1256. {
  1257. tor_free(rs);
  1258. }
  1259. /** Free all storage held by the networkstatus object <b>ns</b>. */
  1260. void
  1261. networkstatus_free(networkstatus_t *ns)
  1262. {
  1263. tor_free(ns->source_address);
  1264. tor_free(ns->contact);
  1265. if (ns->signing_key)
  1266. crypto_free_pk_env(ns->signing_key);
  1267. tor_free(ns->client_versions);
  1268. tor_free(ns->server_versions);
  1269. if (ns->entries) {
  1270. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1271. routerstatus_free(rs));
  1272. smartlist_free(ns->entries);
  1273. }
  1274. tor_free(ns);
  1275. }
  1276. /** Forget that we have issued any router-related warnings, so that we'll
  1277. * warn again if we see the same errors. */
  1278. void
  1279. routerlist_reset_warnings(void)
  1280. {
  1281. if (!warned_nicknames)
  1282. warned_nicknames = smartlist_create();
  1283. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1284. smartlist_clear(warned_nicknames); /* now the list is empty. */
  1285. if (!warned_conflicts)
  1286. warned_conflicts = smartlist_create();
  1287. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1288. smartlist_clear(warned_conflicts); /* now the list is empty. */
  1289. if (!routerstatus_list)
  1290. routerstatus_list = smartlist_create();
  1291. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1292. rs->name_lookup_warned = 0);
  1293. have_warned_about_invalid_status = 0;
  1294. have_warned_about_old_version = 0;
  1295. have_warned_about_new_version = 0;
  1296. }
  1297. /** Mark the router with ID <b>digest</b> as running or non-running
  1298. * in our routerlist. */
  1299. void
  1300. router_set_status(const char *digest, int up)
  1301. {
  1302. routerinfo_t *router;
  1303. local_routerstatus_t *status;
  1304. tor_assert(digest);
  1305. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  1306. if (!memcmp(d->digest, digest, DIGEST_LEN))
  1307. d->is_running = up);
  1308. router = router_get_by_digest(digest);
  1309. if (router) {
  1310. log_debug(LD_DIR,"Marking router '%s' as %s.",
  1311. router->nickname, up ? "up" : "down");
  1312. if (!up && router_is_me(router) && !we_are_hibernating())
  1313. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  1314. "addresses reachable?");
  1315. router->is_running = up;
  1316. }
  1317. status = router_get_combined_status_by_digest(digest);
  1318. if (status) {
  1319. status->status.is_running = up;
  1320. }
  1321. }
  1322. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  1323. * older entries (if any) with the same key. Note: Callers should not hold
  1324. * their pointers to <b>router</b> if this function fails; <b>router</b>
  1325. * will either be inserted into the routerlist or freed.
  1326. *
  1327. * Returns >= 0 if the router was added; less than 0 if it was not.
  1328. *
  1329. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  1330. * describing the reason for not liking the routerinfo.
  1331. *
  1332. * If the return value is less than -1, there was a problem with the
  1333. * routerinfo. If the return value is equal to -1, then the routerinfo was
  1334. * fine, but out-of-date. If the return value is equal to 1, the
  1335. * routerinfo was accepted, but we should notify the generator of the
  1336. * descriptor using the message *<b>msg</b>.
  1337. *
  1338. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  1339. * <b>from_fetch</b>, we received it in response to a request we made.
  1340. * (If both are false, that means it was uploaded to us as an auth dir
  1341. * server or via the controller.)
  1342. *
  1343. * This function should be called *after*
  1344. * routers_update_status_from_networkstatus; subsequently, you should call
  1345. * router_rebuild_store and control_event_descriptors_changed.
  1346. */
  1347. int
  1348. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  1349. int from_cache, int from_fetch)
  1350. {
  1351. int i;
  1352. const char *id_digest;
  1353. int authdir = get_options()->AuthoritativeDir;
  1354. int authdir_believes_valid = 0;
  1355. tor_assert(msg);
  1356. if (!routerlist)
  1357. router_get_routerlist();
  1358. if (!networkstatus_list)
  1359. networkstatus_list = smartlist_create();
  1360. id_digest = router->cache_info.identity_digest;
  1361. /* Make sure that we haven't already got this exact descriptor. */
  1362. if (digestmap_get(routerlist->desc_digest_map,
  1363. router->cache_info.signed_descriptor_digest)) {
  1364. log_info(LD_DIR,
  1365. "Dropping descriptor that we already have for router '%s'",
  1366. router->nickname);
  1367. *msg = "Router descriptor was not new.";
  1368. routerinfo_free(router);
  1369. return -1;
  1370. }
  1371. if (routerlist_is_overfull(routerlist))
  1372. routerlist_remove_old_routers();
  1373. if (authdir) {
  1374. if (authdir_wants_to_reject_router(router, msg,
  1375. !from_cache && !from_fetch)) {
  1376. tor_assert(*msg);
  1377. routerinfo_free(router);
  1378. return -2;
  1379. }
  1380. authdir_believes_valid = router->is_valid;
  1381. } else if (from_fetch) {
  1382. /* Only check the descriptor digest against the network statuses when
  1383. * we are receiving in response to a fetch. */
  1384. if (!signed_desc_digest_is_recognized(&router->cache_info)) {
  1385. log_warn(LD_DIR, "Dropping unrecognized descriptor for router '%s'",
  1386. router->nickname);
  1387. *msg = "Router descriptor is not referenced by any network-status.";
  1388. routerinfo_free(router);
  1389. return -1;
  1390. }
  1391. }
  1392. /* We no longer need a router with this descriptor digest. */
  1393. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1394. {
  1395. routerstatus_t *rs =
  1396. networkstatus_find_entry(ns, router->cache_info.identity_digest);
  1397. if (rs && !memcmp(rs->descriptor_digest,
  1398. router->cache_info.signed_descriptor_digest,
  1399. DIGEST_LEN))
  1400. rs->need_to_mirror = 0;
  1401. });
  1402. /* If we have a router with this name, and the identity key is the same,
  1403. * choose the newer one. If the identity key has changed, and one of the
  1404. * routers is named, drop the unnamed ones. (If more than one are named,
  1405. * drop the old ones.)
  1406. */
  1407. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1408. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  1409. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  1410. if (router->cache_info.published_on <=
  1411. old_router->cache_info.published_on) {
  1412. /* Same key, but old */
  1413. log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
  1414. router->nickname);
  1415. /* Only journal this desc if we'll be serving it. */
  1416. if (!from_cache && get_options()->DirPort)
  1417. router_append_to_journal(&router->cache_info);
  1418. routerlist_insert_old(routerlist, router);
  1419. *msg = "Router descriptor was not new.";
  1420. return -1;
  1421. } else {
  1422. /* Same key, new. */
  1423. int unreachable = 0;
  1424. log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
  1425. router->nickname, old_router->nickname,
  1426. hex_str(id_digest,DIGEST_LEN));
  1427. if (router->addr == old_router->addr &&
  1428. router->or_port == old_router->or_port) {
  1429. /* these carry over when the address and orport are unchanged.*/
  1430. router->last_reachable = old_router->last_reachable;
  1431. router->testing_since = old_router->testing_since;
  1432. router->num_unreachable_notifications =
  1433. old_router->num_unreachable_notifications;
  1434. }
  1435. if (authdir && !from_cache && !from_fetch &&
  1436. router_have_minimum_dir_info() &&
  1437. dirserv_thinks_router_is_blatantly_unreachable(router,
  1438. time(NULL))) {
  1439. if (router->num_unreachable_notifications >= 3) {
  1440. unreachable = 1;
  1441. log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
  1442. "(ContactInfo '%s', platform '%s').",
  1443. router->nickname,
  1444. router->contact_info ? router->contact_info : "",
  1445. router->platform ? router->platform : "");
  1446. } else {
  1447. log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
  1448. "descriptors were thought to be unreachable.",
  1449. router->nickname, router->num_unreachable_notifications);
  1450. router->num_unreachable_notifications++;
  1451. }
  1452. }
  1453. routerlist_replace(routerlist, old_router, router, i, 1);
  1454. if (!from_cache) {
  1455. router_append_to_journal(&router->cache_info);
  1456. }
  1457. directory_set_dirty();
  1458. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1459. authdir_believes_valid ? "Valid server updated" :
  1460. ("Invalid server updated. (This dirserver is marking your "
  1461. "server as unapproved.)");
  1462. return unreachable ? 1 : 0;
  1463. }
  1464. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1465. /* nicknames match, keys don't. */
  1466. if (router->is_named) {
  1467. /* The new named router replaces the old one; remove the
  1468. * old one. And carry on to the end of the list, in case
  1469. * there are more old unnamed routers with this nickname.
  1470. */
  1471. /* mark-for-close connections using the old key, so we can
  1472. * make new ones with the new key.
  1473. */
  1474. connection_t *conn;
  1475. while ((conn = connection_or_get_by_identity_digest(
  1476. old_router->cache_info.identity_digest))) {
  1477. log_info(LD_DIR,"Closing conn to router '%s'; there is now a named "
  1478. "router with that name.",
  1479. old_router->nickname);
  1480. connection_mark_for_close(conn);
  1481. }
  1482. routerlist_remove(routerlist, old_router, i--, 0);
  1483. } else if (old_router->is_named) {
  1484. /* Can't replace a named router with an unnamed one. */
  1485. log_debug(LD_DIR, "Skipping unnamed entry for named router '%s'",
  1486. router->nickname);
  1487. routerinfo_free(router);
  1488. *msg =
  1489. "Already have named router with same nickname and different key.";
  1490. return -2;
  1491. }
  1492. }
  1493. }
  1494. /* We haven't seen a router with this name before. Add it to the end of
  1495. * the list. */
  1496. routerlist_insert(routerlist, router);
  1497. if (!from_cache)
  1498. router_append_to_journal(&router->cache_info);
  1499. directory_set_dirty();
  1500. return 0;
  1501. }
  1502. static int
  1503. _compare_old_routers_by_identity(const void **_a, const void **_b)
  1504. {
  1505. int i;
  1506. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  1507. if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  1508. return i;
  1509. return r1->published_on - r2->published_on;
  1510. }
  1511. struct duration_idx_t {
  1512. int duration;
  1513. int idx;
  1514. int old;
  1515. };
  1516. static int
  1517. _compare_duration_idx(const void *_d1, const void *_d2)
  1518. {
  1519. const struct duration_idx_t *d1 = _d1;
  1520. const struct duration_idx_t *d2 = _d2;
  1521. return d1->duration - d2->duration;
  1522. }
  1523. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  1524. * must contain routerinfo_t with the same identity and with publication time
  1525. * in ascending order. Remove members from this range until there are no more
  1526. * than max_descriptors_per_router() remaining. Start by removing the oldest
  1527. * members from before <b>cutoff</b>, then remove members which were current
  1528. * for the lowest amount of time. The order of members of old_routers at
  1529. * indices <b>lo</b> or higher may be changed.
  1530. */
  1531. static void
  1532. routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
  1533. digestmap_t *retain)
  1534. {
  1535. int i, n = hi-lo+1, n_extra;
  1536. int n_rmv = 0;
  1537. struct duration_idx_t *lifespans;
  1538. uint8_t *rmv, *must_keep;
  1539. smartlist_t *lst = routerlist->old_routers;
  1540. #if 1
  1541. const char *ident;
  1542. tor_assert(hi < smartlist_len(lst));
  1543. tor_assert(lo <= hi);
  1544. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  1545. for (i = lo+1; i <= hi; ++i) {
  1546. signed_descriptor_t *r = smartlist_get(lst, i);
  1547. tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
  1548. }
  1549. #endif
  1550. /* Check whether we need to do anything at all. */
  1551. n_extra = n - max_descriptors_per_router();
  1552. if (n_extra <= 0)
  1553. return;
  1554. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  1555. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  1556. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  1557. /* Set lifespans to contain the lifespan and index of each server. */
  1558. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  1559. for (i = lo; i <= hi; ++i) {
  1560. signed_descriptor_t *r = smartlist_get(lst, i);
  1561. signed_descriptor_t *r_next;
  1562. lifespans[i-lo].idx = i;
  1563. if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
  1564. must_keep[i-lo] = 1;
  1565. }
  1566. if (i < hi) {
  1567. r_next = smartlist_get(lst, i+1);
  1568. tor_assert(r->published_on <= r_next->published_on);
  1569. lifespans[i-lo].duration = (r_next->published_on - r->published_on);
  1570. } else {
  1571. r_next = NULL;
  1572. lifespans[i-lo].duration = INT_MAX;
  1573. }
  1574. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  1575. ++n_rmv;
  1576. lifespans[i-lo].old = 1;
  1577. rmv[i-lo] = 1;
  1578. }
  1579. }
  1580. if (n_rmv < n_extra) {
  1581. /**
  1582. * We aren't removing enough servers for being old. Sort lifespans by
  1583. * the duration of liveness, and remove the ones we're not already going to
  1584. * remove based on how long they were alive.
  1585. **/
  1586. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  1587. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  1588. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  1589. rmv[lifespans[i].idx-lo] = 1;
  1590. ++n_rmv;
  1591. }
  1592. }
  1593. }
  1594. for (i = hi; i >= lo; --i) {
  1595. if (rmv[i-lo])
  1596. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  1597. }
  1598. tor_free(must_keep);
  1599. tor_free(rmv);
  1600. tor_free(lifespans);
  1601. }
  1602. /** Deactivate any routers from the routerlist that are more than
  1603. * ROUTER_MAX_AGE seconds old; remove old routers from the list of
  1604. * cached routers if we have too many.
  1605. */
  1606. void
  1607. routerlist_remove_old_routers(void)
  1608. {
  1609. int i, hi=-1;
  1610. const char *cur_id = NULL;
  1611. time_t now = time(NULL);
  1612. time_t cutoff;
  1613. routerinfo_t *router;
  1614. signed_descriptor_t *sd;
  1615. digestmap_t *retain;
  1616. or_options_t *options = get_options();
  1617. if (!routerlist || !networkstatus_list)
  1618. return;
  1619. retain = digestmap_new();
  1620. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1621. if (server_mode(options) && options->DirPort) {
  1622. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1623. {
  1624. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1625. if (rs->published_on >= cutoff)
  1626. digestmap_set(retain, rs->descriptor_digest, (void*)1));
  1627. });
  1628. }
  1629. cutoff = now - ROUTER_MAX_AGE;
  1630. /* Remove too-old members of routerlist->routers. */
  1631. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1632. router = smartlist_get(routerlist->routers, i);
  1633. if (router->cache_info.published_on <= cutoff &&
  1634. !digestmap_get(retain, router->cache_info.signed_descriptor_digest)) {
  1635. /* Too old. Remove it. */
  1636. log_info(LD_DIR,
  1637. "Forgetting obsolete (too old) routerinfo for router '%s'",
  1638. router->nickname);
  1639. routerlist_remove(routerlist, router, i--, 1);
  1640. }
  1641. }
  1642. /* Remove far-too-old members of routerlist->old_routers. */
  1643. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1644. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  1645. sd = smartlist_get(routerlist->old_routers, i);
  1646. if (sd->published_on <= cutoff &&
  1647. !digestmap_get(retain, sd->signed_descriptor_digest)) {
  1648. /* Too old. Remove it. */
  1649. routerlist_remove_old(routerlist, sd, i--);
  1650. }
  1651. }
  1652. /* Now we're looking at routerlist->old_routers for extraneous
  1653. * members. (We'd keep all the members if we could, but we'd like to save
  1654. * space.) First, check whether we have too many router descriptors, total.
  1655. * We're okay with having too many for some given router, so long as the
  1656. * total number doesn't approach max_descriptors_per_router()*len(router).
  1657. */
  1658. if (smartlist_len(routerlist->old_routers) <
  1659. smartlist_len(routerlist->routers) * (max_descriptors_per_router() - 1))
  1660. goto done;
  1661. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  1662. /* Iterate through the list from back to front, so when we remove descriptors
  1663. * we don't mess up groups we haven't gotten to. */
  1664. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  1665. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  1666. if (!cur_id) {
  1667. cur_id = r->identity_digest;
  1668. hi = i;
  1669. }
  1670. if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
  1671. routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
  1672. cur_id = r->identity_digest;
  1673. hi = i;
  1674. }
  1675. }
  1676. if (hi>=0)
  1677. routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
  1678. routerlist_assert_ok(routerlist);
  1679. done:
  1680. digestmap_free(retain, NULL);
  1681. }
  1682. /**
  1683. * Code to parse a single router descriptor and insert it into the
  1684. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1685. * descriptor was well-formed but could not be added; and 1 if the
  1686. * descriptor was added.
  1687. *
  1688. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1689. * *<b>msg</b> a static string describing the reason for refusing the
  1690. * descriptor.
  1691. *
  1692. * This is used only by the controller.
  1693. */
  1694. int
  1695. router_load_single_router(const char *s, uint8_t purpose, const char **msg)
  1696. {
  1697. routerinfo_t *ri;
  1698. int r;
  1699. smartlist_t *lst;
  1700. tor_assert(msg);
  1701. *msg = NULL;
  1702. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  1703. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  1704. *msg = "Couldn't parse router descriptor.";
  1705. return -1;
  1706. }
  1707. ri->purpose = purpose;
  1708. if (router_is_me(ri)) {
  1709. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  1710. *msg = "Router's identity key matches mine.";
  1711. routerinfo_free(ri);
  1712. return 0;
  1713. }
  1714. lst = smartlist_create();
  1715. smartlist_add(lst, ri);
  1716. routers_update_status_from_networkstatus(lst, 0);
  1717. if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
  1718. /* we've already assigned to *msg now, and ri is already freed */
  1719. tor_assert(*msg);
  1720. if (r < -1)
  1721. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  1722. smartlist_free(lst);
  1723. return 0;
  1724. } else {
  1725. control_event_descriptors_changed(lst);
  1726. smartlist_free(lst);
  1727. log_debug(LD_DIR, "Added router to list");
  1728. return 1;
  1729. }
  1730. }
  1731. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1732. * routers into our directory. If <b>from_cache</b> is false, the routers
  1733. * are in response to a query to the network: cache them.
  1734. *
  1735. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1736. * uppercased identity fingerprints. Do not update any router whose
  1737. * fingerprint is not on the list; after updating a router, remove its
  1738. * fingerprint from the list.
  1739. */
  1740. void
  1741. router_load_routers_from_string(const char *s, int from_cache,
  1742. smartlist_t *requested_fingerprints)
  1743. {
  1744. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1745. char fp[HEX_DIGEST_LEN+1];
  1746. const char *msg;
  1747. router_parse_list_from_string(&s, routers);
  1748. routers_update_status_from_networkstatus(routers, !from_cache);
  1749. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  1750. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1751. {
  1752. base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
  1753. DIGEST_LEN);
  1754. if (requested_fingerprints) {
  1755. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1756. smartlist_string_remove(requested_fingerprints, fp);
  1757. } else {
  1758. char *requested =
  1759. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1760. log_warn(LD_DIR,
  1761. "We received a router descriptor with a fingerprint (%s) "
  1762. "that we never requested. (We asked for: %s.) Dropping.",
  1763. fp, requested);
  1764. tor_free(requested);
  1765. routerinfo_free(ri);
  1766. continue;
  1767. }
  1768. }
  1769. if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
  1770. smartlist_add(changed, ri);
  1771. });
  1772. if (smartlist_len(changed))
  1773. control_event_descriptors_changed(changed);
  1774. routerlist_assert_ok(routerlist);
  1775. router_rebuild_store(0);
  1776. smartlist_free(routers);
  1777. smartlist_free(changed);
  1778. }
  1779. /** Helper: return a newly allocated string containing the name of the filename
  1780. * where we plan to cache <b>ns</b>. */
  1781. static char *
  1782. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1783. {
  1784. const char *datadir = get_options()->DataDirectory;
  1785. size_t len = strlen(datadir)+64;
  1786. char fp[HEX_DIGEST_LEN+1];
  1787. char *fn = tor_malloc(len+1);
  1788. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1789. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1790. return fn;
  1791. }
  1792. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1793. * publication date. */
  1794. static int
  1795. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1796. {
  1797. const networkstatus_t *a = *_a, *b = *_b;
  1798. if (a->published_on < b->published_on)
  1799. return -1;
  1800. else if (a->published_on > b->published_on)
  1801. return 1;
  1802. else
  1803. return 0;
  1804. }
  1805. /** Add the parsed neworkstatus in <b>ns</b> (with original document in
  1806. * <b>s</b> to the disk cache (and the in-memory directory server cache) as
  1807. * appropriate. */
  1808. static int
  1809. add_networkstatus_to_cache(const char *s,
  1810. networkstatus_source_t source,
  1811. networkstatus_t *ns)
  1812. {
  1813. if (source != NS_FROM_CACHE) {
  1814. char *fn = networkstatus_get_cache_filename(ns);
  1815. if (write_str_to_file(fn, s, 0)<0) {
  1816. log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
  1817. }
  1818. tor_free(fn);
  1819. }
  1820. if (get_options()->DirPort)
  1821. dirserv_set_cached_networkstatus_v2(s,
  1822. ns->identity_digest,
  1823. ns->published_on);
  1824. return 0;
  1825. }
  1826. /** How far in the future do we allow a network-status to get before removing
  1827. * it? (seconds) */
  1828. #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
  1829. /** Given a string <b>s</b> containing a network status that we received at
  1830. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1831. * store it, and put it into our cache as necessary.
  1832. *
  1833. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1834. * own networkstatus_t (if we're a directory server).
  1835. *
  1836. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1837. * cache.
  1838. *
  1839. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1840. * uppercased identity fingerprints. Do not update any networkstatus whose
  1841. * fingerprint is not on the list; after updating a networkstatus, remove its
  1842. * fingerprint from the list.
  1843. *
  1844. * Return 0 on success, -1 on failure.
  1845. *
  1846. * Callers should make sure that routers_update_all_from_networkstatus() is
  1847. * invoked after this function succeeds.
  1848. */
  1849. int
  1850. router_set_networkstatus(const char *s, time_t arrived_at,
  1851. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1852. {
  1853. networkstatus_t *ns;
  1854. int i, found;
  1855. time_t now;
  1856. int skewed = 0;
  1857. trusted_dir_server_t *trusted_dir = NULL;
  1858. const char *source_desc = NULL;
  1859. char fp[HEX_DIGEST_LEN+1];
  1860. char published[ISO_TIME_LEN+1];
  1861. ns = networkstatus_parse_from_string(s);
  1862. if (!ns) {
  1863. log_warn(LD_DIR, "Couldn't parse network status.");
  1864. return -1;
  1865. }
  1866. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1867. if (!(trusted_dir =
  1868. router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  1869. log_info(LD_DIR, "Network status was signed, but not by an authoritative "
  1870. "directory we recognize.");
  1871. if (!get_options()->DirPort) {
  1872. networkstatus_free(ns);
  1873. return 0;
  1874. }
  1875. source_desc = fp;
  1876. } else {
  1877. source_desc = trusted_dir->description;
  1878. }
  1879. now = time(NULL);
  1880. if (arrived_at > now)
  1881. arrived_at = now;
  1882. ns->received_on = arrived_at;
  1883. format_iso_time(published, ns->published_on);
  1884. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1885. log_warn(LD_GENERAL, "Network status from %s was published in the future "
  1886. "(%s GMT). Somebody is skewed here: check your clock. "
  1887. "Not caching.",
  1888. source_desc, published);
  1889. skewed = 1;
  1890. }
  1891. if (!networkstatus_list)
  1892. networkstatus_list = smartlist_create();
  1893. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1894. /* Don't replace our own networkstatus when we get it from somebody else.*/
  1895. networkstatus_free(ns);
  1896. return 0;
  1897. }
  1898. if (requested_fingerprints) {
  1899. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1900. smartlist_string_remove(requested_fingerprints, fp);
  1901. } else {
  1902. char *requested =
  1903. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1904. log_warn(LD_DIR,
  1905. "We received a network status with a fingerprint (%s) that we "
  1906. "never requested. (We asked for: %s.) Dropping.",
  1907. fp, requested);
  1908. tor_free(requested);
  1909. return 0;
  1910. }
  1911. }
  1912. if (!trusted_dir) {
  1913. if (!skewed && get_options()->DirPort) {
  1914. /* We got a non-trusted networkstatus, and we're a directory cache.
  1915. * This means that we asked an authority, and it told us about another
  1916. * authority we didn't recognize. */
  1917. add_networkstatus_to_cache(s, source, ns);
  1918. networkstatus_free(ns);
  1919. }
  1920. return 0;
  1921. }
  1922. if (source != NS_FROM_CACHE && trusted_dir)
  1923. trusted_dir->n_networkstatus_failures = 0;
  1924. found = 0;
  1925. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  1926. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  1927. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  1928. if (!memcmp(old_ns->networkstatus_digest,
  1929. ns->networkstatus_digest, DIGEST_LEN)) {
  1930. /* Same one we had before. */
  1931. networkstatus_free(ns);
  1932. log_info(LD_DIR,
  1933. "Not replacing network-status from %s (published %s); "
  1934. "we already have it.",
  1935. trusted_dir->description, published);
  1936. if (old_ns->received_on < arrived_at) {
  1937. if (source != NS_FROM_CACHE) {
  1938. char *fn = networkstatus_get_cache_filename(old_ns);
  1939. /* We use mtime to tell when it arrived, so update that. */
  1940. touch_file(fn);
  1941. tor_free(fn);
  1942. }
  1943. old_ns->received_on = arrived_at;
  1944. }
  1945. return 0;
  1946. } else if (old_ns->published_on >= ns->published_on) {
  1947. char old_published[ISO_TIME_LEN+1];
  1948. format_iso_time(old_published, old_ns->published_on);
  1949. log_info(LD_DIR,
  1950. "Not replacing network-status from %s (published %s);"
  1951. " we have a newer one (published %s) for this authority.",
  1952. trusted_dir->description, published,
  1953. old_published);
  1954. networkstatus_free(ns);
  1955. return 0;
  1956. } else {
  1957. networkstatus_free(old_ns);
  1958. smartlist_set(networkstatus_list, i, ns);
  1959. found = 1;
  1960. break;
  1961. }
  1962. }
  1963. }
  1964. if (!found)
  1965. smartlist_add(networkstatus_list, ns);
  1966. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1967. {
  1968. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  1969. rs->need_to_mirror = 1;
  1970. });
  1971. log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
  1972. source == NS_FROM_CACHE?"cached from":
  1973. (source==NS_FROM_DIR?"downloaded from":"generated for"),
  1974. trusted_dir->description, published);
  1975. networkstatus_list_has_changed = 1;
  1976. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  1977. if (!skewed)
  1978. add_networkstatus_to_cache(s, source, ns);
  1979. networkstatus_list_update_recent(now);
  1980. return 0;
  1981. }
  1982. /** How old do we allow a network-status to get before removing it
  1983. * completely? */
  1984. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  1985. /** Remove all very-old network_status_t objects from memory and from the
  1986. * disk cache. */
  1987. void
  1988. networkstatus_list_clean(time_t now)
  1989. {
  1990. int i;
  1991. if (!networkstatus_list)
  1992. return;
  1993. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  1994. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  1995. char *fname = NULL;;
  1996. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  1997. continue;
  1998. /* Okay, this one is too old. Remove it from the list, and delete it
  1999. * from the cache. */
  2000. smartlist_del(networkstatus_list, i--);
  2001. fname = networkstatus_get_cache_filename(ns);
  2002. if (file_status(fname) == FN_FILE) {
  2003. log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
  2004. unlink(fname);
  2005. }
  2006. tor_free(fname);
  2007. if (get_options()->DirPort) {
  2008. dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
  2009. }
  2010. networkstatus_free(ns);
  2011. }
  2012. }
  2013. /** Helper for bsearching a list of routerstatus_t pointers.*/
  2014. static int
  2015. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  2016. {
  2017. const char *key = _key;
  2018. const routerstatus_t *rs = *_member;
  2019. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  2020. }
  2021. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  2022. * NULL if none was found. */
  2023. static routerstatus_t *
  2024. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  2025. {
  2026. return smartlist_bsearch(ns->entries, digest,
  2027. _compare_digest_to_routerstatus_entry);
  2028. }
  2029. /** Return the consensus view of the status of the router whose digest is
  2030. * <b>digest</b>, or NULL if we don't know about any such router. */
  2031. local_routerstatus_t *
  2032. router_get_combined_status_by_digest(const char *digest)
  2033. {
  2034. if (!routerstatus_list)
  2035. return NULL;
  2036. return smartlist_bsearch(routerstatus_list, digest,
  2037. _compare_digest_to_routerstatus_entry);
  2038. }
  2039. /** Return true iff any networkstatus includes a descriptor whose digest
  2040. * is that of <b>desc</b>. */
  2041. static int
  2042. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  2043. {
  2044. routerstatus_t *rs;
  2045. if (!networkstatus_list)
  2046. return 0;
  2047. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2048. {
  2049. if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
  2050. continue;
  2051. if (!memcmp(rs->descriptor_digest,
  2052. desc->signed_descriptor_digest, DIGEST_LEN))
  2053. return 1;
  2054. });
  2055. return 0;
  2056. }
  2057. /** How frequently do directory authorities re-download fresh networkstatus
  2058. * documents? */
  2059. #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
  2060. /** How frequently do non-authority directory caches re-download fresh
  2061. * networkstatus documents? */
  2062. #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
  2063. /** We are a directory server, and so cache network_status documents.
  2064. * Initiate downloads as needed to update them. For authorities, this means
  2065. * asking each trusted directory for its network-status. For caches, this
  2066. * means asking a random authority for all network-statuses.
  2067. */
  2068. static void
  2069. update_networkstatus_cache_downloads(time_t now)
  2070. {
  2071. int authority = authdir_mode(get_options());
  2072. int interval =
  2073. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  2074. if (last_networkstatus_download_attempted + interval >= now)
  2075. return;
  2076. if (!trusted_dir_servers)
  2077. return;
  2078. last_networkstatus_download_attempted = now;
  2079. if (authority) {
  2080. /* An authority launches a separate connection for everybody. */
  2081. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2082. {
  2083. char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
  2084. if (router_digest_is_me(ds->digest))
  2085. continue;
  2086. if (connection_get_by_type_addr_port_purpose(
  2087. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  2088. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  2089. /* We are already fetching this one. */
  2090. continue;
  2091. }
  2092. strlcpy(resource, "fp/", sizeof(resource));
  2093. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  2094. strlcat(resource, ".z", sizeof(resource));
  2095. directory_initiate_command_routerstatus(
  2096. &ds->fake_status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
  2097. 0, /* Not private */
  2098. resource,
  2099. NULL, 0 /* No payload. */);
  2100. });
  2101. } else {
  2102. /* A non-authority cache launches one connection to a random authority. */
  2103. /* (Check whether we're currently fetching network-status objects.) */
  2104. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  2105. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2106. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  2107. }
  2108. }
  2109. /** How long (in seconds) does a client wait after getting a network status
  2110. * before downloading the next in sequence? */
  2111. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  2112. /* How many times do we allow a networkstatus download to fail before we
  2113. * assume that the authority isn't publishing? */
  2114. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  2115. /** We are not a directory cache or authority. Update our network-status list
  2116. * by launching a new directory fetch for enough network-status documents "as
  2117. * necessary". See function comments for implementation details.
  2118. */
  2119. static void
  2120. update_networkstatus_client_downloads(time_t now)
  2121. {
  2122. int n_live = 0, n_dirservers, n_running_dirservers, needed = 0;
  2123. int fetch_latest = 0;
  2124. int most_recent_idx = -1;
  2125. trusted_dir_server_t *most_recent = NULL;
  2126. time_t most_recent_received = 0;
  2127. char *resource, *cp;
  2128. size_t resource_len;
  2129. smartlist_t *missing;
  2130. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  2131. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2132. return;
  2133. /* This is a little tricky. We want to download enough network-status
  2134. * objects so that we have all of them under
  2135. * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
  2136. * *one* if the most recent one's publication time is under
  2137. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  2138. */
  2139. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  2140. return;
  2141. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  2142. missing = smartlist_create();
  2143. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2144. {
  2145. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  2146. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2147. --n_running_dirservers;
  2148. continue;
  2149. }
  2150. if (ns && ns->published_on > now-NETWORKSTATUS_MAX_AGE)
  2151. ++n_live;
  2152. else
  2153. smartlist_add(missing, ds->digest);
  2154. if (ns && (!most_recent || ns->received_on > most_recent_received)) {
  2155. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  2156. most_recent = ds;
  2157. most_recent_received = ns->received_on;
  2158. }
  2159. });
  2160. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  2161. if (!smartlist_len(missing) &&
  2162. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL) {
  2163. log_info(LD_DIR, "Our most recent network-status document (from %s) "
  2164. "is %d seconds old; downloading another.",
  2165. most_recent?most_recent->description:"nobody",
  2166. (int)(now-most_recent_received));
  2167. fetch_latest = 1;
  2168. needed = 1;
  2169. } else if (smartlist_len(missing)) {
  2170. log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
  2171. " network-status documents. Downloading %d.",
  2172. n_running_dirservers, n_dirservers, n_live,
  2173. smartlist_len(missing));
  2174. needed = smartlist_len(missing);
  2175. } else {
  2176. smartlist_free(missing);
  2177. return;
  2178. }
  2179. /* If no networkstatus was found, choose a dirserver at random as "most
  2180. * recent". */
  2181. if (most_recent_idx<0)
  2182. most_recent_idx = crypto_rand_int(n_dirservers);
  2183. if (fetch_latest) {
  2184. int i;
  2185. int n_failed = 0;
  2186. for (i = most_recent_idx + 1; 1; ++i) {
  2187. trusted_dir_server_t *ds;
  2188. if (i >= n_dirservers)
  2189. i = 0;
  2190. ds = smartlist_get(trusted_dir_servers, i);
  2191. if (n_failed < n_dirservers &&
  2192. ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2193. ++n_failed;
  2194. continue;
  2195. }
  2196. smartlist_add(missing, ds->digest);
  2197. break;
  2198. }
  2199. }
  2200. /* Build a request string for all the resources we want. */
  2201. resource_len = smartlist_len(missing) * (HEX_DIGEST_LEN+1) + 6;
  2202. resource = tor_malloc(resource_len);
  2203. memcpy(resource, "fp/", 3);
  2204. cp = resource+3;
  2205. needed = smartlist_len(missing);
  2206. SMARTLIST_FOREACH(missing, const char *, d,
  2207. {
  2208. base16_encode(cp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  2209. cp += HEX_DIGEST_LEN;
  2210. --needed;
  2211. if (needed)
  2212. *cp++ = '+';
  2213. });
  2214. memcpy(cp, ".z", 3);
  2215. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  2216. tor_free(resource);
  2217. smartlist_free(missing);
  2218. }
  2219. /** Launch requests for networkstatus documents as appropriate. */
  2220. void
  2221. update_networkstatus_downloads(time_t now)
  2222. {
  2223. or_options_t *options = get_options();
  2224. if (server_mode(options) && options->DirPort)
  2225. update_networkstatus_cache_downloads(time(NULL));
  2226. else
  2227. update_networkstatus_client_downloads(time(NULL));
  2228. }
  2229. /** Return 1 if all running sufficiently-stable routers will reject
  2230. * addr:port, return 0 if any might accept it. */
  2231. int
  2232. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  2233. int need_uptime)
  2234. {
  2235. addr_policy_result_t r;
  2236. if (!routerlist) return 1;
  2237. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  2238. {
  2239. if (router->is_running &&
  2240. !router_is_unreliable(router, need_uptime, 0, 0)) {
  2241. r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
  2242. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2243. return 0; /* this one could be ok. good enough. */
  2244. }
  2245. });
  2246. return 1; /* all will reject. */
  2247. }
  2248. /** Return true iff <b>router</b> does not permit exit streams.
  2249. */
  2250. int
  2251. router_exit_policy_rejects_all(routerinfo_t *router)
  2252. {
  2253. return compare_addr_to_addr_policy(0, 0, router->exit_policy)
  2254. == ADDR_POLICY_REJECTED;
  2255. }
  2256. /** Add to the list of authorized directory servers one at
  2257. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  2258. * <b>address</b> is NULL, add ourself. */
  2259. void
  2260. add_trusted_dir_server(const char *nickname, const char *address,
  2261. uint16_t port, const char *digest, int is_v1_authority)
  2262. {
  2263. trusted_dir_server_t *ent;
  2264. uint32_t a;
  2265. char *hostname = NULL;
  2266. size_t dlen;
  2267. if (!trusted_dir_servers)
  2268. trusted_dir_servers = smartlist_create();
  2269. if (!address) { /* The address is us; we should guess. */
  2270. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  2271. log_warn(LD_CONFIG,
  2272. "Couldn't find a suitable address when adding ourself as a "
  2273. "trusted directory server.");
  2274. return;
  2275. }
  2276. } else {
  2277. if (tor_lookup_hostname(address, &a)) {
  2278. log_warn(LD_CONFIG,
  2279. "Unable to lookup address for directory server at '%s'",
  2280. address);
  2281. return;
  2282. }
  2283. hostname = tor_strdup(address);
  2284. a = ntohl(a);
  2285. }
  2286. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  2287. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  2288. ent->address = hostname;
  2289. ent->addr = a;
  2290. ent->dir_port = port;
  2291. ent->is_running = 1;
  2292. ent->is_v1_authority = is_v1_authority;
  2293. memcpy(ent->digest, digest, DIGEST_LEN);
  2294. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  2295. ent->description = tor_malloc(dlen);
  2296. if (nickname)
  2297. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  2298. nickname, hostname, (int)port);
  2299. else
  2300. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  2301. hostname, (int)port);
  2302. ent->fake_status.addr = ent->addr;
  2303. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  2304. if (nickname)
  2305. strlcpy(ent->fake_status.nickname, nickname,
  2306. sizeof(ent->fake_status.nickname));
  2307. else
  2308. ent->fake_status.nickname[0] = '\0';
  2309. ent->fake_status.dir_port = ent->dir_port;
  2310. smartlist_add(trusted_dir_servers, ent);
  2311. }
  2312. /** Free storage held in <b>ds</b> */
  2313. void
  2314. trusted_dir_server_free(trusted_dir_server_t *ds)
  2315. {
  2316. tor_free(ds->nickname);
  2317. tor_free(ds->description);
  2318. tor_free(ds->address);
  2319. tor_free(ds);
  2320. }
  2321. /** Remove all members from the list of trusted dir servers. */
  2322. void
  2323. clear_trusted_dir_servers(void)
  2324. {
  2325. if (trusted_dir_servers) {
  2326. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2327. trusted_dir_server_free(ent));
  2328. smartlist_clear(trusted_dir_servers);
  2329. } else {
  2330. trusted_dir_servers = smartlist_create();
  2331. }
  2332. }
  2333. /** Return 1 if any trusted dir server supports v1 directories,
  2334. * else return 0. */
  2335. int
  2336. any_trusted_dir_is_v1_authority(void)
  2337. {
  2338. if (trusted_dir_servers)
  2339. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2340. if (ent->is_v1_authority) return 1);
  2341. return 0;
  2342. }
  2343. /** Return the network status with a given identity digest. */
  2344. networkstatus_t *
  2345. networkstatus_get_by_digest(const char *digest)
  2346. {
  2347. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2348. {
  2349. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  2350. return ns;
  2351. });
  2352. return NULL;
  2353. }
  2354. /** We believe networkstatuses more recent than this when they tell us that
  2355. * our server is broken, invalid, obsolete, etc. */
  2356. #define SELF_OPINION_INTERVAL (90*60)
  2357. /** Return a string naming the versions of Tor recommended by
  2358. * more than half the versioning networkstatuses. */
  2359. static char *
  2360. compute_recommended_versions(time_t now, int client)
  2361. {
  2362. int n_seen;
  2363. char *current;
  2364. smartlist_t *combined, *recommended;
  2365. int n_versioning;
  2366. char *result;
  2367. if (!networkstatus_list)
  2368. return tor_strdup("<none>");
  2369. combined = smartlist_create();
  2370. n_versioning = 0;
  2371. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2372. {
  2373. const char *vers;
  2374. smartlist_t *versions;
  2375. if (! ns->recommends_versions)
  2376. continue;
  2377. n_versioning++;
  2378. vers = client ? ns->client_versions : ns->server_versions;
  2379. if (!vers)
  2380. continue;
  2381. versions = smartlist_create();
  2382. smartlist_split_string(versions, vers, ",",
  2383. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2384. sort_version_list(versions, 1);
  2385. smartlist_add_all(combined, versions);
  2386. smartlist_free(versions);
  2387. });
  2388. sort_version_list(combined, 0);
  2389. current = NULL;
  2390. n_seen = 0;
  2391. recommended = smartlist_create();
  2392. SMARTLIST_FOREACH(combined, char *, cp,
  2393. {
  2394. if (current && !strcmp(cp, current)) {
  2395. ++n_seen;
  2396. } else {
  2397. if (n_seen >= n_versioning/2 && current)
  2398. smartlist_add(recommended, current);
  2399. n_seen = 0;
  2400. current = cp;
  2401. }
  2402. });
  2403. if (n_seen >= n_versioning/2 && current)
  2404. smartlist_add(recommended, current);
  2405. result = smartlist_join_strings(recommended, ", ", 0, NULL);
  2406. SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
  2407. smartlist_free(combined);
  2408. smartlist_free(recommended);
  2409. return result;
  2410. }
  2411. /** If the network-status list has changed since the last time we called this
  2412. * function, update the status of every routerinfo from the network-status
  2413. * list.
  2414. */
  2415. void
  2416. routers_update_all_from_networkstatus(void)
  2417. {
  2418. routerinfo_t *me;
  2419. time_t now;
  2420. if (!routerlist || !networkstatus_list ||
  2421. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  2422. return;
  2423. now = time(NULL);
  2424. if (networkstatus_list_has_changed)
  2425. routerstatus_list_update_from_networkstatus(now);
  2426. routers_update_status_from_networkstatus(routerlist->routers, 0);
  2427. me = router_get_my_routerinfo();
  2428. if (me && !have_warned_about_invalid_status &&
  2429. have_tried_downloading_all_statuses(4)) {
  2430. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0, n_naming = 0;
  2431. routerstatus_t *rs;
  2432. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2433. {
  2434. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  2435. continue;
  2436. ++n_recent;
  2437. if (ns->binds_names)
  2438. ++n_naming;
  2439. if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
  2440. continue;
  2441. ++n_listing;
  2442. if (rs->is_valid)
  2443. ++n_valid;
  2444. if (rs->is_named)
  2445. ++n_named;
  2446. });
  2447. if (n_recent && n_listing) {
  2448. if (n_valid <= n_recent/2) {
  2449. log_warn(LD_GENERAL,
  2450. "%d/%d recent statements from directory authorities list us "
  2451. "as unapproved. Are you misconfigured?",
  2452. n_recent-n_valid, n_recent);
  2453. have_warned_about_invalid_status = 1;
  2454. } else if (n_naming && !n_named) {
  2455. log_info(LD_GENERAL, "0/%d name-binding directory authorities "
  2456. "recognize your nickname. Please consider sending your "
  2457. "nickname and identity fingerprint to the tor-ops.",
  2458. n_naming);
  2459. have_warned_about_invalid_status = 1;
  2460. }
  2461. }
  2462. }
  2463. entry_guards_set_status_from_directory();
  2464. if (!have_warned_about_old_version &&
  2465. have_tried_downloading_all_statuses(4)) {
  2466. int n_versioning = 0;
  2467. int n_recommended = 0;
  2468. int is_server = server_mode(get_options());
  2469. version_status_t consensus = VS_RECOMMENDED;
  2470. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2471. {
  2472. version_status_t vs;
  2473. if (!ns->recommends_versions)
  2474. continue;
  2475. vs = tor_version_is_obsolete(
  2476. VERSION, is_server ? ns->server_versions : ns->client_versions);
  2477. if (vs == VS_RECOMMENDED)
  2478. ++n_recommended;
  2479. if (n_versioning++ == 0) {
  2480. consensus = vs;
  2481. } else if (consensus != vs) {
  2482. consensus = version_status_join(consensus, vs);
  2483. }
  2484. });
  2485. if (n_versioning && n_recommended <= n_versioning/2) {
  2486. if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
  2487. if (!have_warned_about_new_version) {
  2488. char *rec = compute_recommended_versions(now, !is_server);
  2489. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  2490. "recommended version%s, according to %d/%d network "
  2491. "statuses. Versions recommended by more than %d "
  2492. "authorit%s are: %s",
  2493. VERSION,
  2494. consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  2495. n_versioning-n_recommended, n_versioning, n_versioning/2,
  2496. n_versioning/2 > 1 ? "ies" : "y", rec);
  2497. have_warned_about_new_version = 1;
  2498. tor_free(rec);
  2499. }
  2500. } else {
  2501. char *rec = compute_recommended_versions(now, !is_server);
  2502. log_warn(LD_GENERAL, "Please upgrade! "
  2503. "This version of Tor (%s) is %s, according to "
  2504. "%d/%d network statuses. Versions recommended by "
  2505. "at least %d authorit%s are: %s",
  2506. VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
  2507. n_versioning-n_recommended, n_versioning, n_versioning/2,
  2508. n_versioning/2 > 1 ? "ies" : "y", rec);
  2509. have_warned_about_old_version = 1;
  2510. tor_free(rec);
  2511. }
  2512. } else {
  2513. log_info(LD_GENERAL, "%d/%d statements from "
  2514. "directory authorities say my version is ok.",
  2515. n_recommended, n_versioning);
  2516. }
  2517. }
  2518. routerstatus_list_has_changed = 0;
  2519. }
  2520. /** Allow any network-status newer than this to influence our view of who's
  2521. * running. */
  2522. #define DEFAULT_RUNNING_INTERVAL (60*60)
  2523. /** If possible, always allow at least this many network-statuses to influence
  2524. * our view of who's running. */
  2525. #define MIN_TO_INFLUENCE_RUNNING 3
  2526. /** Change the is_recent field of each member of networkstatus_list so that
  2527. * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
  2528. * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
  2529. * others are recent. Set networkstatus_list_has_changed if anything happened.
  2530. */
  2531. void
  2532. networkstatus_list_update_recent(time_t now)
  2533. {
  2534. int n_statuses, n_recent, changed, i;
  2535. char published[ISO_TIME_LEN+1];
  2536. if (!networkstatus_list)
  2537. return;
  2538. n_statuses = smartlist_len(networkstatus_list);
  2539. n_recent = 0;
  2540. changed = 0;
  2541. for (i=n_statuses-1; i >= 0; --i) {
  2542. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2543. trusted_dir_server_t *ds =
  2544. router_get_trusteddirserver_by_digest(ns->identity_digest);
  2545. const char *src = ds?ds->description:ns->source_address;
  2546. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  2547. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  2548. if (!ns->is_recent) {
  2549. format_iso_time(published, ns->published_on);
  2550. log_info(LD_DIR,
  2551. "Networkstatus from %s (published %s) is now \"recent\"",
  2552. src, published);
  2553. changed = 1;
  2554. }
  2555. ns->is_recent = 1;
  2556. ++n_recent;
  2557. } else {
  2558. if (ns->is_recent) {
  2559. format_iso_time(published, ns->published_on);
  2560. log_info(LD_DIR,
  2561. "Networkstatus from %s (published %s) is "
  2562. "no longer \"recent\"",
  2563. src, published);
  2564. changed = 1;
  2565. ns->is_recent = 0;
  2566. }
  2567. }
  2568. }
  2569. if (changed)
  2570. networkstatus_list_has_changed = 1;
  2571. }
  2572. /** Helper for routerstatus_list_update_from_networkstatus: remember how many
  2573. * authorities recommend a given descriptor digest. */
  2574. typedef struct {
  2575. routerstatus_t *rs;
  2576. int count;
  2577. } desc_digest_count_t;
  2578. /** Update our view of router status (as stored in routerstatus_list) from the
  2579. * current set of network status documents (as stored in networkstatus_list).
  2580. * Do nothing unless the network status list has changed since the last time
  2581. * this function was called.
  2582. */
  2583. static void
  2584. routerstatus_list_update_from_networkstatus(time_t now)
  2585. {
  2586. or_options_t *options = get_options();
  2587. int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
  2588. int i, j, warned;
  2589. int *index, *size;
  2590. networkstatus_t **networkstatus;
  2591. smartlist_t *result;
  2592. strmap_t *name_map;
  2593. char conflict[DIGEST_LEN]; /* Sentinel value */
  2594. desc_digest_count_t *digest_counts = NULL;
  2595. /* compute which network statuses will have a vote now */
  2596. networkstatus_list_update_recent(now);
  2597. if (!networkstatus_list_has_changed)
  2598. return;
  2599. if (!networkstatus_list)
  2600. networkstatus_list = smartlist_create();
  2601. if (!routerstatus_list)
  2602. routerstatus_list = smartlist_create();
  2603. if (!trusted_dir_servers)
  2604. trusted_dir_servers = smartlist_create();
  2605. if (!warned_conflicts)
  2606. warned_conflicts = smartlist_create();
  2607. n_trusted = smartlist_len(trusted_dir_servers);
  2608. n_statuses = smartlist_len(networkstatus_list);
  2609. if (n_statuses <= n_trusted/2) {
  2610. /* Not enough statuses to adjust status. */
  2611. log_info(LD_DIR,
  2612. "Not enough statuses to update router status list. (%d/%d)",
  2613. n_statuses, n_trusted);
  2614. return;
  2615. }
  2616. log_info(LD_DIR, "Rebuilding router status list.");
  2617. index = tor_malloc(sizeof(int)*n_statuses);
  2618. size = tor_malloc(sizeof(int)*n_statuses);
  2619. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  2620. for (i = 0; i < n_statuses; ++i) {
  2621. index[i] = 0;
  2622. networkstatus[i] = smartlist_get(networkstatus_list, i);
  2623. size[i] = smartlist_len(networkstatus[i]->entries);
  2624. if (networkstatus[i]->binds_names)
  2625. ++n_naming;
  2626. if (networkstatus[i]->is_recent)
  2627. ++n_recent;
  2628. }
  2629. /** Iterate over all entries in all networkstatuses, and build
  2630. * name_map as a map from lc nickname to identity digest. If there
  2631. * is a conflict on that nickname, map the lc nickname to conflict.
  2632. */
  2633. name_map = strmap_new();
  2634. memset(conflict, 0xff, sizeof(conflict));
  2635. for (i = 0; i < n_statuses; ++i) {
  2636. if (!networkstatus[i]->binds_names)
  2637. continue;
  2638. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  2639. {
  2640. const char *other_digest;
  2641. if (!rs->is_named)
  2642. continue;
  2643. other_digest = strmap_get_lc(name_map, rs->nickname);
  2644. warned = smartlist_string_isin(warned_conflicts, rs->nickname);
  2645. if (!other_digest) {
  2646. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  2647. if (warned)
  2648. smartlist_string_remove(warned_conflicts, rs->nickname);
  2649. } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  2650. other_digest != conflict) {
  2651. if (!warned) {
  2652. int should_warn = options->DirPort && options->AuthoritativeDir;
  2653. char fp1[HEX_DIGEST_LEN+1];
  2654. char fp2[HEX_DIGEST_LEN+1];
  2655. base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
  2656. base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
  2657. log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
  2658. "Naming authorities disagree about which key goes with %s. "
  2659. "($%s vs $%s)",
  2660. rs->nickname, fp1, fp2);
  2661. strmap_set_lc(name_map, rs->nickname, conflict);
  2662. smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
  2663. }
  2664. } else {
  2665. if (warned)
  2666. smartlist_string_remove(warned_conflicts, rs->nickname);
  2667. }
  2668. });
  2669. }
  2670. result = smartlist_create();
  2671. digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
  2672. /* Iterate through all of the sorted routerstatus lists in lockstep.
  2673. * Invariants:
  2674. * - For 0 <= i < n_statuses: index[i] is an index into
  2675. * networkstatus[i]->entries, which has size[i] elements.
  2676. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  2677. * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
  2678. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  2679. *
  2680. * (That is, the indices are always advanced past lower digest before
  2681. * higher.)
  2682. */
  2683. while (1) {
  2684. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  2685. int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0;
  2686. int n_desc_digests=0, highest_count=0;
  2687. const char *the_name = NULL;
  2688. local_routerstatus_t *rs_out, *rs_old;
  2689. routerstatus_t *rs, *most_recent;
  2690. networkstatus_t *ns;
  2691. const char *lowest = NULL;
  2692. /* Find out which of the digests appears first. */
  2693. for (i = 0; i < n_statuses; ++i) {
  2694. if (index[i] < size[i]) {
  2695. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  2696. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  2697. lowest = rs->identity_digest;
  2698. }
  2699. }
  2700. if (!lowest) {
  2701. /* We're out of routers. Great! */
  2702. break;
  2703. }
  2704. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  2705. * match "lowest" are next in order. Iterate over them, incrementing those
  2706. * index[i] as we go. */
  2707. for (i = 0; i < n_statuses; ++i) {
  2708. if (index[i] >= size[i])
  2709. continue;
  2710. ns = networkstatus[i];
  2711. rs = smartlist_get(ns->entries, index[i]);
  2712. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  2713. continue;
  2714. /* At this point, we know that we're looking at a routersatus with
  2715. * identity "lowest".
  2716. */
  2717. ++index[i];
  2718. ++n_listing;
  2719. /* Should we name this router? Only if all the names from naming
  2720. * authorities match. */
  2721. if (rs->is_named && ns->binds_names) {
  2722. if (!the_name)
  2723. the_name = rs->nickname;
  2724. if (!strcasecmp(rs->nickname, the_name)) {
  2725. ++n_named;
  2726. } else if (strcmp(the_name,"**mismatch**")) {
  2727. char hd[HEX_DIGEST_LEN+1];
  2728. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  2729. if (! smartlist_string_isin(warned_conflicts, hd)) {
  2730. log_warn(LD_DIR,
  2731. "Naming authorities disagree about nicknames for $%s "
  2732. "(\"%s\" vs \"%s\")",
  2733. hd, the_name, rs->nickname);
  2734. smartlist_add(warned_conflicts, tor_strdup(hd));
  2735. }
  2736. the_name = "**mismatch**";
  2737. }
  2738. }
  2739. /* Keep a running count of how often which descriptor digests
  2740. * appear. */
  2741. for (j = 0; j < n_desc_digests; ++j) {
  2742. if (!memcmp(rs->descriptor_digest,
  2743. digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
  2744. if (++digest_counts[j].count > highest_count)
  2745. highest_count = digest_counts[j].count;
  2746. goto found;
  2747. }
  2748. }
  2749. digest_counts[n_desc_digests].rs = rs;
  2750. digest_counts[n_desc_digests].count = 1;
  2751. if (!highest_count)
  2752. highest_count = 1;
  2753. ++n_desc_digests;
  2754. found:
  2755. /* Now tally up the easily-tallied flags. */
  2756. if (rs->is_valid)
  2757. ++n_valid;
  2758. if (rs->is_running && ns->is_recent)
  2759. ++n_running;
  2760. if (rs->is_exit)
  2761. ++n_exit;
  2762. if (rs->is_fast)
  2763. ++n_fast;
  2764. if (rs->is_possible_guard)
  2765. ++n_guard;
  2766. if (rs->is_stable)
  2767. ++n_stable;
  2768. if (rs->is_v2_dir)
  2769. ++n_v2_dir;
  2770. }
  2771. /* Go over the descriptor digests and figure out which descriptor we
  2772. * want. */
  2773. most_recent = NULL;
  2774. for (i = 0; i < n_desc_digests; ++i) {
  2775. /* If any digest appears twice or more, ignore those that don't.*/
  2776. if (highest_count >= 2 && digest_counts[i].count < 2)
  2777. continue;
  2778. if (!most_recent ||
  2779. digest_counts[i].rs->published_on > most_recent->published_on)
  2780. most_recent = digest_counts[i].rs;
  2781. }
  2782. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  2783. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  2784. /* Copy status info about this router, if we had any before. */
  2785. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  2786. if (!memcmp(rs_out->status.descriptor_digest,
  2787. most_recent->descriptor_digest, DIGEST_LEN)) {
  2788. rs_out->n_download_failures = rs_old->n_download_failures;
  2789. rs_out->next_attempt_at = rs_old->next_attempt_at;
  2790. }
  2791. rs_out->name_lookup_warned = rs_old->name_lookup_warned;
  2792. }
  2793. smartlist_add(result, rs_out);
  2794. log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
  2795. "named by %d/%d, validated by %d/%d, and %d/%d recent "
  2796. "directories think it's running.",
  2797. rs_out->status.nickname,
  2798. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  2799. n_running, n_recent);
  2800. rs_out->status.is_named = 0;
  2801. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  2802. const char *d = strmap_get_lc(name_map, the_name);
  2803. if (d && d != conflict)
  2804. rs_out->status.is_named = 1;
  2805. if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
  2806. smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
  2807. }
  2808. if (rs_out->status.is_named)
  2809. strlcpy(rs_out->status.nickname, the_name,
  2810. sizeof(rs_out->status.nickname));
  2811. rs_out->status.is_valid = n_valid > n_statuses/2;
  2812. rs_out->status.is_running = n_running > n_recent/2;
  2813. rs_out->status.is_exit = n_exit > n_statuses/2;
  2814. rs_out->status.is_fast = n_fast > n_statuses/2;
  2815. rs_out->status.is_possible_guard = n_guard > n_statuses/2;
  2816. rs_out->status.is_stable = n_stable > n_statuses/2;
  2817. rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
  2818. }
  2819. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2820. local_routerstatus_free(rs));
  2821. smartlist_free(routerstatus_list);
  2822. routerstatus_list = result;
  2823. tor_free(networkstatus);
  2824. tor_free(index);
  2825. tor_free(size);
  2826. tor_free(digest_counts);
  2827. strmap_free(name_map, NULL);
  2828. networkstatus_list_has_changed = 0;
  2829. routerstatus_list_has_changed = 1;
  2830. }
  2831. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  2832. * is_named, is_valid, and is_running fields according to our current
  2833. * networkstatus_t documents. */
  2834. void
  2835. routers_update_status_from_networkstatus(smartlist_t *routers,
  2836. int reset_failures)
  2837. {
  2838. trusted_dir_server_t *ds;
  2839. local_routerstatus_t *rs;
  2840. or_options_t *options = get_options();
  2841. int authdir = options->AuthoritativeDir;
  2842. int namingdir = options->AuthoritativeDir &&
  2843. options->NamingAuthoritativeDir;
  2844. if (!routerstatus_list)
  2845. return;
  2846. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  2847. {
  2848. const char *digest = router->cache_info.identity_digest;
  2849. rs = router_get_combined_status_by_digest(digest);
  2850. ds = router_get_trusteddirserver_by_digest(digest);
  2851. if (!rs)
  2852. continue;
  2853. if (!namingdir)
  2854. router->is_named = rs->status.is_named;
  2855. if (!authdir) {
  2856. /* If we're not an authdir, believe others. */
  2857. router->is_valid = rs->status.is_valid;
  2858. router->is_running = rs->status.is_running;
  2859. router->is_fast = rs->status.is_fast;
  2860. router->is_stable = rs->status.is_stable;
  2861. router->is_possible_guard = rs->status.is_possible_guard;
  2862. }
  2863. if (router->is_running && ds) {
  2864. ds->n_networkstatus_failures = 0;
  2865. }
  2866. if (reset_failures) {
  2867. rs->n_download_failures = 0;
  2868. rs->next_attempt_at = 0;
  2869. }
  2870. });
  2871. }
  2872. /** For every router descriptor we are currently downloading by descriptor
  2873. * digest, set result[d] to 1. */
  2874. static void
  2875. list_pending_descriptor_downloads(digestmap_t *result)
  2876. {
  2877. const char *prefix = "d/";
  2878. size_t p_len = strlen(prefix);
  2879. int i, n_conns;
  2880. connection_t **carray;
  2881. smartlist_t *tmp = smartlist_create();
  2882. tor_assert(result);
  2883. get_connection_array(&carray, &n_conns);
  2884. for (i = 0; i < n_conns; ++i) {
  2885. connection_t *conn = carray[i];
  2886. if (conn->type == CONN_TYPE_DIR &&
  2887. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  2888. !conn->marked_for_close) {
  2889. if (!strcmpstart(conn->requested_resource, prefix))
  2890. dir_split_resource_into_fingerprints(conn->requested_resource+p_len,
  2891. tmp, NULL, 1);
  2892. }
  2893. }
  2894. SMARTLIST_FOREACH(tmp, char *, d,
  2895. {
  2896. digestmap_set(result, d, (void*)1);
  2897. tor_free(d);
  2898. });
  2899. smartlist_free(tmp);
  2900. }
  2901. /** Launch downloads for all the descriptors whose digests are listed
  2902. * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
  2903. * If <b>source</b> is given, download from <b>source</b>; otherwise,
  2904. * download from an appropriate random directory server.
  2905. */
  2906. static void
  2907. initiate_descriptor_downloads(routerstatus_t *source,
  2908. smartlist_t *digests,
  2909. int lo, int hi)
  2910. {
  2911. int i, n = hi-lo;
  2912. char *resource, *cp;
  2913. size_t r_len;
  2914. if (n <= 0)
  2915. return;
  2916. if (lo < 0)
  2917. lo = 0;
  2918. if (hi > smartlist_len(digests))
  2919. hi = smartlist_len(digests);
  2920. r_len = 8 + (HEX_DIGEST_LEN+1)*n;
  2921. cp = resource = tor_malloc(r_len);
  2922. memcpy(cp, "d/", 2);
  2923. cp += 2;
  2924. for (i = lo; i < hi; ++i) {
  2925. base16_encode(cp, r_len-(cp-resource),
  2926. smartlist_get(digests,i), DIGEST_LEN);
  2927. cp += HEX_DIGEST_LEN;
  2928. *cp++ = '+';
  2929. }
  2930. memcpy(cp-1, ".z", 3);
  2931. if (source) {
  2932. /* We know which authority we want. */
  2933. directory_initiate_command_routerstatus(source,
  2934. DIR_PURPOSE_FETCH_SERVERDESC,
  2935. 0, /* not private */
  2936. resource, NULL, 0);
  2937. } else {
  2938. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  2939. resource,
  2940. 1);
  2941. }
  2942. tor_free(resource);
  2943. }
  2944. /** Clients don't download any descriptor this recent, since it will probably
  2945. * not have propageted to enough caches. */
  2946. #define ESTIMATED_PROPAGATION_TIME (10*60)
  2947. /** Return 0 if this routerstatus is obsolete, too new, isn't
  2948. * running, or otherwise not a descriptor that we would make any
  2949. * use of even if we had it. Else return 1. */
  2950. static int
  2951. client_would_use_router(routerstatus_t *rs, time_t now)
  2952. {
  2953. if (rs->published_on + ROUTER_MAX_AGE < now) {
  2954. /* This one is too old to consider. */
  2955. return 0;
  2956. }
  2957. if (!rs->is_running && !get_options()->FetchUselessDescriptors) {
  2958. /* If we had this router descriptor, we wouldn't even bother using it.
  2959. * But, if we want to have a complete list, fetch it anyway. */
  2960. return 0;
  2961. }
  2962. if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
  2963. /* Most caches probably don't have this descriptor yet. */
  2964. return 0;
  2965. }
  2966. return 1;
  2967. }
  2968. /** Return new list of ID fingerprints for routers that we (as a client) would
  2969. * like to download.
  2970. */
  2971. static smartlist_t *
  2972. router_list_client_downloadable(void)
  2973. {
  2974. int n_downloadable = 0;
  2975. smartlist_t *downloadable = smartlist_create();
  2976. digestmap_t *downloading;
  2977. time_t now = time(NULL);
  2978. /* these are just used for logging */
  2979. int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_wouldnt_use = 0;
  2980. if (!routerstatus_list)
  2981. return downloadable;
  2982. downloading = digestmap_new();
  2983. list_pending_descriptor_downloads(downloading);
  2984. routerstatus_list_update_from_networkstatus(now);
  2985. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2986. {
  2987. routerinfo_t *ri;
  2988. if (!client_would_use_router(&rs->status, now)) {
  2989. /* We wouldn't want this descriptor even if we got it. */
  2990. ++n_wouldnt_use;
  2991. } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
  2992. /* We're downloading this one now. */
  2993. ++n_in_progress;
  2994. } else if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
  2995. /* We have the 'best' descriptor for this router. */
  2996. ++n_uptodate;
  2997. } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
  2998. ri->cache_info.published_on > rs->status.published_on) {
  2999. /* Oddly, we have a descriptor more recent than the 'best' one, but it
  3000. was once best. So that's okay. */
  3001. ++n_uptodate;
  3002. } else if (rs->next_attempt_at > now) {
  3003. /* We failed too recently to try again. */
  3004. ++n_not_ready;
  3005. } else {
  3006. /* Okay, time to try it. */
  3007. smartlist_add(downloadable, rs->status.descriptor_digest);
  3008. ++n_downloadable;
  3009. }
  3010. });
  3011. #if 0
  3012. log_info(LD_DIR,
  3013. "%d router descriptors are downloadable. "
  3014. "%d are in progress. %d are up-to-date. "
  3015. "%d are non-useful. %d failed too recently to retry.",
  3016. n_downloadable, n_in_progress, n_uptodate,
  3017. n_wouldnt_use, n_not_ready);
  3018. #endif
  3019. digestmap_free(downloading, NULL);
  3020. return downloadable;
  3021. }
  3022. /** Initiate new router downloads as needed, using the strategy for
  3023. * non-directory-servers.
  3024. *
  3025. * We only allow one router descriptor download at a time.
  3026. * If we have less than two network-status documents, we ask
  3027. * a directory for "all descriptors."
  3028. * Otherwise, we ask for all descriptors that we think are different
  3029. * from what we have.
  3030. */
  3031. static void
  3032. update_router_descriptor_client_downloads(time_t now)
  3033. {
  3034. /* Max amount of hashes to download per request.
  3035. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3036. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3037. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3038. * So use 96 because it's a nice number.
  3039. */
  3040. #define MAX_DL_PER_REQUEST 96
  3041. /** Don't split our requests so finely that we are requesting fewer than
  3042. * this number per server. */
  3043. #define MIN_DL_PER_REQUEST 4
  3044. /** To prevent a single screwy cache from confusing us by selective reply,
  3045. * try to split our requests into at least this this many requests. */
  3046. #define MIN_REQUESTS 3
  3047. /** If we want fewer than this many descriptors, wait until we
  3048. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3049. * passed. */
  3050. #define MAX_DL_TO_DELAY 16
  3051. /** When directory clients have only a few servers to request, they batch
  3052. * them until they have more, or until this amount of time has passed. */
  3053. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3054. smartlist_t *downloadable = NULL;
  3055. int should_delay, n_downloadable;
  3056. or_options_t *options = get_options();
  3057. if (server_mode(options) && options->DirPort) {
  3058. log_warn(LD_BUG,
  3059. "Called router_descriptor_client_downloads() on a mirror?");
  3060. }
  3061. /* XXX here's another magic 2 that probably should be replaced
  3062. * by <= smartlist_len(trusted_dir_servers)/2
  3063. * or by a function returning same. -- weasel */
  3064. if (networkstatus_list && smartlist_len(networkstatus_list) < 2) {
  3065. log_info(LD_DIR,
  3066. "Not enough networkstatus documents to launch requests.");
  3067. }
  3068. downloadable = router_list_client_downloadable();
  3069. n_downloadable = smartlist_len(downloadable);
  3070. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3071. log_debug(LD_DIR,
  3072. "There are enough downloadable routerdescs to launch requests.");
  3073. should_delay = 0;
  3074. } else if (n_downloadable == 0) {
  3075. // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
  3076. should_delay = 1;
  3077. } else {
  3078. should_delay = (last_routerdesc_download_attempted +
  3079. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3080. if (!should_delay) {
  3081. if (last_routerdesc_download_attempted) {
  3082. log_info(LD_DIR,
  3083. "There are not many downloadable routerdescs, but we've "
  3084. "been waiting long enough (%d seconds). Downloading.",
  3085. (int)(now-last_routerdesc_download_attempted));
  3086. } else {
  3087. log_info(LD_DIR,
  3088. "There are not many downloadable routerdescs, but we've "
  3089. "never downloaded descriptors before. Downloading.");
  3090. }
  3091. }
  3092. }
  3093. if (! should_delay) {
  3094. int i, n_per_request;
  3095. n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
  3096. if (n_per_request > MAX_DL_PER_REQUEST)
  3097. n_per_request = MAX_DL_PER_REQUEST;
  3098. if (n_per_request < MIN_DL_PER_REQUEST)
  3099. n_per_request = MIN_DL_PER_REQUEST;
  3100. log_info(LD_DIR,
  3101. "Launching %d request%s for %d router%s, %d at a time",
  3102. (n_downloadable+n_per_request-1)/n_per_request,
  3103. n_downloadable>n_per_request?"s":"",
  3104. n_downloadable, n_downloadable>1?"s":"", n_per_request);
  3105. for (i=0; i < n_downloadable; i += n_per_request) {
  3106. initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
  3107. }
  3108. last_routerdesc_download_attempted = now;
  3109. }
  3110. smartlist_free(downloadable);
  3111. }
  3112. /** Launch downloads for router status as needed, using the strategy used by
  3113. * authorities and caches: download every descriptor we don't have but would
  3114. * serve from a random authoritiy that lists it. */
  3115. static void
  3116. update_router_descriptor_cache_downloads(time_t now)
  3117. {
  3118. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3119. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3120. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3121. int i, j, n;
  3122. int n_download;
  3123. or_options_t *options = get_options();
  3124. if (!(server_mode(options) && options->DirPort)) {
  3125. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
  3126. "on a non-mirror?");
  3127. }
  3128. if (!networkstatus_list || !smartlist_len(networkstatus_list))
  3129. return;
  3130. map = digestmap_new();
  3131. n = smartlist_len(networkstatus_list);
  3132. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3133. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3134. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3135. * downloading. */
  3136. list_pending_descriptor_downloads(map);
  3137. /* For the digest of every descriptor that we don't have, and that we aren't
  3138. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3139. * about that descriptor, and we haven't already failed to get that
  3140. * descriptor from the corresponding authority.
  3141. */
  3142. n_download = 0;
  3143. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3144. {
  3145. smartlist_t *dl = smartlist_create();
  3146. downloadable[ns_sl_idx] = dl;
  3147. download_from[ns_sl_idx] = smartlist_create();
  3148. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  3149. {
  3150. if (!rs->need_to_mirror)
  3151. continue;
  3152. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3153. log_warn(LD_BUG,
  3154. "Bug: We have a router descriptor, but need_to_mirror=1.");
  3155. rs->need_to_mirror = 0;
  3156. continue;
  3157. }
  3158. if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
  3159. rs->need_to_mirror = 0;
  3160. continue;
  3161. }
  3162. if (digestmap_get(map, rs->descriptor_digest)) {
  3163. /* We're downloading it already. */
  3164. continue;
  3165. } else {
  3166. /* We could download it from this guy. */
  3167. smartlist_add(dl, rs->descriptor_digest);
  3168. ++n_download;
  3169. }
  3170. });
  3171. });
  3172. /* At random, assign descriptors to authorities such that:
  3173. * - if d is a member of some downloadable[x], d is a member of some
  3174. * download_from[y]. (Everything we want to download, we try to download
  3175. * from somebody.)
  3176. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3177. * (We only try to download descriptors from authorities who claim to have
  3178. * them.)
  3179. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3180. * (We don't try to download anything from two authorities concurrently.)
  3181. */
  3182. while (n_download) {
  3183. int which_ns = crypto_rand_int(n);
  3184. smartlist_t *dl = downloadable[which_ns];
  3185. int idx;
  3186. char *d;
  3187. tor_assert(dl);
  3188. if (!smartlist_len(dl))
  3189. continue;
  3190. idx = crypto_rand_int(smartlist_len(dl));
  3191. d = smartlist_get(dl, idx);
  3192. if (! digestmap_get(map, d)) {
  3193. smartlist_add(download_from[which_ns], d);
  3194. digestmap_set(map, d, (void*) 1);
  3195. }
  3196. smartlist_del(dl, idx);
  3197. --n_download;
  3198. }
  3199. /* Now, we can actually launch our requests. */
  3200. for (i=0; i<n; ++i) {
  3201. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  3202. trusted_dir_server_t *ds =
  3203. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3204. smartlist_t *dl = download_from[i];
  3205. if (!ds) {
  3206. log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
  3207. continue;
  3208. }
  3209. if (! smartlist_len(dl))
  3210. continue;
  3211. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3212. smartlist_len(dl), ds->nickname);
  3213. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3214. initiate_descriptor_downloads(&(ds->fake_status), dl, j,
  3215. j+MAX_DL_PER_REQUEST);
  3216. }
  3217. }
  3218. for (i=0; i<n; ++i) {
  3219. smartlist_free(download_from[i]);
  3220. smartlist_free(downloadable[i]);
  3221. }
  3222. tor_free(download_from);
  3223. tor_free(downloadable);
  3224. digestmap_free(map,NULL);
  3225. }
  3226. /** Launch downloads for router status as needed. */
  3227. void
  3228. update_router_descriptor_downloads(time_t now)
  3229. {
  3230. or_options_t *options = get_options();
  3231. if (server_mode(options) && options->DirPort) {
  3232. update_router_descriptor_cache_downloads(now);
  3233. } else {
  3234. update_router_descriptor_client_downloads(now);
  3235. }
  3236. }
  3237. static int
  3238. routerstatus_count_usable_entries(smartlist_t *entries)
  3239. {
  3240. int count = 0;
  3241. time_t now = time(NULL);
  3242. SMARTLIST_FOREACH(entries, routerstatus_t *, rs,
  3243. if (client_would_use_router(rs, now)) count++);
  3244. return count;
  3245. }
  3246. /** Return true iff we have enough networkstatus and router information to
  3247. * start building circuits. Right now, this means "more than half the
  3248. * networkstatus documents, and at least 1/4 of expected routers." */
  3249. //XXX should consider whether we have enough exiting nodes here.
  3250. int
  3251. router_have_minimum_dir_info(void)
  3252. {
  3253. int tot = 0, num_running = 0;
  3254. int n_ns, n_authorities, res, avg;
  3255. static int have_enough = 0;
  3256. if (!networkstatus_list || !routerlist) {
  3257. res = 0;
  3258. goto done;
  3259. }
  3260. n_authorities = smartlist_len(trusted_dir_servers);
  3261. n_ns = smartlist_len(networkstatus_list);
  3262. if (n_ns<=n_authorities/2) {
  3263. log_info(LD_DIR,
  3264. "We have %d of %d network statuses, and we want "
  3265. "more than %d.", n_ns, n_authorities, n_authorities/2);
  3266. res = 0;
  3267. goto done;
  3268. }
  3269. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3270. tot += routerstatus_count_usable_entries(ns->entries));
  3271. avg = tot / n_ns;
  3272. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3273. {
  3274. if (rs->status.is_running)
  3275. num_running++;
  3276. });
  3277. res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
  3278. done:
  3279. if (res && !have_enough) {
  3280. log(LOG_NOTICE, LD_DIR,
  3281. "We now have enough directory information to build circuits.");
  3282. }
  3283. if (!res && have_enough) {
  3284. log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
  3285. "enough to build circuits.%s",
  3286. num_running > 2 ? "" : " (Not enough servers seem reachable -- "
  3287. "is your network connection down?)");
  3288. }
  3289. have_enough = res;
  3290. return res;
  3291. }
  3292. /** Return true iff we have downloaded, or attempted to download at least
  3293. * n_failures times, a network status for each authority. */
  3294. static int
  3295. have_tried_downloading_all_statuses(int n_failures)
  3296. {
  3297. if (!trusted_dir_servers)
  3298. return 0;
  3299. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  3300. {
  3301. /* If we don't have the status, and we haven't failed to get the status,
  3302. * we haven't tried to get the status. */
  3303. if (!networkstatus_get_by_digest(ds->digest) &&
  3304. ds->n_networkstatus_failures <= n_failures)
  3305. return 0;
  3306. });
  3307. return 1;
  3308. }
  3309. /** Reset the descriptor download failure count on all routers, so that we
  3310. * can retry any long-failed routers immediately.
  3311. */
  3312. void
  3313. router_reset_descriptor_download_failures(void)
  3314. {
  3315. if (!routerstatus_list)
  3316. return;
  3317. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3318. {
  3319. rs->n_download_failures = 0;
  3320. rs->next_attempt_at = 0;
  3321. });
  3322. tor_assert(networkstatus_list);
  3323. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3324. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  3325. {
  3326. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  3327. rs->need_to_mirror = 1;
  3328. }));
  3329. last_routerdesc_download_attempted = 0;
  3330. }
  3331. /** Any changes in a router descriptor's publication time larger than this are
  3332. * automatically non-cosmetic. */
  3333. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  3334. /** Return true iff the only differences between r1 and r2 are such that
  3335. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  3336. */
  3337. int
  3338. router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
  3339. {
  3340. time_t r1pub, r2pub;
  3341. tor_assert(r1 && r2);
  3342. /* r1 should be the one that was published first. */
  3343. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  3344. routerinfo_t *ri_tmp = r2;
  3345. r2 = r1;
  3346. r1 = ri_tmp;
  3347. }
  3348. /* If any key fields differ, they're different. */
  3349. if (strcasecmp(r1->address, r2->address) ||
  3350. strcasecmp(r1->nickname, r2->nickname) ||
  3351. r1->or_port != r2->or_port ||
  3352. r1->dir_port != r2->dir_port ||
  3353. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  3354. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  3355. strcasecmp(r1->platform, r2->platform) ||
  3356. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  3357. (!r1->contact_info && r2->contact_info) ||
  3358. (r1->contact_info && r2->contact_info &&
  3359. strcasecmp(r1->contact_info, r2->contact_info)) ||
  3360. r1->is_hibernating != r2->is_hibernating ||
  3361. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  3362. return 0;
  3363. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  3364. return 0;
  3365. if (r1->declared_family && r2->declared_family) {
  3366. int i, n;
  3367. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  3368. return 0;
  3369. n = smartlist_len(r1->declared_family);
  3370. for (i=0; i < n; ++i) {
  3371. if (strcasecmp(smartlist_get(r1->declared_family, i),
  3372. smartlist_get(r2->declared_family, i)))
  3373. return 0;
  3374. }
  3375. }
  3376. /* Did bandwidth change a lot? */
  3377. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  3378. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  3379. return 0;
  3380. /* Did more than 12 hours pass? */
  3381. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  3382. < r2->cache_info.published_on)
  3383. return 0;
  3384. /* Did uptime fail to increase by approximately the amount we would think,
  3385. * give or take 30 minutes? */
  3386. r1pub = r1->cache_info.published_on;
  3387. r2pub = r2->cache_info.published_on;
  3388. if (abs(r2->uptime - (r1->uptime + (r2pub - r1pub))))
  3389. return 0;
  3390. /* Otherwise, the difference is cosmetic. */
  3391. return 1;
  3392. }
  3393. static void
  3394. routerlist_assert_ok(routerlist_t *rl)
  3395. {
  3396. digestmap_iter_t *iter;
  3397. routerinfo_t *r2;
  3398. signed_descriptor_t *sd2;
  3399. if (!routerlist)
  3400. return;
  3401. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  3402. {
  3403. r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
  3404. tor_assert(r == r2);
  3405. sd2 = digestmap_get(rl->desc_digest_map,
  3406. r->cache_info.signed_descriptor_digest);
  3407. tor_assert(&(r->cache_info) == sd2);
  3408. });
  3409. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  3410. {
  3411. r2 = digestmap_get(rl->identity_map, sd->identity_digest);
  3412. tor_assert(sd != &(r2->cache_info));
  3413. sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  3414. tor_assert(sd == sd2);
  3415. });
  3416. iter = digestmap_iter_init(rl->identity_map);
  3417. while (!digestmap_iter_done(iter)) {
  3418. const char *d;
  3419. void *_r;
  3420. routerinfo_t *r;
  3421. digestmap_iter_get(iter, &d, &_r);
  3422. r = _r;
  3423. tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
  3424. iter = digestmap_iter_next(rl->identity_map, iter);
  3425. }
  3426. iter = digestmap_iter_init(rl->desc_digest_map);
  3427. while (!digestmap_iter_done(iter)) {
  3428. const char *d;
  3429. void *_sd;
  3430. signed_descriptor_t *sd;
  3431. digestmap_iter_get(iter, &d, &_sd);
  3432. sd = _sd;
  3433. tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
  3434. iter = digestmap_iter_next(rl->desc_digest_map, iter);
  3435. }
  3436. }
  3437. /** Allocate and return a new string representing the contact info
  3438. * and platform string for <b>router</b>,
  3439. * surrounded by quotes and using standard C escapes.
  3440. *
  3441. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  3442. * thread. Also, each call invalidates the last-returned value, so don't
  3443. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  3444. */
  3445. const char *
  3446. esc_router_info(routerinfo_t *router)
  3447. {
  3448. static char *info;
  3449. char *esc_contact, *esc_platform;
  3450. size_t len;
  3451. if (info)
  3452. tor_free(info);
  3453. esc_contact = esc_for_log(router->contact_info);
  3454. esc_platform = esc_for_log(router->platform);
  3455. len = strlen(esc_contact)+strlen(esc_platform)+32;
  3456. info = tor_malloc(len);
  3457. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  3458. esc_platform);
  3459. tor_free(esc_contact);
  3460. tor_free(esc_platform);
  3461. return info;
  3462. }