routerlist.c 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569
  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[] = "$Id$";
  7. /**
  8. * \file routerlist.c
  9. * \brief Code to
  10. * maintain and access the global list of routerinfos for known
  11. * servers.
  12. **/
  13. #include "or.h"
  14. /****************************************************************************/
  15. /** Global list of a trusted_dir_server_t object for each trusted directory
  16. * server. */
  17. static smartlist_t *trusted_dir_servers = NULL;
  18. /* static function prototypes */
  19. static routerinfo_t *router_pick_directory_server_impl(int requireother,
  20. int fascistfirewall,
  21. int for_v2_directory);
  22. static trusted_dir_server_t *router_pick_trusteddirserver_impl(
  23. int need_v1_support, int requireother, int fascistfirewall);
  24. static void mark_all_trusteddirservers_up(void);
  25. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  26. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  27. static void routerstatus_list_update_from_networkstatus(time_t now);
  28. /****************************************************************************/
  29. /****
  30. * Functions to manage and access our list of known routers. (Note:
  31. * dirservers maintain a separate, independent list of known router
  32. * descriptors.)
  33. ****/
  34. /** Global list of all of the routers that we know about. */
  35. static routerlist_t *routerlist = NULL;
  36. extern int has_fetched_directory; /**< from main.c */
  37. /** Global list of all of the current network_status documents that we know
  38. * about. This list is kept sorted by published_on. */
  39. static smartlist_t *networkstatus_list = NULL;
  40. /** Global list of routerstatuses_t for each router, known or unknown. */
  41. static smartlist_t *routerstatus_list = NULL;
  42. /*DOCDOC */
  43. static int networkstatus_list_has_changed = 0;
  44. /*DOCDOC */
  45. static int routerstatus_list_has_changed = 0;
  46. /** Repopulate our list of network_status_t objects from the list cached on
  47. * disk. Return 0 on success, -1 on failure. */
  48. int
  49. router_reload_networkstatus(void)
  50. {
  51. char filename[512];
  52. struct stat st;
  53. smartlist_t *entries, *bad_names;
  54. char *s;
  55. tor_assert(get_options()->DataDirectory);
  56. if (!networkstatus_list)
  57. networkstatus_list = smartlist_create();
  58. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  59. get_options()->DataDirectory);
  60. entries = tor_listdir(filename);
  61. bad_names = smartlist_create();
  62. SMARTLIST_FOREACH(entries, const char *, fn, {
  63. char buf[DIGEST_LEN];
  64. if (strlen(fn) != HEX_DIGEST_LEN ||
  65. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  66. log_fn(LOG_INFO,
  67. "Skipping cached-status file with unexpected name \"%s\"",fn);
  68. continue;
  69. }
  70. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  71. get_options()->DataDirectory, fn);
  72. s = read_file_to_str(filename, 0);
  73. if (s) {
  74. stat(filename, &st);
  75. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  76. log_fn(LOG_WARN, "Couldn't load networkstatus from \"%s\"",filename);
  77. }
  78. tor_free(s);
  79. }
  80. });
  81. networkstatus_list_clean(time(NULL));
  82. routers_update_all_from_networkstatus();
  83. return 0;
  84. }
  85. /* Router descriptor storage.
  86. *
  87. * Routerdescs are stored in a big file, named "cached-routers". As new
  88. * routerdescs arrive, we append them to a journal file named
  89. * "cached-routers.new".
  90. *
  91. * From time to time, we replace "cached-routers" with a new file containing
  92. * only the live, non-superseded descriptors, and clear cached-routers.new.
  93. *
  94. * On startup, we read both files.
  95. */
  96. /** The size of the router log, in bytes. */
  97. static size_t router_journal_len = 0;
  98. /** The size of the router store, in bytes. */
  99. static size_t router_store_len = 0;
  100. /** Helper: return 1 iff the router log is so big we want to rebuild the
  101. * store. */
  102. static int
  103. router_should_rebuild_store(void)
  104. {
  105. if (router_store_len > (1<<16))
  106. return router_journal_len > router_store_len / 2;
  107. else
  108. return router_journal_len > (1<<15);
  109. }
  110. /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
  111. * journal. */
  112. static int
  113. router_append_to_journal(const char *s, size_t len)
  114. {
  115. or_options_t *options = get_options();
  116. size_t fname_len = strlen(options->DataDirectory)+32;
  117. char *fname = tor_malloc(len);
  118. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  119. options->DataDirectory);
  120. if (!len)
  121. len = strlen(s);
  122. if (append_bytes_to_file(fname, s, len, 0)) {
  123. log_fn(LOG_WARN, "Unable to store router descriptor");
  124. tor_free(fname);
  125. return -1;
  126. }
  127. tor_free(fname);
  128. router_journal_len += len;
  129. return 0;
  130. }
  131. /** If the journal is too long, or if <b>force</b> is true, then atomically
  132. * replace the router store with the routers currently in our routerlist, and
  133. * clear the journal. Return 0 on success, -1 on failure.
  134. */
  135. static int
  136. router_rebuild_store(int force)
  137. {
  138. size_t len = 0;
  139. or_options_t *options;
  140. size_t fname_len;
  141. smartlist_t *chunk_list = NULL;
  142. char *fname = NULL;
  143. int r = -1;
  144. if (!force && !router_should_rebuild_store())
  145. return 0;
  146. if (!routerlist)
  147. return 0;
  148. /* Don't save deadweight. */
  149. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  150. options = get_options();
  151. fname_len = strlen(options->DataDirectory)+32;
  152. fname = tor_malloc(fname_len);
  153. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  154. chunk_list = smartlist_create();
  155. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  156. {
  157. sized_chunk_t *c;
  158. if (!ri->signed_descriptor) {
  159. log_fn(LOG_WARN, "Bug! No descriptor stored for router '%s'.",
  160. ri->nickname);
  161. goto done;
  162. }
  163. c = tor_malloc(sizeof(sized_chunk_t));
  164. c->bytes = ri->signed_descriptor;
  165. c->len = ri->signed_descriptor_len;
  166. smartlist_add(chunk_list, c);
  167. });
  168. if (write_chunks_to_file(fname, chunk_list, 0)<0) {
  169. log_fn(LOG_WARN, "Error writing router store to disk.");
  170. goto done;
  171. }
  172. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  173. options->DataDirectory);
  174. write_str_to_file(fname, "", 0);
  175. r = 0;
  176. router_store_len = len;
  177. router_journal_len = 0;
  178. done:
  179. tor_free(fname);
  180. if (chunk_list) {
  181. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  182. smartlist_free(chunk_list);
  183. }
  184. return r;
  185. }
  186. /* Load all cached router descriptors from the store. Return 0 on success and
  187. * -1 on failure.
  188. */
  189. int
  190. router_reload_router_list(void)
  191. {
  192. or_options_t *options = get_options();
  193. size_t fname_len = strlen(options->DataDirectory)+32;
  194. char *fname = tor_malloc(fname_len);
  195. struct stat st;
  196. int j;
  197. if (!routerlist) {
  198. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  199. routerlist->routers = smartlist_create();
  200. }
  201. router_journal_len = router_store_len = 0;
  202. for (j = 0; j < 2; ++j) {
  203. char *contents;
  204. tor_snprintf(fname, fname_len,
  205. (j==0)?"%s/cached-routers":"%s/cached-routers.new",
  206. options->DataDirectory);
  207. contents = read_file_to_str(fname, 0);
  208. if (contents) {
  209. stat(fname, &st);
  210. if (j==0)
  211. router_store_len = st.st_size;
  212. else
  213. router_journal_len = st.st_size;
  214. router_load_routers_from_string(contents, 1, NULL);
  215. tor_free(contents);
  216. }
  217. }
  218. /* Don't cache expired routers. */
  219. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  220. if (router_journal_len) {
  221. /* Always clear the journal on startup.*/
  222. router_rebuild_store(1);
  223. }
  224. return 0;
  225. }
  226. /** Set *<b>outp</b> to a smartlist containing a list of
  227. * trusted_dir_server_t * for all known trusted dirservers. Callers
  228. * must not modify the list or its contents.
  229. */
  230. void
  231. router_get_trusted_dir_servers(smartlist_t **outp)
  232. {
  233. if (!trusted_dir_servers)
  234. trusted_dir_servers = smartlist_create();
  235. *outp = trusted_dir_servers;
  236. }
  237. /** Try to find a running dirserver. If there are no running dirservers
  238. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  239. * set all the authoritative ones as running again, and pick one;
  240. * if there are then no dirservers at all in our routerlist,
  241. * reload the routerlist and try one last time. If for_runningrouters is
  242. * true, then only pick a dirserver that can answer runningrouters queries
  243. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  244. * Other args are as in router_pick_directory_server_impl().
  245. */
  246. routerinfo_t *
  247. router_pick_directory_server(int requireother,
  248. int fascistfirewall,
  249. int for_v2_directory,
  250. int retry_if_no_servers)
  251. {
  252. routerinfo_t *choice;
  253. if (!routerlist)
  254. return NULL;
  255. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  256. for_v2_directory);
  257. if (choice || !retry_if_no_servers)
  258. return choice;
  259. log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
  260. /* mark all authdirservers as up again */
  261. mark_all_trusteddirservers_up();
  262. /* try again */
  263. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  264. for_v2_directory);
  265. if (choice)
  266. return choice;
  267. log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
  268. firewall_is_fascist() ? "reachable" : "known");
  269. has_fetched_directory=0; /* reset it */
  270. if (router_reload_router_list()) {
  271. return NULL;
  272. }
  273. /* give it one last try */
  274. choice = router_pick_directory_server_impl(requireother, 0,
  275. for_v2_directory);
  276. return choice;
  277. }
  278. trusted_dir_server_t *
  279. router_get_trusteddirserver_by_digest(const char *digest)
  280. {
  281. if (!trusted_dir_servers)
  282. return NULL;
  283. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  284. {
  285. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  286. return ds;
  287. });
  288. return NULL;
  289. }
  290. /** Try to find a running trusted dirserver. If there are no running
  291. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  292. * set them all as running again, and try again.
  293. * Other args are as in router_pick_trusteddirserver_impl().
  294. */
  295. trusted_dir_server_t *
  296. router_pick_trusteddirserver(int need_v1_support,
  297. int requireother,
  298. int fascistfirewall,
  299. int retry_if_no_servers)
  300. {
  301. trusted_dir_server_t *choice;
  302. choice = router_pick_trusteddirserver_impl(need_v1_support,
  303. requireother, fascistfirewall);
  304. if (choice || !retry_if_no_servers)
  305. return choice;
  306. log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
  307. mark_all_trusteddirservers_up();
  308. return router_pick_trusteddirserver_impl(need_v1_support,
  309. requireother, fascistfirewall);
  310. }
  311. /** Pick a random running verified directory server/mirror from our
  312. * routerlist.
  313. * If <b>fascistfirewall</b> and we're not using a proxy,
  314. * make sure the port we pick is allowed by options-\>firewallports.
  315. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  316. * choose a directory server new enough to support the v2 directory
  317. * functionality.
  318. */
  319. static routerinfo_t *
  320. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  321. int for_v2_directory)
  322. {
  323. routerinfo_t *result;
  324. smartlist_t *sl;
  325. if (!routerlist)
  326. return NULL;
  327. if (get_options()->HttpProxy)
  328. fascistfirewall = 0;
  329. /* Find all the running dirservers we know about. */
  330. sl = smartlist_create();
  331. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  332. {
  333. if (!router->is_running || !router->dir_port || !router->is_verified)
  334. continue;
  335. if (requireother && router_is_me(router))
  336. continue;
  337. if (fascistfirewall) {
  338. if (!fascist_firewall_allows_address(router->addr, router->dir_port))
  339. continue;
  340. }
  341. /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
  342. * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
  343. * the directory server.
  344. */
  345. if (for_v2_directory &&
  346. !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
  347. router_digest_is_trusted_dir(router->identity_digest)))
  348. continue;
  349. smartlist_add(sl, router);
  350. });
  351. result = smartlist_choose(sl);
  352. smartlist_free(sl);
  353. return result;
  354. }
  355. /** Choose randomly from among the trusted dirservers that are up.
  356. * If <b>fascistfirewall</b> and we're not using a proxy,
  357. * make sure the port we pick is allowed by options-\>firewallports.
  358. * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
  359. * a trusted authority for the v1 directory system.
  360. */
  361. static trusted_dir_server_t *
  362. router_pick_trusteddirserver_impl(int need_v1_support,
  363. int requireother, int fascistfirewall)
  364. {
  365. smartlist_t *sl;
  366. routerinfo_t *me;
  367. trusted_dir_server_t *ds;
  368. sl = smartlist_create();
  369. me = router_get_my_routerinfo();
  370. if (!trusted_dir_servers)
  371. return NULL;
  372. if (get_options()->HttpProxy)
  373. fascistfirewall = 0;
  374. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  375. {
  376. if (!d->is_running) continue;
  377. if (need_v1_support && !d->supports_v1_protocol)
  378. continue;
  379. if (requireother && me &&
  380. !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
  381. continue;
  382. if (fascistfirewall) {
  383. if (!fascist_firewall_allows_address(d->addr, d->dir_port))
  384. continue;
  385. }
  386. smartlist_add(sl, d);
  387. });
  388. ds = smartlist_choose(sl);
  389. smartlist_free(sl);
  390. return ds;
  391. }
  392. /** Go through and mark the authoritative dirservers as up. */
  393. static void
  394. mark_all_trusteddirservers_up(void)
  395. {
  396. if (routerlist) {
  397. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  398. if (router_digest_is_trusted_dir(router->identity_digest) &&
  399. router->dir_port > 0) {
  400. router->is_running = 1;
  401. });
  402. }
  403. if (trusted_dir_servers) {
  404. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  405. {
  406. dir->is_running = 1;
  407. dir->n_networkstatus_failures = 0;
  408. });
  409. }
  410. }
  411. /** Return 0 if \\exists an authoritative dirserver that's currently
  412. * thought to be running, else return 1.
  413. */
  414. int
  415. all_trusted_directory_servers_down(void)
  416. {
  417. if (!trusted_dir_servers)
  418. return 1;
  419. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  420. if (dir->is_running) return 0);
  421. return 1;
  422. }
  423. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  424. * This is used to make sure we don't pick siblings in a single path.
  425. */
  426. void
  427. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  428. {
  429. routerinfo_t *r;
  430. config_line_t *cl;
  431. if (!router->declared_family)
  432. return;
  433. /* Add every r such that router declares familyness with r, and r
  434. * declares familyhood with router. */
  435. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  436. {
  437. if (!(r = router_get_by_nickname(n)))
  438. continue;
  439. if (!r->declared_family)
  440. continue;
  441. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  442. {
  443. if (router_nickname_matches(router, n2))
  444. smartlist_add(sl, r);
  445. });
  446. });
  447. /* If the user declared any families locally, honor those too. */
  448. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  449. if (router_nickname_is_in_list(router, cl->value)) {
  450. add_nickname_list_to_smartlist(sl, cl->value, 0);
  451. }
  452. }
  453. }
  454. /** List of strings for nicknames we've already warned about and that are
  455. * still unknown / unavailable. */
  456. static smartlist_t *warned_nicknames = NULL;
  457. /** Given a comma-and-whitespace separated list of nicknames, see which
  458. * nicknames in <b>list</b> name routers in our routerlist that are
  459. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  460. */
  461. void
  462. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
  463. {
  464. routerinfo_t *router;
  465. smartlist_t *nickname_list;
  466. if (!list)
  467. return; /* nothing to do */
  468. tor_assert(sl);
  469. nickname_list = smartlist_create();
  470. if (!warned_nicknames)
  471. warned_nicknames = smartlist_create();
  472. smartlist_split_string(nickname_list, list, ",",
  473. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  474. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  475. int warned;
  476. if (!is_legal_nickname_or_hexdigest(nick)) {
  477. log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
  478. continue;
  479. }
  480. router = router_get_by_nickname(nick);
  481. warned = smartlist_string_isin(warned_nicknames, nick);
  482. if (router) {
  483. if (router->is_running) {
  484. smartlist_add(sl,router);
  485. if (warned)
  486. smartlist_string_remove(warned_nicknames, nick);
  487. } else {
  488. if (!warned) {
  489. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
  490. "Nickname list includes '%s' which is known but down.",nick);
  491. smartlist_add(warned_nicknames, tor_strdup(nick));
  492. }
  493. }
  494. } else {
  495. if (!warned) {
  496. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  497. "Nickname list includes '%s' which isn't a known router.",nick);
  498. smartlist_add(warned_nicknames, tor_strdup(nick));
  499. }
  500. }
  501. });
  502. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  503. smartlist_free(nickname_list);
  504. }
  505. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  506. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  507. */
  508. static int
  509. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  510. {
  511. smartlist_t *nickname_list;
  512. int v = 0;
  513. if (!list)
  514. return 0; /* definitely not */
  515. tor_assert(router);
  516. nickname_list = smartlist_create();
  517. smartlist_split_string(nickname_list, list, ",",
  518. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  519. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  520. if (router_nickname_matches(router, cp)) {v=1;break;});
  521. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  522. smartlist_free(nickname_list);
  523. return v;
  524. }
  525. /** Add every router from our routerlist that is currently running to
  526. * <b>sl</b>.
  527. */
  528. static void
  529. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
  530. int need_uptime, int need_capacity)
  531. {
  532. if (!routerlist)
  533. return;
  534. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  535. {
  536. if (router->is_running &&
  537. (router->is_verified ||
  538. (allow_unverified &&
  539. !router_is_unreliable(router, need_uptime, need_capacity)))) {
  540. /* If it's running, and either it's verified or we're ok picking
  541. * unverified routers and this one is suitable.
  542. */
  543. smartlist_add(sl, router);
  544. }
  545. });
  546. }
  547. /** Look through the routerlist until we find a router that has my key.
  548. Return it. */
  549. routerinfo_t *
  550. routerlist_find_my_routerinfo(void)
  551. {
  552. if (!routerlist)
  553. return NULL;
  554. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  555. {
  556. if (router_is_me(router))
  557. return router;
  558. });
  559. return NULL;
  560. }
  561. /** Find a router that's up, that has this IP address, and
  562. * that allows exit to this address:port, or return NULL if there
  563. * isn't a good one.
  564. */
  565. routerinfo_t *
  566. router_find_exact_exit_enclave(const char *address, uint16_t port)
  567. {
  568. uint32_t addr;
  569. struct in_addr in;
  570. if (!tor_inet_aton(address, &in))
  571. return NULL; /* it's not an IP already */
  572. addr = ntohl(in.s_addr);
  573. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  574. {
  575. if (router->is_running &&
  576. router->addr == addr &&
  577. router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  578. ADDR_POLICY_ACCEPTED)
  579. return router;
  580. });
  581. return NULL;
  582. }
  583. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  584. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  585. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  586. * bandwidth.
  587. */
  588. int
  589. router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
  590. {
  591. if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
  592. return 1;
  593. if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  594. return 1;
  595. return 0;
  596. }
  597. /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
  598. static void
  599. routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
  600. {
  601. int i;
  602. routerinfo_t *router;
  603. for (i = 0; i < smartlist_len(sl); ++i) {
  604. router = smartlist_get(sl, i);
  605. if (router_is_unreliable(router, 1, 0)) {
  606. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  607. // router->nickname);
  608. smartlist_del(sl, i--);
  609. }
  610. }
  611. }
  612. #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
  613. /** Choose a random element of router list <b>sl</b>, weighted by
  614. * the advertised bandwidth of each router.
  615. */
  616. routerinfo_t *
  617. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  618. {
  619. int i;
  620. routerinfo_t *router;
  621. smartlist_t *bandwidths;
  622. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  623. uint32_t *p;
  624. /* First count the total bandwidth weight, and make a smartlist
  625. * of each value. */
  626. bandwidths = smartlist_create();
  627. for (i = 0; i < smartlist_len(sl); ++i) {
  628. router = smartlist_get(sl, i);
  629. this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
  630. router->bandwidthcapacity : router->bandwidthrate;
  631. /* if they claim something huge, don't believe it */
  632. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  633. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  634. p = tor_malloc(sizeof(uint32_t));
  635. *p = this_bw;
  636. smartlist_add(bandwidths, p);
  637. total_bw += this_bw;
  638. }
  639. if (!total_bw) {
  640. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  641. smartlist_free(bandwidths);
  642. return smartlist_choose(sl);
  643. }
  644. /* Second, choose a random value from the bandwidth weights. */
  645. rand_bw = crypto_pseudo_rand_int(total_bw);
  646. /* Last, count through sl until we get to the element we picked */
  647. tmp = 0;
  648. for (i=0; ; i++) {
  649. tor_assert(i < smartlist_len(sl));
  650. p = smartlist_get(bandwidths, i);
  651. tmp += *p;
  652. if (tmp >= rand_bw)
  653. break;
  654. }
  655. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  656. smartlist_free(bandwidths);
  657. return (routerinfo_t *)smartlist_get(sl, i);
  658. }
  659. /** Return a random running router from the routerlist. If any node
  660. * named in <b>preferred</b> is available, pick one of those. Never
  661. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  662. * <b>excludedsmartlist</b>, even if they are the only nodes
  663. * available. If <b>strict</b> is true, never pick any node besides
  664. * those in <b>preferred</b>.
  665. * If <b>need_uptime</b> is non-zero, don't return a router with less
  666. * than a minimum uptime.
  667. * If <b>need_capacity</b> is non-zero, weight your choice by the
  668. * advertised capacity of each router.
  669. */
  670. routerinfo_t *
  671. router_choose_random_node(const char *preferred,
  672. const char *excluded,
  673. smartlist_t *excludedsmartlist,
  674. int need_uptime, int need_capacity,
  675. int allow_unverified, int strict)
  676. {
  677. smartlist_t *sl, *excludednodes;
  678. routerinfo_t *choice;
  679. excludednodes = smartlist_create();
  680. add_nickname_list_to_smartlist(excludednodes,excluded,0);
  681. /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
  682. * since the user explicitly asked for these nodes. */
  683. sl = smartlist_create();
  684. add_nickname_list_to_smartlist(sl,preferred,1);
  685. smartlist_subtract(sl,excludednodes);
  686. if (excludedsmartlist)
  687. smartlist_subtract(sl,excludedsmartlist);
  688. choice = smartlist_choose(sl);
  689. smartlist_free(sl);
  690. if (!choice && !strict) {
  691. /* Then give up on our preferred choices: any node
  692. * will do that has the required attributes. */
  693. sl = smartlist_create();
  694. router_add_running_routers_to_smartlist(sl, allow_unverified,
  695. need_uptime, need_capacity);
  696. smartlist_subtract(sl,excludednodes);
  697. if (excludedsmartlist)
  698. smartlist_subtract(sl,excludedsmartlist);
  699. if (need_uptime)
  700. routerlist_sl_remove_unreliable_routers(sl);
  701. if (need_capacity)
  702. choice = routerlist_sl_choose_by_bandwidth(sl);
  703. else
  704. choice = smartlist_choose(sl);
  705. smartlist_free(sl);
  706. }
  707. smartlist_free(excludednodes);
  708. if (!choice)
  709. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  710. return choice;
  711. }
  712. /** Return true iff the digest of <b>router</b>'s identity key,
  713. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  714. * optionally prefixed with a single dollar sign). Return false if
  715. * <b>hexdigest</b> is malformed, or it doesn't match. */
  716. static INLINE int
  717. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  718. {
  719. char digest[DIGEST_LEN];
  720. tor_assert(hexdigest);
  721. if (hexdigest[0] == '$')
  722. ++hexdigest;
  723. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  724. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  725. return 0;
  726. return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
  727. }
  728. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  729. * (case-insensitive), or if <b>router's</b> identity key digest
  730. * matches a hexadecimal value stored in <b>nickname</b>. Return
  731. * false otherwise. */
  732. static int
  733. router_nickname_matches(routerinfo_t *router, const char *nickname)
  734. {
  735. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  736. return 1;
  737. return router_hex_digest_matches(router, nickname);
  738. }
  739. /** Return the router in our routerlist whose (case-insensitive)
  740. * nickname or (case-sensitive) hexadecimal key digest is
  741. * <b>nickname</b>. Return NULL if no such router is known.
  742. */
  743. routerinfo_t *
  744. router_get_by_nickname(const char *nickname)
  745. {
  746. int maybedigest;
  747. char digest[DIGEST_LEN];
  748. tor_assert(nickname);
  749. if (!routerlist)
  750. return NULL;
  751. if (nickname[0] == '$')
  752. return router_get_by_hexdigest(nickname);
  753. if (server_mode(get_options()) &&
  754. !strcasecmp(nickname, get_options()->Nickname))
  755. return router_get_my_routerinfo();
  756. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  757. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  758. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  759. {
  760. /* XXXX011 NM Should this restrict by Named rouers, or warn on
  761. * non-named routers, or something? */
  762. if (0 == strcasecmp(router->nickname, nickname) ||
  763. (maybedigest && 0 == memcmp(digest, router->identity_digest,
  764. DIGEST_LEN)))
  765. return router;
  766. });
  767. return NULL;
  768. }
  769. /** Return true iff <b>digest</b> is the digest of the identity key of
  770. * a trusted directory. */
  771. int
  772. router_digest_is_trusted_dir(const char *digest)
  773. {
  774. if (!trusted_dir_servers)
  775. return 0;
  776. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  777. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  778. return 0;
  779. }
  780. /** Return the router in our routerlist whose hexadecimal key digest
  781. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  782. routerinfo_t *
  783. router_get_by_hexdigest(const char *hexdigest)
  784. {
  785. char digest[DIGEST_LEN];
  786. tor_assert(hexdigest);
  787. if (!routerlist)
  788. return NULL;
  789. if (hexdigest[0]=='$')
  790. ++hexdigest;
  791. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  792. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  793. return NULL;
  794. return router_get_by_digest(digest);
  795. }
  796. /** Return the router in our routerlist whose 20-byte key digest
  797. * is <b>digest</b>. Return NULL if no such router is known. */
  798. routerinfo_t *
  799. router_get_by_digest(const char *digest)
  800. {
  801. tor_assert(digest);
  802. if (!routerlist) return NULL;
  803. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t*, router,
  804. {
  805. if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
  806. return router;
  807. });
  808. return NULL;
  809. }
  810. /** Set *<b>prouterlist</b> to the current list of all known routers. */
  811. void
  812. router_get_routerlist(routerlist_t **prouterlist)
  813. {
  814. *prouterlist = routerlist;
  815. }
  816. /** Free all storage held by <b>router</b>. */
  817. void
  818. routerinfo_free(routerinfo_t *router)
  819. {
  820. if (!router)
  821. return;
  822. tor_free(router->signed_descriptor);
  823. tor_free(router->address);
  824. tor_free(router->nickname);
  825. tor_free(router->platform);
  826. tor_free(router->contact_info);
  827. if (router->onion_pkey)
  828. crypto_free_pk_env(router->onion_pkey);
  829. if (router->identity_pkey)
  830. crypto_free_pk_env(router->identity_pkey);
  831. if (router->declared_family) {
  832. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  833. smartlist_free(router->declared_family);
  834. }
  835. addr_policy_free(router->exit_policy);
  836. tor_free(router);
  837. }
  838. /** Allocate a fresh copy of <b>router</b> */
  839. routerinfo_t *
  840. routerinfo_copy(const routerinfo_t *router)
  841. {
  842. routerinfo_t *r;
  843. addr_policy_t **e, *tmp;
  844. r = tor_malloc(sizeof(routerinfo_t));
  845. memcpy(r, router, sizeof(routerinfo_t));
  846. r->address = tor_strdup(r->address);
  847. r->nickname = tor_strdup(r->nickname);
  848. r->platform = tor_strdup(r->platform);
  849. if (r->signed_descriptor)
  850. r->signed_descriptor = tor_strdup(r->signed_descriptor);
  851. if (r->onion_pkey)
  852. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  853. if (r->identity_pkey)
  854. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  855. e = &r->exit_policy;
  856. while (*e) {
  857. tmp = tor_malloc(sizeof(addr_policy_t));
  858. memcpy(tmp,*e,sizeof(addr_policy_t));
  859. *e = tmp;
  860. (*e)->string = tor_strdup((*e)->string);
  861. e = & ((*e)->next);
  862. }
  863. if (r->declared_family) {
  864. r->declared_family = smartlist_create();
  865. SMARTLIST_FOREACH(router->declared_family, const char *, s,
  866. smartlist_add(r->declared_family, tor_strdup(s)));
  867. }
  868. return r;
  869. }
  870. /** Free all storage held by a routerlist <b>rl</b> */
  871. void
  872. routerlist_free(routerlist_t *rl)
  873. {
  874. tor_assert(rl);
  875. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  876. routerinfo_free(r));
  877. smartlist_free(rl->routers);
  878. tor_free(rl);
  879. }
  880. /** Free all memory held by the rouerlist module */
  881. void
  882. routerlist_free_all(void)
  883. {
  884. if (routerlist)
  885. routerlist_free(routerlist);
  886. routerlist = NULL;
  887. if (warned_nicknames) {
  888. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  889. smartlist_free(warned_nicknames);
  890. warned_nicknames = NULL;
  891. }
  892. if (trusted_dir_servers) {
  893. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  894. { tor_free(ds->address); tor_free(ds); });
  895. smartlist_free(trusted_dir_servers);
  896. trusted_dir_servers = NULL;
  897. }
  898. if (networkstatus_list) {
  899. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  900. networkstatus_free(ns));
  901. smartlist_free(networkstatus_list);
  902. networkstatus_list = NULL;
  903. }
  904. }
  905. /** Free all storage held by the routerstatus object <b>rs</b>. */
  906. void
  907. routerstatus_free(routerstatus_t *rs)
  908. {
  909. tor_free(rs);
  910. }
  911. /** Free all storage held by the networkstatus object <b>ns</b>. */
  912. void
  913. networkstatus_free(networkstatus_t *ns)
  914. {
  915. tor_free(ns->source_address);
  916. tor_free(ns->contact);
  917. if (ns->signing_key)
  918. crypto_free_pk_env(ns->signing_key);
  919. tor_free(ns->client_versions);
  920. tor_free(ns->server_versions);
  921. if (ns->entries) {
  922. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
  923. smartlist_free(ns->entries);
  924. }
  925. tor_free(ns);
  926. }
  927. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  928. void
  929. router_mark_as_down(const char *digest)
  930. {
  931. routerinfo_t *router;
  932. tor_assert(digest);
  933. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  934. if (!memcmp(d->digest, digest, DIGEST_LEN))
  935. d->is_running = 0);
  936. router = router_get_by_digest(digest);
  937. if (!router) /* we don't seem to know about him in the first place */
  938. return;
  939. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  940. if (router_is_me(router) && !we_are_hibernating())
  941. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  942. router->is_running = 0;
  943. }
  944. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  945. * older entries (if any) with the same key. Note: Callers should not hold
  946. * their pointers to <b>router</b> if this function fails; <b>router</b>
  947. * will either be inserted into the routerlist or freed.
  948. *
  949. * Returns >= 0 if the router was added; less than 0 if it was not.
  950. *
  951. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  952. * describing the reason for not liking the routerinfo.
  953. *
  954. * If the return value is less than -1, there was a problem with the
  955. * routerinfo. If the return value is equal to -1, then the routerinfo was
  956. * fine, but out-of-date. If the return value is equal to 1, the
  957. * routerinfo was accepted, but we should notify the generator of the
  958. * descriptor using the message *<b>msg</b>.
  959. *
  960. * This function should be called *after*
  961. * routers_update_status_from_networkstatus; subsequenctly, you should call
  962. * router_rebuild_store and control_event_descriptors_changed.
  963. *
  964. * XXXX never replace your own descriptor.
  965. */
  966. int
  967. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  968. int from_cache)
  969. {
  970. int i;
  971. char id_digest[DIGEST_LEN];
  972. int authdir = get_options()->AuthoritativeDir;
  973. int authdir_verified = 0;
  974. tor_assert(msg);
  975. if (!routerlist) {
  976. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  977. routerlist->routers = smartlist_create();
  978. }
  979. crypto_pk_get_digest(router->identity_pkey, id_digest);
  980. if (authdir) {
  981. if (authdir_wants_to_reject_router(router, msg))
  982. return -2;
  983. authdir_verified = router->is_verified;
  984. }
  985. /* If we have a router with this name, and the identity key is the same,
  986. * choose the newer one. If the identity key has changed, drop the router.
  987. */
  988. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  989. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  990. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  991. if (router->published_on <= old_router->published_on) {
  992. /* Same key, but old */
  993. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  994. router->nickname);
  995. routerinfo_free(router);
  996. *msg = "Router descriptor was not new.";
  997. return -1;
  998. } else {
  999. /* Same key, new. */
  1000. int unreachable = 0;
  1001. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  1002. router->nickname, old_router->nickname,
  1003. hex_str(id_digest,DIGEST_LEN));
  1004. if (router->addr == old_router->addr &&
  1005. router->or_port == old_router->or_port) {
  1006. /* these carry over when the address and orport are unchanged.*/
  1007. router->last_reachable = old_router->last_reachable;
  1008. router->testing_since = old_router->testing_since;
  1009. router->num_unreachable_notifications =
  1010. old_router->num_unreachable_notifications;
  1011. }
  1012. if (authdir &&
  1013. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  1014. if (router->num_unreachable_notifications >= 3) {
  1015. unreachable = 1;
  1016. log_fn(LOG_NOTICE, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
  1017. router->nickname, router->contact_info ? router->contact_info : "",
  1018. router->platform ? router->platform : "");
  1019. } else {
  1020. log_fn(LOG_INFO,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
  1021. router->num_unreachable_notifications++;
  1022. }
  1023. }
  1024. routerinfo_free(old_router);
  1025. smartlist_set(routerlist->routers, i, router);
  1026. if (!from_cache)
  1027. router_append_to_journal(router->signed_descriptor,
  1028. router->signed_descriptor_len);
  1029. directory_set_dirty();
  1030. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1031. authdir_verified ? "Verified server updated" :
  1032. "Unverified server updated. (Have you sent us your key fingerprint?)";
  1033. return unreachable ? 1 : 0;
  1034. }
  1035. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1036. /* nicknames match, keys don't. */
  1037. if (router->is_named) {
  1038. /* The new verified router replaces the old one; remove the
  1039. * old one. And carry on to the end of the list, in case
  1040. * there are more old unverified routers with this nickname
  1041. */
  1042. /* mark-for-close connections using the old key, so we can
  1043. * make new ones with the new key.
  1044. */
  1045. connection_t *conn;
  1046. while ((conn = connection_get_by_identity_digest(
  1047. old_router->identity_digest, CONN_TYPE_OR))) {
  1048. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
  1049. old_router->nickname);
  1050. connection_mark_for_close(conn);
  1051. }
  1052. routerinfo_free(old_router);
  1053. smartlist_del_keeporder(routerlist->routers, i--);
  1054. } else if (old_router->is_named) {
  1055. /* Can't replace a verified router with an unverified one. */
  1056. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  1057. router->nickname);
  1058. routerinfo_free(router);
  1059. *msg = "Already have verified router with same nickname and different key.";
  1060. return -2;
  1061. }
  1062. }
  1063. }
  1064. /* We haven't seen a router with this name before. Add it to the end of
  1065. * the list. */
  1066. smartlist_add(routerlist->routers, router);
  1067. if (!from_cache)
  1068. router_append_to_journal(router->signed_descriptor,
  1069. router->signed_descriptor_len);
  1070. directory_set_dirty();
  1071. return 0;
  1072. }
  1073. /** Remove any routers from the routerlist that are more than <b>age</b>
  1074. * seconds old.
  1075. */
  1076. void
  1077. routerlist_remove_old_routers(int age)
  1078. {
  1079. int i;
  1080. time_t cutoff;
  1081. routerinfo_t *router;
  1082. if (!routerlist)
  1083. return;
  1084. cutoff = time(NULL) - age;
  1085. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1086. router = smartlist_get(routerlist->routers, i);
  1087. if (router->published_on <= cutoff) {
  1088. /* Too old. Remove it. */
  1089. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  1090. routerinfo_free(router);
  1091. smartlist_del(routerlist->routers, i--);
  1092. }
  1093. }
  1094. }
  1095. /**
  1096. * Code to parse a single router descriptor and insert it into the
  1097. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1098. * descriptor was well-formed but could not be added; and 1 if the
  1099. * descriptor was added.
  1100. *
  1101. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1102. * *<b>msg</b> a static string describing the reason for refusing the
  1103. * descriptor.
  1104. *
  1105. * This is used only by the controller.
  1106. */
  1107. int
  1108. router_load_single_router(const char *s, const char **msg)
  1109. {
  1110. routerinfo_t *ri;
  1111. tor_assert(msg);
  1112. *msg = NULL;
  1113. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  1114. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  1115. *msg = "Couldn't parse router descriptor.";
  1116. return -1;
  1117. }
  1118. if (router_is_me(ri)) {
  1119. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  1120. *msg = "Router's identity key matches mine.";
  1121. routerinfo_free(ri);
  1122. return 0;
  1123. }
  1124. /* XXXX011 update router status from networkstatus!! */
  1125. if (router_add_to_routerlist(ri, msg, 0)<0) {
  1126. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  1127. *msg?*msg:"(No message).");
  1128. /* we've already assigned to *msg now, and ri is already freed */
  1129. return 0;
  1130. } else {
  1131. smartlist_t *changed = smartlist_create();
  1132. smartlist_add(changed, ri);
  1133. control_event_descriptors_changed(changed);
  1134. smartlist_free(changed);
  1135. }
  1136. log_fn(LOG_DEBUG, "Added router to list");
  1137. return 1;
  1138. }
  1139. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1140. * routers into our directory. If <b>from_cache</b> is false, the routers
  1141. * have come from the network: cache them.
  1142. *
  1143. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1144. * uppercased identity fingerprints. Do not update any router whose
  1145. * fingerprint is not on the list; after updating a router, remove its
  1146. * fingerprint from the list.
  1147. */
  1148. void
  1149. router_load_routers_from_string(const char *s, int from_cache,
  1150. smartlist_t *requested_fingerprints)
  1151. {
  1152. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1153. char fp[HEX_DIGEST_LEN+1];
  1154. const char *msg;
  1155. router_parse_list_from_string(&s, routers);
  1156. routers_update_status_from_networkstatus(routers, !from_cache);
  1157. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1158. {
  1159. base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
  1160. if (requested_fingerprints) {
  1161. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1162. smartlist_string_remove(requested_fingerprints, fp);
  1163. } else {
  1164. char *requested =
  1165. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1166. log_fn(LOG_WARN, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1167. tor_free(requested);
  1168. routerinfo_free(ri);
  1169. continue;
  1170. }
  1171. }
  1172. if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
  1173. smartlist_add(changed, ri);
  1174. });
  1175. control_event_descriptors_changed(changed);
  1176. router_rebuild_store(0);
  1177. smartlist_free(routers);
  1178. smartlist_free(changed);
  1179. }
  1180. /** Helper: return a newly allocated string containing the name of the filename
  1181. * where we plan to cache <b>ns</b>. */
  1182. static char *
  1183. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1184. {
  1185. const char *datadir = get_options()->DataDirectory;
  1186. size_t len = strlen(datadir)+64;
  1187. char fp[HEX_DIGEST_LEN+1];
  1188. char *fn = tor_malloc(len+1);
  1189. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1190. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1191. return fn;
  1192. }
  1193. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1194. * publication date. */
  1195. static int
  1196. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1197. {
  1198. const networkstatus_t *a = *_a, *b = *_b;
  1199. if (a->published_on < b->published_on)
  1200. return -1;
  1201. else if (a->published_on > b->published_on)
  1202. return 1;
  1203. else
  1204. return 0;
  1205. }
  1206. /** How far in the future do we allow a network-status to get before removing
  1207. * it? (seconds) */
  1208. #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
  1209. /** Given a string <b>s</b> containing a network status that we received at
  1210. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1211. * store it, and put it into our cache is necessary.
  1212. *
  1213. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1214. * own networkstatus_t (if we're a directory server).
  1215. *
  1216. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1217. * cache.
  1218. *
  1219. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1220. * uppercased identity fingerprints. Do not update any networkstatus whose
  1221. * fingerprint is not on the list; after updating a networkstatus, remove its
  1222. * fingerprint from the list.
  1223. *
  1224. * Return 0 on success, -1 on failure.
  1225. *
  1226. * Callers should make sure that routers_update_all_from_networkstatus() is
  1227. * invoked after this function succeeds.
  1228. */
  1229. int
  1230. router_set_networkstatus(const char *s, time_t arrived_at,
  1231. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1232. {
  1233. networkstatus_t *ns;
  1234. int i, found;
  1235. time_t now;
  1236. int skewed = 0;
  1237. trusted_dir_server_t *trusted_dir;
  1238. char fp[HEX_DIGEST_LEN+1];
  1239. char published[ISO_TIME_LEN+1];
  1240. ns = networkstatus_parse_from_string(s);
  1241. if (!ns) {
  1242. log_fn(LOG_WARN, "Couldn't parse network status.");
  1243. return -1;
  1244. }
  1245. if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  1246. log_fn(LOG_INFO, "Network status was signed, but not by an authoritative directory we recognize.");
  1247. networkstatus_free(ns);
  1248. return -1;
  1249. }
  1250. now = time(NULL);
  1251. if (arrived_at > now)
  1252. arrived_at = now;
  1253. ns->received_on = arrived_at;
  1254. format_iso_time(published, ns->published_on);
  1255. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1256. log_fn(LOG_WARN, "Network status was published in the future (%s GMT). Somebody is skewed here: check your clock. Not caching.", published);
  1257. skewed = 1;
  1258. }
  1259. if (!networkstatus_list)
  1260. networkstatus_list = smartlist_create();
  1261. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1262. /* Don't replace our own networkstatus when we get it from somebody else. */
  1263. networkstatus_free(ns);
  1264. return 0;
  1265. }
  1266. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1267. if (requested_fingerprints) {
  1268. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1269. smartlist_string_remove(requested_fingerprints, fp);
  1270. } else {
  1271. char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1272. log_fn(LOG_WARN, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1273. tor_free(requested);
  1274. return 0;
  1275. }
  1276. }
  1277. if (source != NS_FROM_CACHE)
  1278. trusted_dir->n_networkstatus_failures = 0;
  1279. found = 0;
  1280. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  1281. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  1282. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  1283. if (!memcmp(old_ns->networkstatus_digest,
  1284. ns->networkstatus_digest, DIGEST_LEN)) {
  1285. /* Same one we had before. */
  1286. networkstatus_free(ns);
  1287. log_fn(LOG_NOTICE,
  1288. "Dropping network-status from %s:%d (published %s); already have it.",
  1289. trusted_dir->address, trusted_dir->dir_port, published);
  1290. if (old_ns->received_on < arrived_at) {
  1291. if (source != NS_FROM_CACHE) {
  1292. char *fn = networkstatus_get_cache_filename(old_ns);
  1293. /* We use mtime to tell when it arrived, so update that. */
  1294. touch_file(fn);
  1295. tor_free(fn);
  1296. }
  1297. old_ns->received_on = arrived_at;
  1298. }
  1299. return 0;
  1300. } else if (old_ns->published_on >= ns->published_on) {
  1301. char old_published[ISO_TIME_LEN+1];
  1302. format_iso_time(old_published, old_ns->published_on);
  1303. log_fn(LOG_NOTICE,
  1304. "Dropping network-status from %s:%d (published %s);"
  1305. " we have a newer one (published %s) for this authority.",
  1306. trusted_dir->address, trusted_dir->dir_port, published,
  1307. old_published);
  1308. networkstatus_free(ns);
  1309. return 0;
  1310. } else {
  1311. networkstatus_free(old_ns);
  1312. smartlist_set(networkstatus_list, i, ns);
  1313. found = 1;
  1314. break;
  1315. }
  1316. }
  1317. }
  1318. if (!found)
  1319. smartlist_add(networkstatus_list, ns);
  1320. /*XXXX011 downgrade to INFO NM */
  1321. log_fn(LOG_NOTICE, "Setting networkstatus %s %s:%d (published %s)",
  1322. source == NS_FROM_CACHE?"cached from":
  1323. (source==NS_FROM_DIR?"downloaded from":"generated for"),
  1324. trusted_dir->address, trusted_dir->dir_port, published);
  1325. networkstatus_list_has_changed = 1;
  1326. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  1327. if (source != NS_FROM_CACHE && !skewed) {
  1328. char *fn = networkstatus_get_cache_filename(ns);
  1329. if (write_str_to_file(fn, s, 0)<0) {
  1330. log_fn(LOG_NOTICE, "Couldn't write cached network status to \"%s\"", fn);
  1331. }
  1332. tor_free(fn);
  1333. }
  1334. networkstatus_list_update_recent(now);
  1335. if (get_options()->DirPort && !skewed)
  1336. dirserv_set_cached_networkstatus_v2(s, fp, ns->published_on);
  1337. return 0;
  1338. }
  1339. /** How old do we allow a network-status to get before removing it completely? */
  1340. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  1341. /** Remove all very-old network_status_t objects from memory and from the
  1342. * disk cache. */
  1343. void
  1344. networkstatus_list_clean(time_t now)
  1345. {
  1346. int i;
  1347. if (!networkstatus_list)
  1348. return;
  1349. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  1350. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  1351. char *fname = NULL;;
  1352. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  1353. continue;
  1354. /* Okay, this one is too old. Remove it from the list, and delete it
  1355. * from the cache. */
  1356. smartlist_del(networkstatus_list, i--);
  1357. fname = networkstatus_get_cache_filename(ns);
  1358. if (file_status(fname) == FN_FILE) {
  1359. log_fn(LOG_INFO, "Removing too-old networkstatus in %s", fname);
  1360. unlink(fname);
  1361. }
  1362. tor_free(fname);
  1363. if (get_options()->DirPort) {
  1364. char fp[HEX_DIGEST_LEN+1];
  1365. base16_encode(fp, sizeof(fp), ns->identity_digest, DIGEST_LEN);
  1366. dirserv_set_cached_networkstatus_v2(NULL, fp, 0);
  1367. }
  1368. networkstatus_free(ns);
  1369. }
  1370. }
  1371. /** Helper for bsearching a list of routerstatus_t pointers.*/
  1372. static int
  1373. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  1374. {
  1375. const char *key = _key;
  1376. const routerstatus_t *rs = *_member;
  1377. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  1378. }
  1379. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  1380. * NULL if none was found. */
  1381. static routerstatus_t *
  1382. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  1383. {
  1384. return smartlist_bsearch(ns->entries, digest,
  1385. _compare_digest_to_routerstatus_entry);
  1386. }
  1387. /*DOCDOC*/
  1388. local_routerstatus_t *
  1389. router_get_combined_status_by_digest(const char *digest)
  1390. {
  1391. if (!routerstatus_list)
  1392. return NULL;
  1393. return smartlist_bsearch(routerstatus_list, digest,
  1394. _compare_digest_to_routerstatus_entry);
  1395. }
  1396. /* XXXX These should be configurable, perhaps? NM */
  1397. #define AUTHORITY_NS_CACHE_INTERVAL 10*60
  1398. #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
  1399. /** We are a directory server, and so cache network_status documents.
  1400. * Initiate downloads as needed to update them. For authorities, this means
  1401. * asking each trusted directory for its network-status. For caches, this means
  1402. * asking a random authority for all network-statuses.
  1403. */
  1404. void
  1405. update_networkstatus_cache_downloads(time_t now)
  1406. {
  1407. static time_t last_downloaded = 0;
  1408. int authority = authdir_mode(get_options());
  1409. int interval =
  1410. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  1411. /*XXXXX NM we should retry on failure. */
  1412. if (last_downloaded + interval >= now)
  1413. return;
  1414. if (!trusted_dir_servers)
  1415. return;
  1416. last_downloaded = now;
  1417. if (authority) {
  1418. /* An authority launches a separate connection for everybody. */
  1419. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1420. {
  1421. char resource[HEX_DIGEST_LEN+6];
  1422. if (router_digest_is_me(ds->digest))
  1423. continue;
  1424. if (connection_get_by_type_addr_port_purpose(
  1425. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  1426. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  1427. /* We are already fetching this one. */
  1428. continue;
  1429. }
  1430. strlcpy(resource, "fp/", sizeof(resource));
  1431. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  1432. strlcat(resource, ".z", sizeof(resource));
  1433. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
  1434. });
  1435. } else {
  1436. /* A non-authority cache launches one connection to a random authority. */
  1437. /* (Check whether we're currently fetching network-status objects.) */
  1438. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  1439. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1440. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  1441. }
  1442. }
  1443. /*XXXX Should these be configurable? NM*/
  1444. /** How old (in seconds) can a network-status be before we try replacing it? */
  1445. #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
  1446. /** How long (in seconds) does a client wait after getting a network status
  1447. * before downloading the next in sequence? */
  1448. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  1449. /* How many times do we allow a networkstatus download to fail before we
  1450. * assume that the authority isn't publishing? */
  1451. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  1452. /** We are not a directory cache or authority. Update our network-status list
  1453. * by launching a new directory fetch for enough network-status documents "as
  1454. * necessary". See function comments for implementation details.
  1455. */
  1456. void
  1457. update_networkstatus_client_downloads(time_t now)
  1458. {
  1459. int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
  1460. int most_recent_idx = -1;
  1461. trusted_dir_server_t *most_recent = NULL;
  1462. time_t most_recent_received = 0;
  1463. char *resource, *cp;
  1464. size_t resource_len;
  1465. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  1466. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1467. return;
  1468. /* This is a little tricky. We want to download enough network-status
  1469. * objects so that we have at least half of them under
  1470. * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
  1471. * *one* if the most recent one's publication time is under
  1472. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  1473. */
  1474. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  1475. return;
  1476. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  1477. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1478. {
  1479. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  1480. if (!ns)
  1481. continue;
  1482. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  1483. --n_running_dirservers;
  1484. continue;
  1485. }
  1486. if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
  1487. ++n_live;
  1488. if (!most_recent || ns->received_on > most_recent_received) {
  1489. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  1490. most_recent = ds;
  1491. most_recent_received = ns->received_on;
  1492. }
  1493. });
  1494. /* Download enough so we have at least half live, but no more than all the
  1495. * trusted dirservers we know.
  1496. */
  1497. if (n_live < (n_dirservers/2)+1)
  1498. needed = (n_dirservers/2)+1-n_live;
  1499. if (needed > n_running_dirservers)
  1500. needed = n_running_dirservers;
  1501. if (needed)
  1502. /* XXXX011 Downgrade to info NM */
  1503. log_fn(LOG_NOTICE, "For %d/%d running directory servers, we have %d live"
  1504. " network-status documents. Downloading %d.",
  1505. n_running_dirservers, n_dirservers, n_live, needed);
  1506. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  1507. if (n_running_dirservers &&
  1508. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
  1509. const char *addr = most_recent?most_recent->address:"nobody";
  1510. int port = most_recent?most_recent->dir_port:0;
  1511. log_fn(LOG_NOTICE, "Our most recent network-status document (from %s:%d) "
  1512. "is %d seconds old; downloading another.",
  1513. addr, port, (int)(now-most_recent_received));
  1514. needed = 1;
  1515. }
  1516. if (!needed)
  1517. return;
  1518. /* If no networkstatus was found, choose a dirserver at random as "most
  1519. * recent". */
  1520. if (most_recent_idx<0)
  1521. most_recent_idx = crypto_pseudo_rand_int(n_dirservers);
  1522. /* Build a request string for all the resources we want. */
  1523. resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
  1524. resource = tor_malloc(resource_len);
  1525. memcpy(resource, "fp/", 3);
  1526. cp = resource+3;
  1527. for (i = most_recent_idx+1; needed; ++i) {
  1528. trusted_dir_server_t *ds;
  1529. if (i >= n_dirservers)
  1530. i = 0;
  1531. ds = smartlist_get(trusted_dir_servers, i);
  1532. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
  1533. continue;
  1534. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1535. cp += HEX_DIGEST_LEN;
  1536. --needed;
  1537. if (needed)
  1538. *cp++ = '+';
  1539. }
  1540. memcpy(cp, ".z", 3);
  1541. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  1542. tor_free(resource);
  1543. }
  1544. /** Decide whether a given addr:port is definitely accepted,
  1545. * definitely rejected, probably accepted, or probably rejected by a
  1546. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1547. * target address. If <b>port</b> is 0, we don't know the port of the
  1548. * target address.
  1549. *
  1550. * For now, the algorithm is pretty simple: we look for definite and
  1551. * uncertain matches. The first definite match is what we guess; if
  1552. * it was preceded by no uncertain matches of the opposite policy,
  1553. * then the guess is definite; otherwise it is probable. (If we
  1554. * have a known addr and port, all matches are definite; if we have an
  1555. * unknown addr/port, any address/port ranges other than "all" are
  1556. * uncertain.)
  1557. *
  1558. * We could do better by assuming that some ranges never match typical
  1559. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1560. */
  1561. addr_policy_result_t
  1562. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1563. addr_policy_t *policy)
  1564. {
  1565. int maybe_reject = 0;
  1566. int maybe_accept = 0;
  1567. int match = 0;
  1568. int maybe = 0;
  1569. addr_policy_t *tmpe;
  1570. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1571. maybe = 0;
  1572. if (!addr) {
  1573. /* Address is unknown. */
  1574. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1575. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1576. /* The port definitely matches. */
  1577. if (tmpe->msk == 0) {
  1578. match = 1;
  1579. } else {
  1580. maybe = 1;
  1581. }
  1582. } else if (!port) {
  1583. /* The port maybe matches. */
  1584. maybe = 1;
  1585. }
  1586. } else {
  1587. /* Address is known */
  1588. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1589. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1590. /* Exact match for the policy */
  1591. match = 1;
  1592. } else if (!port) {
  1593. maybe = 1;
  1594. }
  1595. }
  1596. }
  1597. if (maybe) {
  1598. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1599. maybe_reject = 1;
  1600. else
  1601. maybe_accept = 1;
  1602. }
  1603. if (match) {
  1604. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1605. /* If we already hit a clause that might trigger a 'reject', than we
  1606. * can't be sure of this certain 'accept'.*/
  1607. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1608. } else {
  1609. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1610. }
  1611. }
  1612. }
  1613. /* accept all by default. */
  1614. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1615. }
  1616. /** Return 1 if all running sufficiently-stable routers will reject
  1617. * addr:port, return 0 if any might accept it. */
  1618. int
  1619. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1620. int need_uptime)
  1621. {
  1622. addr_policy_result_t r;
  1623. if (!routerlist) return 1;
  1624. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1625. {
  1626. if (router->is_running &&
  1627. !router_is_unreliable(router, need_uptime, 0)) {
  1628. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1629. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1630. return 0; /* this one could be ok. good enough. */
  1631. }
  1632. });
  1633. return 1; /* all will reject. */
  1634. }
  1635. /**
  1636. * If <b>policy</b> implicitly allows connections to any port in the
  1637. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1638. * part of the policy that allows it, and return 1. Else return 0.
  1639. *
  1640. * A policy allows an IP:Port combination <em>implicitly</em> if
  1641. * it is included in a *: pattern, or in a fallback pattern.
  1642. */
  1643. static int
  1644. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1645. uint32_t addr, uint32_t mask,
  1646. addr_policy_t **policy_out)
  1647. {
  1648. uint32_t addr2;
  1649. tor_assert(policy_out);
  1650. addr &= mask;
  1651. addr2 = addr | ~mask;
  1652. for (; policy; policy=policy->next) {
  1653. /* Does this policy cover all of the address range we're looking at? */
  1654. /* Boolean logic time: range X is contained in range Y if, for
  1655. * each bit B, all possible values of B in X are values of B in Y.
  1656. * In "addr", we have every fixed bit set to its value, and every
  1657. * free bit set to 0. In "addr2", we have every fixed bit set to
  1658. * its value, and every free bit set to 1. So if addr and addr2 are
  1659. * both in the policy, the range is covered by the policy.
  1660. */
  1661. uint32_t p_addr = policy->addr & policy->msk;
  1662. if (p_addr == (addr & policy->msk) &&
  1663. p_addr == (addr2 & policy->msk) &&
  1664. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1665. return 0;
  1666. }
  1667. /* Does this policy cover some of the address range we're looking at? */
  1668. /* Boolean logic time: range X and range Y intersect if there is
  1669. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1670. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1671. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1672. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1673. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1674. */
  1675. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1676. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1677. *policy_out = policy;
  1678. return 1;
  1679. }
  1680. }
  1681. *policy_out = NULL;
  1682. return 1;
  1683. }
  1684. /** If <b>policy</b> implicitly allows connections to any port on
  1685. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1686. * true. Else return false.
  1687. **/
  1688. int
  1689. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1690. int warn)
  1691. {
  1692. addr_policy_t *p;
  1693. int r=0,i;
  1694. static struct {
  1695. uint32_t addr; uint32_t mask; const char *network;
  1696. } private_networks[] = {
  1697. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1698. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1699. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1700. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1701. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1702. { 0,0,NULL},
  1703. };
  1704. for (i=0; private_networks[i].addr; ++i) {
  1705. p = NULL;
  1706. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1707. if (policy_includes_addr_mask_implicitly(
  1708. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1709. if (warn)
  1710. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1711. p?p->string:"(default)",
  1712. private_networks[i].network);
  1713. r = 1;
  1714. }
  1715. }
  1716. return r;
  1717. }
  1718. /** Return true iff <b>router</b> does not permit exit streams.
  1719. */
  1720. int
  1721. router_exit_policy_rejects_all(routerinfo_t *router)
  1722. {
  1723. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1724. == ADDR_POLICY_REJECTED;
  1725. }
  1726. /** Add to the list of authorized directory servers one at
  1727. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  1728. * <b>address</b> is NULL, add ourself. */
  1729. void
  1730. add_trusted_dir_server(const char *address, uint16_t port, const char *digest,
  1731. int supports_v1)
  1732. {
  1733. trusted_dir_server_t *ent;
  1734. uint32_t a;
  1735. char *hostname = NULL;
  1736. if (!trusted_dir_servers)
  1737. trusted_dir_servers = smartlist_create();
  1738. if (!address) { /* The address is us; we should guess. */
  1739. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  1740. log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
  1741. return;
  1742. }
  1743. } else {
  1744. if (tor_lookup_hostname(address, &a)) {
  1745. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1746. address);
  1747. return;
  1748. }
  1749. hostname = tor_strdup(address);
  1750. a = ntohl(a);
  1751. }
  1752. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  1753. ent->address = hostname;
  1754. ent->addr = a;
  1755. ent->dir_port = port;
  1756. ent->is_running = 1;
  1757. ent->supports_v1_protocol = supports_v1;
  1758. memcpy(ent->digest, digest, DIGEST_LEN);
  1759. smartlist_add(trusted_dir_servers, ent);
  1760. }
  1761. /** Remove all members from the list of trusted dir servers. */
  1762. void
  1763. clear_trusted_dir_servers(void)
  1764. {
  1765. if (trusted_dir_servers) {
  1766. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1767. { tor_free(ent->address); tor_free(ent); });
  1768. smartlist_clear(trusted_dir_servers);
  1769. } else {
  1770. trusted_dir_servers = smartlist_create();
  1771. }
  1772. }
  1773. /** Return the network status with a given identity digest. */
  1774. networkstatus_t *
  1775. networkstatus_get_by_digest(const char *digest)
  1776. {
  1777. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1778. {
  1779. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  1780. return ns;
  1781. });
  1782. return NULL;
  1783. }
  1784. /** If the network-status list has changed since the last time we called this
  1785. * function, update the status of every router from the network-status list.
  1786. */
  1787. void
  1788. routers_update_all_from_networkstatus(void)
  1789. {
  1790. #define SELF_OPINION_INTERVAL 90*60
  1791. static int have_warned_about_unverified_status = 0;
  1792. static int have_warned_about_old_version = 0;
  1793. static int have_warned_about_new_version = 0;
  1794. routerinfo_t *me;
  1795. time_t now;
  1796. if (!routerlist || !networkstatus_list ||
  1797. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  1798. return;
  1799. now = time(NULL);
  1800. if (networkstatus_list_has_changed)
  1801. routerstatus_list_update_from_networkstatus(now);
  1802. routers_update_status_from_networkstatus(routerlist->routers, 0);
  1803. me = router_get_my_routerinfo();
  1804. if (me && !have_warned_about_unverified_status) {
  1805. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
  1806. routerstatus_t *rs;
  1807. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1808. {
  1809. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  1810. continue;
  1811. ++n_recent;
  1812. if (!(rs = networkstatus_find_entry(ns, me->identity_digest)))
  1813. continue;
  1814. ++n_listing;
  1815. if (rs->is_valid)
  1816. ++n_valid;
  1817. if (rs->is_named)
  1818. ++n_named;
  1819. });
  1820. if (n_recent >= 2 && n_listing >= 2) {
  1821. if (n_valid <= n_recent/2) {
  1822. log_fn(LOG_WARN, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
  1823. n_recent-n_valid, n_recent);
  1824. have_warned_about_unverified_status = 1;
  1825. } else if (n_named <= n_recent/2) {
  1826. log_fn(LOG_WARN, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
  1827. n_recent-n_valid, n_recent);
  1828. have_warned_about_unverified_status = 1;
  1829. }
  1830. }
  1831. }
  1832. helper_nodes_set_status_from_directory();
  1833. if (!have_warned_about_old_version) {
  1834. int n_recent = 0;
  1835. int n_recommended = 0;
  1836. int is_server = server_mode(get_options());
  1837. version_status_t consensus = VS_RECOMMENDED;
  1838. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1839. {
  1840. version_status_t vs;
  1841. if (!ns->recommends_versions ||
  1842. ns->received_on + SELF_OPINION_INTERVAL < now )
  1843. continue;
  1844. vs = tor_version_is_obsolete(
  1845. VERSION, is_server ? ns->server_versions : ns->client_versions);
  1846. if (vs == VS_RECOMMENDED)
  1847. ++n_recommended;
  1848. if (n_recent++ == 0) {
  1849. consensus = vs;
  1850. } else if (consensus != vs) {
  1851. consensus = version_status_join(consensus, vs);
  1852. }
  1853. });
  1854. if (n_recent > 2 && n_recommended < n_recent/2) {
  1855. if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
  1856. if (!have_warned_about_new_version) {
  1857. log_fn(LOG_NOTICE, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
  1858. VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  1859. n_recent-n_recommended, n_recent);
  1860. have_warned_about_new_version = 1;
  1861. }
  1862. } else {
  1863. log_fn(LOG_NOTICE, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
  1864. VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
  1865. n_recent-n_recommended, n_recent);
  1866. have_warned_about_old_version = 1;
  1867. }
  1868. } else {
  1869. log_fn(LOG_INFO, "%d/%d recent directories think my version is ok.",
  1870. n_recommended, n_recent);
  1871. }
  1872. }
  1873. routerstatus_list_has_changed = 0;
  1874. }
  1875. /** Allow any network-status newer than this to influence our view of who's
  1876. * running. */
  1877. #define DEFAULT_RUNNING_INTERVAL 60*60
  1878. /** If possible, always allow at least this many network-statuses to influence
  1879. * our view of who's running. */
  1880. #define MIN_TO_INFLUENCE_RUNNING 3
  1881. /** DOCDOC */
  1882. void
  1883. networkstatus_list_update_recent(time_t now)
  1884. {
  1885. int n_statuses, n_recent, changed, i;
  1886. char published[ISO_TIME_LEN+1];
  1887. if (!networkstatus_list)
  1888. return;
  1889. n_statuses = smartlist_len(networkstatus_list);
  1890. n_recent = 0;
  1891. changed = 0;
  1892. for (i=n_statuses-1; i >= 0; --i) {
  1893. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  1894. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  1895. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  1896. if (!ns->is_recent) {
  1897. format_iso_time(published, ns->published_on);
  1898. log_fn(LOG_NOTICE,
  1899. "Networkstatus from %s:%d (published %s) is now \"recent\"",
  1900. ns->source_address, ns->source_dirport, published);
  1901. changed = 1;
  1902. }
  1903. ns->is_recent = 1;
  1904. ++n_recent;
  1905. } else {
  1906. if (ns->is_recent) {
  1907. format_iso_time(published, ns->published_on);
  1908. log_fn(LOG_NOTICE,
  1909. "Networkstatus from %s:%d (published %s) is no longer \"recent\"",
  1910. ns->source_address, ns->source_dirport, published);
  1911. changed = 1;
  1912. ns->is_recent = 0;
  1913. }
  1914. }
  1915. }
  1916. if (changed)
  1917. networkstatus_list_has_changed = 1;
  1918. }
  1919. /* DOCDOC */
  1920. static void
  1921. routerstatus_list_update_from_networkstatus(time_t now)
  1922. {
  1923. int n_trusted, n_statuses, n_recent=0, n_naming=0;
  1924. int n_distinct = 0;
  1925. int i;
  1926. int *index, *size;
  1927. networkstatus_t **networkstatus;
  1928. smartlist_t *result;
  1929. strmap_t *name_map;
  1930. char conflict[DIGEST_LEN];
  1931. networkstatus_list_update_recent(now);
  1932. if (!networkstatus_list_has_changed)
  1933. return;
  1934. if (!networkstatus_list)
  1935. networkstatus_list = smartlist_create();
  1936. if (!routerstatus_list)
  1937. routerstatus_list = smartlist_create();
  1938. if (!trusted_dir_servers)
  1939. trusted_dir_servers = smartlist_create();
  1940. n_trusted = smartlist_len(trusted_dir_servers);
  1941. n_statuses = smartlist_len(networkstatus_list);
  1942. if (n_statuses < (n_trusted/2)+1) {
  1943. /* Not enough statuses to adjust status. */
  1944. log_fn(LOG_NOTICE,"Not enough statuses to update router status list. (%d/%d)",
  1945. n_statuses, n_trusted);
  1946. return;
  1947. }
  1948. log_fn(LOG_NOTICE, "rebuilding router status list.");
  1949. index = tor_malloc(sizeof(int)*n_statuses);
  1950. size = tor_malloc(sizeof(int)*n_statuses);
  1951. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  1952. for (i = 0; i < n_statuses; ++i) {
  1953. index[i] = 0;
  1954. networkstatus[i] = smartlist_get(networkstatus_list, i);
  1955. size[i] = smartlist_len(networkstatus[i]->entries);
  1956. if (networkstatus[i]->binds_names)
  1957. ++n_naming;
  1958. if (networkstatus[i]->is_recent)
  1959. ++n_recent;
  1960. }
  1961. name_map = strmap_new();
  1962. memset(conflict, 0xff, sizeof(conflict));
  1963. for (i = 0; i < n_statuses; ++i) {
  1964. if (!networkstatus[i]->binds_names)
  1965. continue;
  1966. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  1967. {
  1968. const char *other_digest;
  1969. if (!rs->is_named)
  1970. continue;
  1971. other_digest = strmap_get_lc(name_map, rs->nickname);
  1972. if (!other_digest)
  1973. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  1974. else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  1975. other_digest != conflict) {
  1976. /*XXXX011 rate-limit this?*/
  1977. log_fn(LOG_WARN,
  1978. "Naming authorities disagree about which key goes with %s.",
  1979. rs->nickname);
  1980. strmap_set_lc(name_map, rs->nickname, conflict);
  1981. }
  1982. });
  1983. }
  1984. result = smartlist_create();
  1985. /* Iterate through all of the sorted routerstatus lists in step.
  1986. * Invariants:
  1987. * - For 0 <= i < n_statuses: index[i] is an index into
  1988. * networkstatus[i]->entries, which has size[i] elements.
  1989. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  1990. * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
  1991. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  1992. *
  1993. * (That is, the indices are always advanced past lower digest before
  1994. * higher.)
  1995. */
  1996. while (1) {
  1997. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  1998. const char *the_name = NULL;
  1999. local_routerstatus_t *rs_out, *rs_old;
  2000. routerstatus_t *rs, *most_recent;
  2001. networkstatus_t *ns;
  2002. const char *lowest = NULL;
  2003. /* Find out which of the digests appears first. */
  2004. for (i = 0; i < n_statuses; ++i) {
  2005. if (index[i] < size[i]) {
  2006. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  2007. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  2008. lowest = rs->identity_digest;
  2009. }
  2010. }
  2011. if (!lowest) {
  2012. /* We're out of routers. Great! */
  2013. break;
  2014. }
  2015. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  2016. * match "lowest" are next in order. Iterate over them, incrementing those
  2017. * index[i] as we go. */
  2018. ++n_distinct;
  2019. most_recent = NULL;
  2020. for (i = 0; i < n_statuses; ++i) {
  2021. if (index[i] >= size[i])
  2022. continue;
  2023. ns = networkstatus[i];
  2024. rs = smartlist_get(ns->entries, index[i]);
  2025. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  2026. continue;
  2027. ++index[i];
  2028. ++n_listing;
  2029. if (!most_recent || rs->published_on > most_recent->published_on)
  2030. most_recent = rs;
  2031. if (rs->is_named && ns->binds_names) {
  2032. if (!the_name)
  2033. the_name = rs->nickname;
  2034. if (!strcasecmp(rs->nickname, the_name)) {
  2035. ++n_named;
  2036. } else if (strcmp(the_name,"**mismatch**")) {
  2037. char hd[HEX_DIGEST_LEN+1];
  2038. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  2039. log_fn(LOG_WARN, "Naming authorities disagree about nicknames for $%s",
  2040. hd);
  2041. the_name = "**mismatch**";
  2042. }
  2043. }
  2044. if (rs->is_valid)
  2045. ++n_valid;
  2046. if (rs->is_running && ns->is_recent)
  2047. ++n_running;
  2048. }
  2049. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  2050. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  2051. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  2052. rs_out->n_download_failures = rs_old->n_download_failures;
  2053. rs_out->next_attempt_at = rs_old->next_attempt_at;
  2054. }
  2055. smartlist_add(result, rs_out);
  2056. log_fn(LOG_DEBUG, "Router '%s' is listed by %d/%d directories, "
  2057. "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
  2058. "think it's running.",
  2059. rs_out->status.nickname,
  2060. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  2061. n_running, n_recent);
  2062. rs_out->status.is_named = 0;
  2063. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  2064. const char *d = strmap_get_lc(name_map, the_name);
  2065. if (d && d != conflict)
  2066. rs_out->status.is_named = 1;
  2067. }
  2068. if (rs_out->status.is_named)
  2069. strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
  2070. rs_out->status.is_valid = n_valid > n_statuses/2;
  2071. rs_out->status.is_running = n_running > n_recent/2;
  2072. }
  2073. SMARTLIST_FOREACH(routerstatus_list, routerstatus_t *, rs,
  2074. routerstatus_free(rs));
  2075. smartlist_free(routerstatus_list);
  2076. routerstatus_list = result;
  2077. tor_free(networkstatus);
  2078. tor_free(index);
  2079. tor_free(size);
  2080. strmap_free(name_map, NULL);
  2081. networkstatus_list_has_changed = 0;
  2082. routerstatus_list_has_changed = 1;
  2083. }
  2084. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  2085. * is_named, is_verified, and is_running fields according to our current
  2086. * networkstatus_t documents. */
  2087. void
  2088. routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures)
  2089. {
  2090. trusted_dir_server_t *ds;
  2091. local_routerstatus_t *rs;
  2092. or_options_t *options = get_options();
  2093. int authdir = options->AuthoritativeDir;
  2094. int namingdir = options->NamingAuthoritativeDir;
  2095. if (!routerstatus_list)
  2096. return;
  2097. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  2098. {
  2099. rs = router_get_combined_status_by_digest(router->identity_digest);
  2100. ds = router_get_trusteddirserver_by_digest(router->identity_digest);
  2101. if (!rs)
  2102. continue;
  2103. if (reset_failures) {
  2104. rs->n_download_failures = 0;
  2105. rs->next_attempt_at = 0;
  2106. }
  2107. if (!namingdir)
  2108. router->is_named = rs->status.is_named;
  2109. if (!authdir) {
  2110. /* If we're an authdir, don't believe others. */
  2111. router->is_verified = rs->status.is_valid;
  2112. router->is_running = rs->status.is_running;
  2113. if (router->is_running && ds) {
  2114. /* XXXX011 NM Hm. What about authorities? When do they reset
  2115. * n_networkstatus_failures? */
  2116. ds->n_networkstatus_failures = 0;
  2117. }
  2118. }
  2119. });
  2120. }
  2121. /** Return new list of ID fingerprints for superseded routers. A router is
  2122. * superseded if any network-status has a router with a different digest
  2123. * published more recently, or it it is listed in the network-status but not
  2124. * in the router list.
  2125. */
  2126. static smartlist_t *
  2127. router_list_downloadable(void)
  2128. {
  2129. #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
  2130. int n_conns, i, n_downloadable = 0;
  2131. int n_uptodate=0,n_skip_old=0;
  2132. connection_t **carray;
  2133. smartlist_t *superseded = smartlist_create();
  2134. smartlist_t *downloading;
  2135. time_t now = time(NULL);
  2136. if (!routerstatus_list)
  2137. return superseded;
  2138. get_connection_array(&carray, &n_conns);
  2139. routerstatus_list_update_from_networkstatus(now);
  2140. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2141. {
  2142. if (rs->next_attempt_at < now) {
  2143. rs->should_download = 1;
  2144. ++n_downloadable;
  2145. } else {
  2146. /*
  2147. char fp[HEX_DIGEST_LEN+1];
  2148. base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
  2149. log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
  2150. (int)(rs->next_attempt_at-now));
  2151. */
  2152. rs->should_download = 0;
  2153. }
  2154. });
  2155. downloading = smartlist_create();
  2156. for (i = 0; i < n_conns; ++i) {
  2157. connection_t *conn = carray[i];
  2158. if (conn->type == CONN_TYPE_DIR &&
  2159. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  2160. !conn->marked_for_close) {
  2161. if (!strcmpstart(conn->requested_resource, "all"))
  2162. n_downloadable = 0;
  2163. dir_split_resource_into_fingerprints(conn->requested_resource,
  2164. downloading, NULL);
  2165. }
  2166. }
  2167. /*
  2168. log_fn(LOG_NOTICE, "%d downloads already in progress",
  2169. smartlist_len(downloading));
  2170. smartlist_sort_strings(downloading);
  2171. */
  2172. if (n_downloadable) {
  2173. SMARTLIST_FOREACH(downloading, const char *, dl,
  2174. {
  2175. char d[DIGEST_LEN];
  2176. local_routerstatus_t *rs;
  2177. base16_decode(d, DIGEST_LEN, dl, strlen(dl));
  2178. if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
  2179. rs->should_download = 0;
  2180. --n_downloadable;
  2181. // log_fn(LOG_NOTICE, "%s is in-progress; not fetching", dl);
  2182. }
  2183. });
  2184. }
  2185. SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
  2186. smartlist_free(downloading);
  2187. if (!n_downloadable)
  2188. return superseded;
  2189. if (routerlist) {
  2190. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  2191. {
  2192. local_routerstatus_t *rs;
  2193. if (!(rs = router_get_combined_status_by_digest(ri->identity_digest)) ||
  2194. !rs->should_download) {
  2195. // log_fn(LOG_NOTICE, "No status for %s", fp);
  2196. continue;
  2197. }
  2198. /* Change this "or" to be an "and" once dirs generate hashes right.
  2199. * Remove the version check once older versions are uncommon.
  2200. * XXXXX. NM */
  2201. if (!memcmp(ri->signed_descriptor_digest, rs->status.descriptor_digest,
  2202. DIGEST_LEN) ||
  2203. rs->status.published_on <= ri->published_on) {
  2204. ++n_uptodate;
  2205. rs->should_download = 0;
  2206. --n_downloadable;
  2207. } else if (ri->platform &&
  2208. !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
  2209. ri->published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
  2210. /* Same digest, or date is up-to-date, or we have a comparatively recent
  2211. * server with an old version.
  2212. * No need to download it. */
  2213. // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
  2214. ++n_skip_old;
  2215. rs->should_download = 0;
  2216. --n_downloadable;
  2217. } /* else {
  2218. char t1[ISO_TIME_LEN+1];
  2219. char t2[ISO_TIME_LEN+1];
  2220. format_iso_time(t1, rs->satus.published_on);
  2221. format_iso_time(t2, ri->published_on);
  2222. log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
  2223. ri->nickname,
  2224. !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
  2225. DIGEST_LEN),
  2226. rs->published_on < ri->published_on,
  2227. t1, t2);
  2228. } */
  2229. });
  2230. }
  2231. if (n_skip_old)
  2232. log_fn(LOG_INFO, "Skipped %d updatable pre-0.1.1.6 servers.", n_skip_old);
  2233. if (!n_downloadable)
  2234. return superseded;
  2235. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2236. {
  2237. if (rs->should_download) {
  2238. char *fp = tor_malloc(HEX_DIGEST_LEN+1);
  2239. base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
  2240. smartlist_add(superseded, fp);
  2241. }
  2242. });
  2243. return superseded;
  2244. }
  2245. /** Initiate new router downloads as needed.
  2246. *
  2247. * We only allow one router descriptor download at a time.
  2248. * If we have less than two network-status documents, we ask
  2249. * a directory for "all descriptors."
  2250. * Otherwise, we ask for all descriptors that we think are different
  2251. * from what we have.
  2252. */
  2253. void
  2254. update_router_descriptor_downloads(time_t now)
  2255. {
  2256. #define MAX_DL_PER_REQUEST 128
  2257. #define MIN_DL_PER_REQUEST 4
  2258. #define MIN_REQUESTS 3
  2259. smartlist_t *downloadable = NULL;
  2260. int get_all = 0;
  2261. int always_split = !server_mode(get_options()) || !get_options()->DirPort;
  2262. if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
  2263. get_all = 1;
  2264. if (get_all) {
  2265. log_fn(LOG_NOTICE, "Launching request for all routers");
  2266. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
  2267. return;
  2268. }
  2269. downloadable = router_list_downloadable();
  2270. if (smartlist_len(downloadable)) {
  2271. int i, j, n, n_per_request=MAX_DL_PER_REQUEST;
  2272. size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
  2273. char *resource = tor_malloc(r_len);
  2274. n = smartlist_len(downloadable);
  2275. if (always_split) {
  2276. n_per_request = (n+MIN_REQUESTS-1) / MIN_REQUESTS;
  2277. if (n_per_request > MAX_DL_PER_REQUEST)
  2278. n_per_request = MAX_DL_PER_REQUEST;
  2279. if (n_per_request < MIN_DL_PER_REQUEST)
  2280. n_per_request = MIN_DL_PER_REQUEST;
  2281. }
  2282. log_fn(LOG_NOTICE, "Launching %d request%s for %d router%s, %d at a time",
  2283. (n+n_per_request-1)/n_per_request, n>n_per_request?"s":"",
  2284. n, n>1?"s":"", n_per_request);
  2285. for (i=0; i < n; i += n_per_request) {
  2286. char *cp = resource;
  2287. memcpy(resource, "fp/", 3);
  2288. cp = resource + 3;
  2289. for (j=i; j < i+n_per_request && j < n; ++j) {
  2290. memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
  2291. cp += HEX_DIGEST_LEN;
  2292. *cp++ = '+';
  2293. }
  2294. memcpy(cp-1, ".z", 3);
  2295. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
  2296. }
  2297. tor_free(resource);
  2298. }
  2299. SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
  2300. smartlist_free(downloadable);
  2301. }
  2302. /** Return true iff we have enough networkstatus and router information to
  2303. * start building circuits. Right now, this means "at least 2 networkstatus
  2304. * documents, and at least 1/4 of expected routers." */
  2305. int
  2306. router_have_minimum_dir_info(void)
  2307. {
  2308. int tot = 0, avg;
  2309. if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
  2310. !routerlist)
  2311. return 0;
  2312. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2313. tot += smartlist_len(ns->entries));
  2314. avg = tot / smartlist_len(networkstatus_list);
  2315. return smartlist_len(routerlist->routers) > (avg/4);
  2316. }
  2317. /** DOCDOC */
  2318. void
  2319. router_reset_descriptor_download_failures(void)
  2320. {
  2321. if (!routerstatus_list)
  2322. return;
  2323. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2324. {
  2325. rs->n_download_failures = 0;
  2326. rs->next_attempt_at = 0;
  2327. });
  2328. }