routerlist.c 125 KB

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