routerlist.c 112 KB

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