routerlist.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  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. static smartlist_t *trusted_dir_servers = NULL;
  16. /* static function prototypes */
  17. static routerinfo_t *
  18. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  19. int for_runningrouters);
  20. static trusted_dir_server_t *
  21. router_pick_trusteddirserver_impl(int requireother, int fascistfirewall);
  22. static void mark_all_trusteddirservers_up(void);
  23. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  24. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  25. static void router_normalize_routerlist(routerlist_t *rl);
  26. /****************************************************************************/
  27. /****
  28. * Functions to manage and access our list of known routers. (Note:
  29. * dirservers maintain a separate, independent list of known router
  30. * descriptors.)
  31. ****/
  32. /** Global list of all of the routers that we, as an OR or OP, know about. */
  33. static routerlist_t *routerlist = NULL;
  34. extern int has_fetched_directory; /**< from main.c */
  35. /**
  36. * Reload the most recent cached directory (if present).
  37. */
  38. int
  39. router_reload_router_list(void)
  40. {
  41. char filename[512];
  42. int is_recent;
  43. struct stat st;
  44. char *s;
  45. tor_assert(get_options()->DataDirectory);
  46. tor_snprintf(filename,sizeof(filename),"%s/cached-directory",
  47. get_options()->DataDirectory);
  48. s = read_file_to_str(filename,0);
  49. if (s) {
  50. stat(filename, &st); /* if s is true, stat probably worked */
  51. log_fn(LOG_INFO, "Loading cached directory from %s", filename);
  52. is_recent = st.st_mtime > time(NULL) - 60*15;
  53. if (router_load_routerlist_from_directory(s, NULL, is_recent, 1) < 0) {
  54. log_fn(LOG_WARN, "Cached directory at '%s' was unparseable; ignoring.", filename);
  55. }
  56. if (routerlist &&
  57. ((routerlist->published_on > time(NULL) - MIN_ONION_KEY_LIFETIME/2)
  58. || is_recent)) {
  59. directory_has_arrived(st.st_mtime, NULL); /* do things we've been waiting to do */
  60. }
  61. tor_free(s);
  62. }
  63. return 0;
  64. }
  65. /* Set *<b>outp</b> to a smartlist containing a list of
  66. * trusted_dir_server_t * for all known trusted dirservers. Callers
  67. * must not modify the list or its contents.
  68. */
  69. void
  70. router_get_trusted_dir_servers(smartlist_t **outp)
  71. {
  72. if (!trusted_dir_servers)
  73. trusted_dir_servers = smartlist_create();
  74. *outp = trusted_dir_servers;
  75. }
  76. /** Try to find a running dirserver. If there are no running dirservers
  77. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  78. * set all the authoritative ones as running again, and pick one;
  79. * if there are then no dirservers at all in our routerlist,
  80. * reload the routerlist and try one last time. If for_runningrouters is
  81. * true, then only pick a dirserver that can answer runningrouters queries
  82. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  83. * Other args are as in router_pick_directory_server_impl().
  84. */
  85. routerinfo_t *
  86. router_pick_directory_server(int requireother,
  87. int fascistfirewall,
  88. int for_runningrouters,
  89. int retry_if_no_servers)
  90. {
  91. routerinfo_t *choice;
  92. if (!routerlist)
  93. return NULL;
  94. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  95. for_runningrouters);
  96. if (choice || !retry_if_no_servers)
  97. return choice;
  98. log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
  99. /* mark all authdirservers as up again */
  100. mark_all_trusteddirservers_up();
  101. /* try again */
  102. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  103. for_runningrouters);
  104. if (choice)
  105. return choice;
  106. log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
  107. firewall_is_fascist() ? "reachable" : "known");
  108. has_fetched_directory=0; /* reset it */
  109. if (router_reload_router_list()) {
  110. return NULL;
  111. }
  112. /* give it one last try */
  113. choice = router_pick_directory_server_impl(requireother, 0,
  114. for_runningrouters);
  115. return choice;
  116. }
  117. /** Try to find a running trusted dirserver. If there are no running
  118. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  119. * set them all as running again, and try again.
  120. * Other args are as in router_pick_trusteddirserver_impl().
  121. */
  122. trusted_dir_server_t *
  123. router_pick_trusteddirserver(int requireother,
  124. int fascistfirewall,
  125. int retry_if_no_servers)
  126. {
  127. trusted_dir_server_t *choice;
  128. choice = router_pick_trusteddirserver_impl(requireother, fascistfirewall);
  129. if (choice || !retry_if_no_servers)
  130. return choice;
  131. log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
  132. mark_all_trusteddirservers_up();
  133. return router_pick_trusteddirserver_impl(requireother, fascistfirewall);
  134. }
  135. /** Pick a random running verified directory server/mirror from our
  136. * routerlist.
  137. * If <b>fascistfirewall</b> and we're not using a proxy,
  138. * make sure the port we pick is allowed by options-\>firewallports.
  139. * If <b>requireother</b>, it cannot be us.
  140. * If <b>for_runningrouters</b>, make sure we pick a dirserver that
  141. * can answer queries for running-routers (this option will become obsolete
  142. * once 0.0.9-rc5 is dead).
  143. */
  144. static routerinfo_t *
  145. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  146. int for_runningrouters)
  147. {
  148. int i;
  149. routerinfo_t *router;
  150. smartlist_t *sl;
  151. if (!routerlist)
  152. return NULL;
  153. if (get_options()->HttpProxy)
  154. fascistfirewall = 0;
  155. /* Find all the running dirservers we know about. */
  156. sl = smartlist_create();
  157. for (i=0;i < smartlist_len(routerlist->routers); i++) {
  158. router = smartlist_get(routerlist->routers, i);
  159. if (!router->is_running || !router->dir_port || !router->is_verified)
  160. continue;
  161. if (requireother && router_is_me(router))
  162. continue;
  163. if (fascistfirewall) {
  164. if (!fascist_firewall_allows_address(router->addr, router->dir_port))
  165. continue;
  166. }
  167. /* before 0.0.9rc5-cvs, only trusted dirservers served status info. */
  168. if (for_runningrouters &&
  169. !(tor_version_as_new_as(router->platform,"0.0.9rc5-cvs") ||
  170. router_digest_is_trusted_dir(router->identity_digest)))
  171. continue;
  172. smartlist_add(sl, router);
  173. }
  174. router = smartlist_choose(sl);
  175. smartlist_free(sl);
  176. return router;
  177. }
  178. /** Choose randomly from among the trusted dirservers that are up.
  179. * If <b>fascistfirewall</b> and we're not using a proxy,
  180. * make sure the port we pick is allowed by options-\>firewallports.
  181. * If <b>requireother</b>, it cannot be us.
  182. */
  183. static trusted_dir_server_t *
  184. router_pick_trusteddirserver_impl(int requireother, int fascistfirewall)
  185. {
  186. smartlist_t *sl;
  187. routerinfo_t *me;
  188. trusted_dir_server_t *ds;
  189. sl = smartlist_create();
  190. me = router_get_my_routerinfo();
  191. if (!trusted_dir_servers)
  192. return NULL;
  193. if (get_options()->HttpProxy)
  194. fascistfirewall = 0;
  195. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  196. {
  197. if (!d->is_running) continue;
  198. if (requireother && me &&
  199. !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
  200. continue;
  201. if (fascistfirewall) {
  202. if (!fascist_firewall_allows_address(d->addr, d->dir_port))
  203. continue;
  204. }
  205. smartlist_add(sl, d);
  206. });
  207. ds = smartlist_choose(sl);
  208. smartlist_free(sl);
  209. return ds;
  210. }
  211. /** Go through and mark the authoritative dirservers as up. */
  212. static void
  213. mark_all_trusteddirservers_up(void)
  214. {
  215. if (routerlist) {
  216. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  217. if (router_digest_is_trusted_dir(router->identity_digest) &&
  218. router->dir_port > 0) {
  219. router->is_running = 1;
  220. router->status_set_at = time(NULL);
  221. });
  222. }
  223. if (trusted_dir_servers) {
  224. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  225. dir->is_running = 1);
  226. }
  227. }
  228. /** Return 0 if \\exists an authoritative dirserver that's currently
  229. * thought to be running, else return 1.
  230. */
  231. int
  232. all_trusted_directory_servers_down(void)
  233. {
  234. if (!trusted_dir_servers)
  235. return 1;
  236. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  237. if (dir->is_running) return 0);
  238. return 1;
  239. }
  240. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  241. * This is used to make sure we don't pick siblings in a single path.
  242. */
  243. void
  244. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  245. {
  246. routerinfo_t *r;
  247. config_line_t *cl;
  248. if (!router->declared_family)
  249. return;
  250. /* Add every r such that router declares familyness with r, and r
  251. * declares familyhood with router. */
  252. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  253. {
  254. if (!(r = router_get_by_nickname(n)))
  255. continue;
  256. if (!r->declared_family)
  257. continue;
  258. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  259. {
  260. if (router_nickname_matches(router, n2))
  261. smartlist_add(sl, r);
  262. });
  263. });
  264. /* If the user declared any families locally, honor those too. */
  265. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  266. if (router_nickname_is_in_list(router, cl->value)) {
  267. add_nickname_list_to_smartlist(sl, cl->value, 0);
  268. }
  269. }
  270. }
  271. /** List of strings for nicknames we've already warned about and that are
  272. * still unknown / unavailable. */
  273. static smartlist_t *warned_nicknames = NULL;
  274. /** Given a comma-and-whitespace separated list of nicknames, see which
  275. * nicknames in <b>list</b> name routers in our routerlist that are
  276. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  277. */
  278. void
  279. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
  280. {
  281. routerinfo_t *router;
  282. smartlist_t *nickname_list;
  283. if (!list)
  284. return; /* nothing to do */
  285. tor_assert(sl);
  286. nickname_list = smartlist_create();
  287. if (!warned_nicknames)
  288. warned_nicknames = smartlist_create();
  289. smartlist_split_string(nickname_list, list, ",",
  290. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  291. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  292. int warned;
  293. if (!is_legal_nickname_or_hexdigest(nick)) {
  294. log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
  295. continue;
  296. }
  297. router = router_get_by_nickname(nick);
  298. warned = smartlist_string_isin(warned_nicknames, nick);
  299. if (router) {
  300. if (router->is_running) {
  301. smartlist_add(sl,router);
  302. if (warned)
  303. smartlist_string_remove(warned_nicknames, nick);
  304. } else {
  305. if (!warned) {
  306. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
  307. "Nickname list includes '%s' which is known but down.",nick);
  308. smartlist_add(warned_nicknames, tor_strdup(nick));
  309. }
  310. }
  311. } else {
  312. if (!warned) {
  313. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  314. "Nickname list includes '%s' which isn't a known router.",nick);
  315. smartlist_add(warned_nicknames, tor_strdup(nick));
  316. }
  317. }
  318. });
  319. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  320. smartlist_free(nickname_list);
  321. }
  322. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  323. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  324. */
  325. static int
  326. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  327. {
  328. smartlist_t *nickname_list;
  329. int v = 0;
  330. if (!list)
  331. return 0; /* definitely not */
  332. tor_assert(router);
  333. nickname_list = smartlist_create();
  334. smartlist_split_string(nickname_list, list, ",",
  335. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  336. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  337. if (router_nickname_matches(router, cp)) {v=1;break;});
  338. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  339. smartlist_free(nickname_list);
  340. return v;
  341. }
  342. /** Add every router from our routerlist that is currently running to
  343. * <b>sl</b>.
  344. */
  345. static void
  346. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
  347. int need_uptime, int need_capacity)
  348. {
  349. routerinfo_t *router;
  350. int i;
  351. if (!routerlist)
  352. return;
  353. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  354. router = smartlist_get(routerlist->routers, i);
  355. if (router->is_running &&
  356. (router->is_verified ||
  357. (allow_unverified &&
  358. !router_is_unreliable(router, need_uptime, need_capacity)))) {
  359. /* If it's running, and either it's verified or we're ok picking
  360. * unverified routers and this one is suitable.
  361. */
  362. smartlist_add(sl, router);
  363. }
  364. }
  365. }
  366. /** Look through the routerlist until we find a router that has my key.
  367. Return it. */
  368. routerinfo_t *
  369. routerlist_find_my_routerinfo(void)
  370. {
  371. routerinfo_t *router;
  372. int i;
  373. if (!routerlist)
  374. return NULL;
  375. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  376. router = smartlist_get(routerlist->routers, i);
  377. if (router_is_me(router))
  378. return router;
  379. }
  380. return NULL;
  381. }
  382. /** Find a router that's up, that has this IP address, and
  383. * that allows exit to this address:port, or return NULL if there
  384. * isn't a good one.
  385. */
  386. routerinfo_t *
  387. router_find_exact_exit_enclave(const char *address, uint16_t port) {
  388. int i;
  389. routerinfo_t *router;
  390. uint32_t addr;
  391. struct in_addr in;
  392. if (!tor_inet_aton(address, &in))
  393. return NULL; /* it's not an IP already */
  394. addr = ntohl(in.s_addr);
  395. for (i=0;i < smartlist_len(routerlist->routers); i++) {
  396. router = smartlist_get(routerlist->routers, i);
  397. log_fn(LOG_DEBUG,"Considering %s: %d, %u==%u, %d.",
  398. router->nickname,
  399. router->is_running,
  400. router->addr, addr,
  401. router_compare_addr_to_addr_policy(addr, port, router->exit_policy));
  402. if (router->is_running &&
  403. router->addr == addr &&
  404. router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  405. ADDR_POLICY_ACCEPTED)
  406. return router;
  407. }
  408. return NULL;
  409. }
  410. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  411. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  412. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  413. * bandwidth.
  414. */
  415. int
  416. router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
  417. {
  418. if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
  419. return 1;
  420. if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  421. return 1;
  422. return 0;
  423. }
  424. /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
  425. static void
  426. routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
  427. {
  428. int i;
  429. routerinfo_t *router;
  430. for (i = 0; i < smartlist_len(sl); ++i) {
  431. router = smartlist_get(sl, i);
  432. if (router_is_unreliable(router, 1, 0)) {
  433. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  434. // router->nickname);
  435. smartlist_del(sl, i--);
  436. }
  437. }
  438. }
  439. #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
  440. /** Choose a random element of router list <b>sl</b>, weighted by
  441. * the advertised bandwidth of each router.
  442. */
  443. routerinfo_t *
  444. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  445. {
  446. int i;
  447. routerinfo_t *router;
  448. smartlist_t *bandwidths;
  449. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  450. uint32_t *p;
  451. /* First count the total bandwidth weight, and make a smartlist
  452. * of each value. */
  453. bandwidths = smartlist_create();
  454. for (i = 0; i < smartlist_len(sl); ++i) {
  455. router = smartlist_get(sl, i);
  456. this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
  457. router->bandwidthcapacity : router->bandwidthrate;
  458. /* if they claim something huge, don't believe it */
  459. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  460. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  461. p = tor_malloc(sizeof(uint32_t));
  462. *p = this_bw;
  463. smartlist_add(bandwidths, p);
  464. total_bw += this_bw;
  465. }
  466. if (!total_bw) {
  467. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  468. smartlist_free(bandwidths);
  469. return smartlist_choose(sl);
  470. }
  471. /* Second, choose a random value from the bandwidth weights. */
  472. rand_bw = crypto_pseudo_rand_int(total_bw);
  473. /* Last, count through sl until we get to the element we picked */
  474. tmp = 0;
  475. for (i=0; ; i++) {
  476. tor_assert(i < smartlist_len(sl));
  477. p = smartlist_get(bandwidths, i);
  478. tmp += *p;
  479. if (tmp >= rand_bw)
  480. break;
  481. }
  482. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  483. smartlist_free(bandwidths);
  484. return (routerinfo_t *)smartlist_get(sl, i);
  485. }
  486. /** Return a random running router from the routerlist. If any node
  487. * named in <b>preferred</b> is available, pick one of those. Never
  488. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  489. * <b>excludedsmartlist</b>, even if they are the only nodes
  490. * available. If <b>strict</b> is true, never pick any node besides
  491. * those in <b>preferred</b>.
  492. * If <b>need_uptime</b> is non-zero, don't return a router with less
  493. * than a minimum uptime.
  494. * If <b>need_capacity</b> is non-zero, weight your choice by the
  495. * advertised capacity of each router.
  496. */
  497. routerinfo_t *
  498. router_choose_random_node(const char *preferred,
  499. const char *excluded,
  500. smartlist_t *excludedsmartlist,
  501. int need_uptime, int need_capacity,
  502. int allow_unverified, int strict)
  503. {
  504. smartlist_t *sl, *excludednodes;
  505. routerinfo_t *choice;
  506. excludednodes = smartlist_create();
  507. add_nickname_list_to_smartlist(excludednodes,excluded,0);
  508. /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
  509. * since the user explicitly asked for these nodes. */
  510. sl = smartlist_create();
  511. add_nickname_list_to_smartlist(sl,preferred,1);
  512. smartlist_subtract(sl,excludednodes);
  513. if (excludedsmartlist)
  514. smartlist_subtract(sl,excludedsmartlist);
  515. choice = smartlist_choose(sl);
  516. smartlist_free(sl);
  517. if (!choice && !strict) {
  518. /* Then give up on our preferred choices: any node
  519. * will do that has the required attributes. */
  520. sl = smartlist_create();
  521. router_add_running_routers_to_smartlist(sl, allow_unverified,
  522. need_uptime, need_capacity);
  523. smartlist_subtract(sl,excludednodes);
  524. if (excludedsmartlist)
  525. smartlist_subtract(sl,excludedsmartlist);
  526. if (need_uptime)
  527. routerlist_sl_remove_unreliable_routers(sl);
  528. if (need_capacity)
  529. choice = routerlist_sl_choose_by_bandwidth(sl);
  530. else
  531. choice = smartlist_choose(sl);
  532. smartlist_free(sl);
  533. }
  534. smartlist_free(excludednodes);
  535. if (!choice)
  536. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  537. return choice;
  538. }
  539. /** Return true iff the digest of <b>router</b>'s identity key,
  540. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  541. * optionally prefixed with a single dollar sign). Return false if
  542. * <b>hexdigest</b> is malformed, or it doesn't match. */
  543. static INLINE int
  544. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  545. {
  546. char digest[DIGEST_LEN];
  547. tor_assert(hexdigest);
  548. if (hexdigest[0] == '$')
  549. ++hexdigest;
  550. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  551. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  552. return 0;
  553. return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
  554. }
  555. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  556. * (case-insensitive), or if <b>router's</b> identity key digest
  557. * matches a hexadecimal value stored in <b>nickname</b>. Return
  558. * false otherwise. */
  559. static int
  560. router_nickname_matches(routerinfo_t *router, const char *nickname)
  561. {
  562. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  563. return 1;
  564. return router_hex_digest_matches(router, nickname);
  565. }
  566. /** Return the router in our routerlist whose (case-insensitive)
  567. * nickname or (case-sensitive) hexadecimal key digest is
  568. * <b>nickname</b>. Return NULL if no such router is known.
  569. */
  570. routerinfo_t *
  571. router_get_by_nickname(const char *nickname)
  572. {
  573. int i, maybedigest;
  574. routerinfo_t *router;
  575. char digest[DIGEST_LEN];
  576. tor_assert(nickname);
  577. if (!routerlist)
  578. return NULL;
  579. if (nickname[0] == '$')
  580. return router_get_by_hexdigest(nickname);
  581. if (server_mode(get_options()) &&
  582. !strcasecmp(nickname, get_options()->Nickname))
  583. return router_get_my_routerinfo();
  584. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  585. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  586. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  587. router = smartlist_get(routerlist->routers, i);
  588. if (0 == strcasecmp(router->nickname, nickname) ||
  589. (maybedigest && 0 == memcmp(digest, router->identity_digest,
  590. DIGEST_LEN)))
  591. return router;
  592. }
  593. return NULL;
  594. }
  595. /** Return true iff <b>digest</b> is the digest of the identity key of
  596. * a trusted directory. */
  597. int
  598. router_digest_is_trusted_dir(const char *digest)
  599. {
  600. if (!trusted_dir_servers)
  601. return 0;
  602. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  603. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  604. return 0;
  605. }
  606. /** Return the router in our routerlist whose hexadecimal key digest
  607. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  608. routerinfo_t *
  609. router_get_by_hexdigest(const char *hexdigest)
  610. {
  611. char digest[DIGEST_LEN];
  612. tor_assert(hexdigest);
  613. if (!routerlist)
  614. return NULL;
  615. if (hexdigest[0]=='$')
  616. ++hexdigest;
  617. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  618. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  619. return NULL;
  620. return router_get_by_digest(digest);
  621. }
  622. /** Return the router in our routerlist whose 20-byte key digest
  623. * is <b>digest</b>. Return NULL if no such router is known. */
  624. routerinfo_t *
  625. router_get_by_digest(const char *digest)
  626. {
  627. int i;
  628. routerinfo_t *router;
  629. tor_assert(digest);
  630. if (!routerlist) return NULL;
  631. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  632. router = smartlist_get(routerlist->routers, i);
  633. if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
  634. return router;
  635. }
  636. return NULL;
  637. }
  638. /** Set *<b>prouterlist</b> to the current list of all known routers. */
  639. void
  640. router_get_routerlist(routerlist_t **prouterlist)
  641. {
  642. *prouterlist = routerlist;
  643. }
  644. /** Return the publication time on the current routerlist, or 0 if we have no
  645. * routerlist. */
  646. time_t
  647. routerlist_get_published_time(void)
  648. {
  649. return routerlist ? routerlist->published_on : 0;
  650. }
  651. /** Free all storage held by <b>router</b>. */
  652. void
  653. routerinfo_free(routerinfo_t *router)
  654. {
  655. if (!router)
  656. return;
  657. tor_free(router->signed_descriptor);
  658. tor_free(router->address);
  659. tor_free(router->nickname);
  660. tor_free(router->platform);
  661. tor_free(router->contact_info);
  662. if (router->onion_pkey)
  663. crypto_free_pk_env(router->onion_pkey);
  664. if (router->identity_pkey)
  665. crypto_free_pk_env(router->identity_pkey);
  666. if (router->declared_family) {
  667. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  668. smartlist_free(router->declared_family);
  669. }
  670. addr_policy_free(router->exit_policy);
  671. tor_free(router);
  672. }
  673. /** Allocate a fresh copy of <b>router</b> */
  674. routerinfo_t *
  675. routerinfo_copy(const routerinfo_t *router)
  676. {
  677. routerinfo_t *r;
  678. addr_policy_t **e, *tmp;
  679. r = tor_malloc(sizeof(routerinfo_t));
  680. memcpy(r, router, sizeof(routerinfo_t));
  681. r->address = tor_strdup(r->address);
  682. r->nickname = tor_strdup(r->nickname);
  683. r->platform = tor_strdup(r->platform);
  684. if (r->signed_descriptor)
  685. r->signed_descriptor = tor_strdup(r->signed_descriptor);
  686. if (r->onion_pkey)
  687. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  688. if (r->identity_pkey)
  689. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  690. e = &r->exit_policy;
  691. while (*e) {
  692. tmp = tor_malloc(sizeof(addr_policy_t));
  693. memcpy(tmp,*e,sizeof(addr_policy_t));
  694. *e = tmp;
  695. (*e)->string = tor_strdup((*e)->string);
  696. e = & ((*e)->next);
  697. }
  698. if (r->declared_family) {
  699. r->declared_family = smartlist_create();
  700. SMARTLIST_FOREACH(router->declared_family, const char *, s,
  701. smartlist_add(r->declared_family, tor_strdup(s)));
  702. }
  703. return r;
  704. }
  705. /** Free all storage held by a routerlist <b>rl</b> */
  706. void
  707. routerlist_free(routerlist_t *rl)
  708. {
  709. tor_assert(rl);
  710. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  711. routerinfo_free(r));
  712. smartlist_free(rl->routers);
  713. running_routers_free(rl->running_routers);
  714. tor_free(rl->software_versions);
  715. tor_free(rl);
  716. }
  717. /** Free all entries in the current router list. */
  718. void
  719. routerlist_free_current(void)
  720. {
  721. if (routerlist)
  722. routerlist_free(routerlist);
  723. routerlist = NULL;
  724. if (warned_nicknames) {
  725. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  726. smartlist_free(warned_nicknames);
  727. warned_nicknames = NULL;
  728. }
  729. }
  730. /** Free all entries in the list of trusted directory servers. */
  731. void
  732. free_trusted_dir_servers(void)
  733. {
  734. if (trusted_dir_servers) {
  735. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  736. { tor_free(ds->address); tor_free(ds); });
  737. smartlist_free(trusted_dir_servers);
  738. trusted_dir_servers = NULL;
  739. }
  740. }
  741. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  742. void
  743. router_mark_as_down(const char *digest)
  744. {
  745. routerinfo_t *router;
  746. tor_assert(digest);
  747. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  748. if (!memcmp(d->digest, digest, DIGEST_LEN))
  749. d->is_running = 0);
  750. router = router_get_by_digest(digest);
  751. if (!router) /* we don't seem to know about him in the first place */
  752. return;
  753. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  754. if (router_is_me(router) && !we_are_hibernating())
  755. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  756. router->is_running = 0;
  757. router->status_set_at = time(NULL);
  758. }
  759. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  760. * older entries (if any) with the same name. Note: Callers should not hold
  761. * their pointers to <b>router</b> if this function fails; <b>router</b>
  762. * will either be inserted into the routerlist or freed.
  763. *
  764. * Returns >= 0 if the router was added; less than 0 if it was not.
  765. *
  766. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  767. * describing the reason for not liking the routerinfo.
  768. *
  769. * If the return value is less than -1, there was a problem with the
  770. * routerinfo. If the return value is equal to -1, then the routerinfo was
  771. * fine, but out-of-date. If the return value is equal to 1, the
  772. * routerinfo was accepted, but we should notify the generator of the
  773. * descriptor using the message *<b>msg</b>.
  774. */
  775. int
  776. router_add_to_routerlist(routerinfo_t *router, const char **msg)
  777. {
  778. int i;
  779. char id_digest[DIGEST_LEN];
  780. int authdir = get_options()->AuthoritativeDir;
  781. int authdir_verified = 0;
  782. tor_assert(msg);
  783. if (!routerlist) {
  784. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  785. routerlist->routers = smartlist_create();
  786. }
  787. crypto_pk_get_digest(router->identity_pkey, id_digest);
  788. if (authdir) {
  789. if (dirserv_wants_to_reject_router(router, &authdir_verified, msg)) {
  790. tor_assert(*msg);
  791. routerinfo_free(router);
  792. return -2;
  793. }
  794. router->is_verified = authdir_verified;
  795. if (tor_version_as_new_as(router->platform,"0.1.0.2-rc"))
  796. router->is_verified = 1;
  797. }
  798. /* If we have a router with this name, and the identity key is the same,
  799. * choose the newer one. If the identity key has changed, drop the router.
  800. */
  801. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  802. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  803. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  804. if (router->published_on <= old_router->published_on) {
  805. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  806. router->nickname);
  807. if (!authdir) {
  808. /* Update the is_running status to whatever we were told. */
  809. old_router->is_running = router->is_running;
  810. }
  811. routerinfo_free(router);
  812. *msg = "Router descriptor was not new.";
  813. return -1;
  814. } else {
  815. int unreachable = 0;
  816. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  817. router->nickname, old_router->nickname,
  818. hex_str(id_digest,DIGEST_LEN));
  819. if (router->addr == old_router->addr &&
  820. router->or_port == old_router->or_port) {
  821. /* these carry over when the address and orport are unchanged.*/
  822. router->last_reachable = old_router->last_reachable;
  823. router->testing_since = old_router->testing_since;
  824. router->num_unreachable_notifications =
  825. old_router->num_unreachable_notifications;
  826. }
  827. if (authdir &&
  828. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  829. if (router->num_unreachable_notifications >= 3) {
  830. unreachable = 1;
  831. log_fn(LOG_WARN, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
  832. router->nickname, router->contact_info ? router->contact_info : "",
  833. router->platform ? router->platform : "");
  834. } else {
  835. log_fn(LOG_NOTICE,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
  836. router->num_unreachable_notifications++;
  837. }
  838. }
  839. routerinfo_free(old_router);
  840. smartlist_set(routerlist->routers, i, router);
  841. directory_set_dirty();
  842. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  843. authdir_verified ? "Verified server updated" :
  844. "Unverified server updated. (Have you sent us your key fingerprint?)";
  845. return unreachable ? 1 : 0;
  846. }
  847. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  848. /* nicknames match, keys don't. */
  849. if (router->is_verified) {
  850. /* The new verified router replaces the old one; remove the
  851. * old one. And carry on to the end of the list, in case
  852. * there are more old unverified routers with this nickname
  853. */
  854. /* mark-for-close connections using the old key, so we can
  855. * make new ones with the new key.
  856. */
  857. connection_t *conn;
  858. while ((conn = connection_get_by_identity_digest(
  859. old_router->identity_digest, CONN_TYPE_OR))) {
  860. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
  861. old_router->nickname);
  862. connection_mark_for_close(conn);
  863. }
  864. routerinfo_free(old_router);
  865. smartlist_del_keeporder(routerlist->routers, i--);
  866. } else if (old_router->is_verified) {
  867. /* Can't replace a verified router with an unverified one. */
  868. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  869. router->nickname);
  870. routerinfo_free(router);
  871. *msg = "Already have verified router with same nickname and different key.";
  872. return -2;
  873. }
  874. }
  875. }
  876. /* We haven't seen a router with this name before. Add it to the end of
  877. * the list. */
  878. smartlist_add(routerlist->routers, router);
  879. directory_set_dirty();
  880. return 0;
  881. }
  882. /** Remove any routers from the routerlist that are more than <b>age</b>
  883. * seconds old.
  884. */
  885. void
  886. routerlist_remove_old_routers(int age)
  887. {
  888. int i;
  889. time_t cutoff;
  890. routerinfo_t *router;
  891. if (!routerlist)
  892. return;
  893. cutoff = time(NULL) - age;
  894. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  895. router = smartlist_get(routerlist->routers, i);
  896. if (router->published_on <= cutoff) {
  897. /* Too old. Remove it. */
  898. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  899. routerinfo_free(router);
  900. smartlist_del(routerlist->routers, i--);
  901. }
  902. }
  903. }
  904. /**
  905. * Code to parse a single router descriptor and insert it into the
  906. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  907. * descriptor was well-formed but could not be added; and 1 if the
  908. * descriptor was added.
  909. *
  910. * If we don't add it and <b>msg</b> is not NULL, then assign to
  911. * *<b>msg</b> a static string describing the reason for refusing the
  912. * descriptor.
  913. *
  914. * This is used only by the controller.
  915. */
  916. int
  917. router_load_single_router(const char *s, const char **msg)
  918. {
  919. routerinfo_t *ri;
  920. tor_assert(msg);
  921. *msg = NULL;
  922. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  923. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  924. *msg = "Couldn't parse router descriptor.";
  925. return -1;
  926. }
  927. if (router_is_me(ri)) {
  928. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  929. *msg = "Router's identity key matches mine.";
  930. routerinfo_free(ri);
  931. return 0;
  932. }
  933. if (routerlist && routerlist->running_routers) {
  934. running_routers_t *rr = routerlist->running_routers;
  935. router_update_status_from_smartlist(ri,
  936. rr->published_on,
  937. rr->running_routers);
  938. }
  939. if (router_add_to_routerlist(ri, msg)<0) {
  940. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  941. *msg?*msg:"(No message).");
  942. /* we've already assigned to *msg now, and ri is already freed */
  943. return 0;
  944. } else {
  945. smartlist_t *changed = smartlist_create();
  946. smartlist_add(changed, ri);
  947. control_event_descriptors_changed(changed);
  948. smartlist_free(changed);
  949. }
  950. log_fn(LOG_DEBUG, "Added router to list");
  951. return 1;
  952. }
  953. /** Add to the current routerlist each router stored in the
  954. * signed directory <b>s</b>. If pkey is provided, check the signature
  955. * against pkey; else check against the pkey of the signing directory
  956. * server.
  957. *
  958. * If <b>dir_is_recent</b> is non-zero, then examine the
  959. * Recommended-versions line and take appropriate action.
  960. *
  961. * If <b>dir_is_cached</b> is non-zero, then we're reading it
  962. * from the cache so don't bother to re-write it to the cache.
  963. */
  964. int
  965. router_load_routerlist_from_directory(const char *s,
  966. crypto_pk_env_t *pkey,
  967. int dir_is_recent,
  968. int dir_is_cached)
  969. {
  970. routerlist_t *new_list = NULL;
  971. if (router_parse_routerlist_from_directory(s, &new_list, pkey,
  972. dir_is_recent,
  973. !dir_is_cached)) {
  974. log_fn(LOG_WARN, "Couldn't parse directory.");
  975. return -1;
  976. }
  977. if (routerlist) {
  978. /* Merge the new_list into routerlist, then free new_list. Also
  979. * keep a list of changed descriptors to inform controllers. */
  980. smartlist_t *changed = smartlist_create();
  981. SMARTLIST_FOREACH(new_list->routers, routerinfo_t *, r,
  982. {
  983. const char *msg;
  984. if (router_add_to_routerlist(r,&msg)>=0)
  985. smartlist_add(changed, r);
  986. });
  987. smartlist_clear(new_list->routers);
  988. routerlist->published_on = new_list->published_on;
  989. tor_free(routerlist->software_versions);
  990. routerlist->software_versions = new_list->software_versions;
  991. new_list->software_versions = NULL;
  992. routerlist_free(new_list);
  993. control_event_descriptors_changed(changed);
  994. smartlist_free(changed);
  995. } else {
  996. routerlist = new_list;
  997. control_event_descriptors_changed(routerlist->routers);
  998. }
  999. router_normalize_routerlist(routerlist);
  1000. return 0;
  1001. }
  1002. /** Ensure that our own routerinfo is at the front, and remove duplicates
  1003. * of our routerinfo.
  1004. */
  1005. static void
  1006. router_normalize_routerlist(routerlist_t *rl)
  1007. {
  1008. int i=0;
  1009. routerinfo_t *r;
  1010. if ((r = router_get_my_routerinfo())) {
  1011. smartlist_insert(rl->routers, 0, routerinfo_copy(r));
  1012. ++i;
  1013. }
  1014. for ( ; i < smartlist_len(rl->routers); ++i) {
  1015. r = smartlist_get(rl->routers,i);
  1016. if (router_is_me(r)) {
  1017. routerinfo_free(r);
  1018. smartlist_del_keeporder(rl->routers, i--);
  1019. }
  1020. }
  1021. }
  1022. /** Decide whether a given addr:port is definitely accepted,
  1023. * definitely rejected, probably accepted, or probably rejected by a
  1024. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1025. * target address. If <b>port</b> is 0, we don't know the port of the
  1026. * target address.
  1027. *
  1028. * For now, the algorithm is pretty simple: we look for definite and
  1029. * uncertain matches. The first definite match is what we guess; if
  1030. * it was preceded by no uncertain matches of the opposite policy,
  1031. * then the guess is definite; otherwise it is probable. (If we
  1032. * have a known addr and port, all matches are definite; if we have an
  1033. * unknown addr/port, any address/port ranges other than "all" are
  1034. * uncertain.)
  1035. *
  1036. * We could do better by assuming that some ranges never match typical
  1037. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1038. */
  1039. addr_policy_result_t
  1040. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1041. addr_policy_t *policy)
  1042. {
  1043. int maybe_reject = 0;
  1044. int maybe_accept = 0;
  1045. int match = 0;
  1046. int maybe = 0;
  1047. addr_policy_t *tmpe;
  1048. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1049. maybe = 0;
  1050. if (!addr) {
  1051. /* Address is unknown. */
  1052. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1053. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1054. /* The port definitely matches. */
  1055. if (tmpe->msk == 0) {
  1056. match = 1;
  1057. } else {
  1058. maybe = 1;
  1059. }
  1060. } else if (!port) {
  1061. /* The port maybe matches. */
  1062. maybe = 1;
  1063. }
  1064. } else {
  1065. /* Address is known */
  1066. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1067. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1068. /* Exact match for the policy */
  1069. match = 1;
  1070. } else if (!port) {
  1071. maybe = 1;
  1072. }
  1073. }
  1074. }
  1075. if (maybe) {
  1076. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1077. maybe_reject = 1;
  1078. else
  1079. maybe_accept = 1;
  1080. }
  1081. if (match) {
  1082. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1083. /* If we already hit a clause that might trigger a 'reject', than we
  1084. * can't be sure of this certain 'accept'.*/
  1085. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1086. } else {
  1087. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1088. }
  1089. }
  1090. }
  1091. /* accept all by default. */
  1092. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1093. }
  1094. /** Return 1 if all running sufficiently-stable routers will reject
  1095. * addr:port, return 0 if any might accept it. */
  1096. int
  1097. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1098. int need_uptime)
  1099. {
  1100. int i;
  1101. routerinfo_t *router;
  1102. addr_policy_result_t r;
  1103. if (!routerlist) return 1;
  1104. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  1105. router = smartlist_get(routerlist->routers, i);
  1106. if (router->is_running &&
  1107. !router_is_unreliable(router, need_uptime, 0)) {
  1108. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1109. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1110. return 0; /* this one could be ok. good enough. */
  1111. }
  1112. }
  1113. return 1; /* all will reject. */
  1114. }
  1115. /**
  1116. * If <b>policy</b> implicitly allows connections to any port in the
  1117. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1118. * part of the policy that allows it, and return 1. Else return 0.
  1119. *
  1120. * A policy allows an IP:Port combination <em>implicitly</em> if
  1121. * it is included in a *: pattern, or in a fallback pattern.
  1122. */
  1123. static int
  1124. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1125. uint32_t addr, uint32_t mask,
  1126. addr_policy_t **policy_out)
  1127. {
  1128. uint32_t addr2;
  1129. tor_assert(policy_out);
  1130. addr &= mask;
  1131. addr2 = addr | ~mask;
  1132. for (; policy; policy=policy->next) {
  1133. /* Does this policy cover all of the address range we're looking at? */
  1134. /* Boolean logic time: range X is contained in range Y if, for
  1135. * each bit B, all possible values of B in X are values of B in Y.
  1136. * In "addr", we have every fixed bit set to its value, and every
  1137. * free bit set to 0. In "addr2", we have every fixed bit set to
  1138. * its value, and every free bit set to 1. So if addr and addr2 are
  1139. * both in the policy, the range is covered by the policy.
  1140. */
  1141. uint32_t p_addr = policy->addr & policy->msk;
  1142. if (p_addr == (addr & policy->msk) &&
  1143. p_addr == (addr2 & policy->msk) &&
  1144. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1145. return 0;
  1146. }
  1147. /* Does this policy cover some of the address range we're looking at? */
  1148. /* Boolean logic time: range X and range Y intersect if there is
  1149. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1150. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1151. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1152. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1153. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1154. */
  1155. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1156. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1157. *policy_out = policy;
  1158. return 1;
  1159. }
  1160. }
  1161. *policy_out = NULL;
  1162. return 1;
  1163. }
  1164. /** If <b>policy</b> implicitly allows connections to any port on
  1165. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1166. * true. Else return false.
  1167. **/
  1168. int
  1169. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1170. int warn)
  1171. {
  1172. addr_policy_t *p;
  1173. int r=0,i;
  1174. static struct {
  1175. uint32_t addr; uint32_t mask; const char *network;
  1176. } private_networks[] = {
  1177. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1178. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1179. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1180. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1181. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1182. { 0,0,NULL},
  1183. };
  1184. for (i=0; private_networks[i].addr; ++i) {
  1185. p = NULL;
  1186. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1187. if (policy_includes_addr_mask_implicitly(
  1188. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1189. if (warn)
  1190. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1191. p?p->string:"(default)",
  1192. private_networks[i].network);
  1193. r = 1;
  1194. }
  1195. }
  1196. return r;
  1197. }
  1198. /** Return true iff <b>router</b> does not permit exit streams.
  1199. */
  1200. int
  1201. router_exit_policy_rejects_all(routerinfo_t *router)
  1202. {
  1203. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1204. == ADDR_POLICY_REJECTED;
  1205. }
  1206. /** Release all space held in <b>rr</b>. */
  1207. void
  1208. running_routers_free(running_routers_t *rr)
  1209. {
  1210. if (!rr)
  1211. return;
  1212. if (rr->running_routers) {
  1213. SMARTLIST_FOREACH(rr->running_routers, char *, s, tor_free(s));
  1214. smartlist_free(rr->running_routers);
  1215. }
  1216. tor_free(rr);
  1217. }
  1218. /** Update the running/not-running status of every router in <b>list</b>, based
  1219. * on the contents of <b>rr</b>. */
  1220. static void
  1221. routerlist_update_from_runningrouters(routerlist_t *list,
  1222. running_routers_t *rr)
  1223. {
  1224. routerinfo_t *me = router_get_my_routerinfo();
  1225. smartlist_t *all_routers;
  1226. if (!list)
  1227. return;
  1228. if (list->published_on >= rr->published_on)
  1229. return;
  1230. if (list->running_routers_updated_on >= rr->published_on)
  1231. return;
  1232. all_routers = smartlist_create();
  1233. if (me) /* learn if the dirservers think I'm verified */
  1234. smartlist_add(all_routers, me);
  1235. smartlist_add_all(all_routers,list->routers);
  1236. SMARTLIST_FOREACH(rr->running_routers, const char *, cp,
  1237. routers_update_status_from_entry(all_routers, rr->published_on,
  1238. cp));
  1239. smartlist_free(all_routers);
  1240. list->running_routers_updated_on = rr->published_on;
  1241. }
  1242. /** We've just got a running routers list in <b>rr</b>; update the
  1243. * status of the routers in <b>list</b>, and cache <b>rr</b> */
  1244. void
  1245. routerlist_set_runningrouters(routerlist_t *list, running_routers_t *rr)
  1246. {
  1247. routerlist_update_from_runningrouters(list,rr);
  1248. if (list->running_routers != rr) {
  1249. running_routers_free(list->running_routers);
  1250. list->running_routers = rr;
  1251. }
  1252. }
  1253. /** Update the is_running and is_verified fields of the router <b>router</b>,
  1254. * based in its status in the list of strings stored in <b>running_list</b>.
  1255. * All entries in <b>running_list</b> follow one of these formats:
  1256. * <ol><li> <b>nickname</b> -- router is running and verified.
  1257. * (running-routers format)
  1258. * <li> !<b>nickname</b> -- router is not-running and verified.
  1259. * (running-routers format)
  1260. * <li> <b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1261. * verified. (router-status format)
  1262. * (router-status format)
  1263. * <li> !<b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1264. * verified. (router-status format)
  1265. * <li> !<b>nickname</b> -- router is not-running and verified.
  1266. * <li> $<b>hexdigest</b> -- router is running and unverified.
  1267. * <li> !$<b>hexdigest</b> -- router is not-running and unverified.
  1268. * </ol>
  1269. *
  1270. * Return 1 if we found router in running_list, else return 0.
  1271. */
  1272. int
  1273. routers_update_status_from_entry(smartlist_t *routers,
  1274. time_t list_time,
  1275. const char *s)
  1276. {
  1277. int authdir = get_options()->AuthoritativeDir;
  1278. int is_running = 1;
  1279. int is_verified = 0;
  1280. int hex_digest_set = 0;
  1281. char nickname[MAX_NICKNAME_LEN+1];
  1282. char hexdigest[HEX_DIGEST_LEN+1];
  1283. char digest[DIGEST_LEN];
  1284. const char *cp, *end;
  1285. /* First, parse the entry. */
  1286. cp = s;
  1287. if (*cp == '!') {
  1288. is_running = 0;
  1289. ++cp;
  1290. }
  1291. if (*cp != '$') {
  1292. /* It starts with a non-dollar character; that's a nickname. The nickname
  1293. * entry will either extend to a NUL (old running-routers format) or to an
  1294. * equals sign (new router-status format). */
  1295. is_verified = 1;
  1296. end = strchr(cp, '=');
  1297. if (!end)
  1298. end = strchr(cp,'\0');
  1299. tor_assert(end);
  1300. /* 'end' now points on character beyond the end of the nickname */
  1301. if (end == cp || end-cp > MAX_NICKNAME_LEN) {
  1302. log_fn(LOG_WARN, "Bad nickname length (%d) in router status entry (%s)",
  1303. (int)(end-cp), s);
  1304. return -1;
  1305. }
  1306. memcpy(nickname, cp, end-cp);
  1307. nickname[end-cp]='\0';
  1308. if (!is_legal_nickname(nickname)) {
  1309. log_fn(LOG_WARN, "Bad nickname (%s) in router status entry (%s)",
  1310. nickname, s);
  1311. return -1;
  1312. }
  1313. cp = end;
  1314. if (*cp == '=')
  1315. ++cp;
  1316. }
  1317. /* 'end' now points to the start of a hex digest, or EOS. */
  1318. /* Parse the hexdigest portion of the status. */
  1319. if (*cp == '$') {
  1320. hex_digest_set = 1;
  1321. ++cp;
  1322. if (strlen(cp) != HEX_DIGEST_LEN) {
  1323. log_fn(LOG_WARN, "Bad length (%d) on digest in router status entry (%s)",
  1324. (int)strlen(cp), s);
  1325. return -1;
  1326. }
  1327. strlcpy(hexdigest, cp, sizeof(hexdigest));
  1328. if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0) {
  1329. log_fn(LOG_WARN, "Invalid digest in router status entry (%s)", s);
  1330. return -1;
  1331. }
  1332. }
  1333. /* Make sure that the entry was in the right format. */
  1334. if (!hex_digest_set) {
  1335. log_fn(LOG_WARN, "Invalid syntax for router-status member (%s)", s);
  1336. return -1;
  1337. }
  1338. /* Okay, we're done parsing. For all routers that match, update their status.
  1339. */
  1340. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1341. {
  1342. int nickname_matches = is_verified && !strcasecmp(r->nickname, nickname);
  1343. int digest_matches = !memcmp(digest, r->identity_digest, DIGEST_LEN);
  1344. if (!authdir) {
  1345. /* If we're not an authoritative directory, update verified status.
  1346. */
  1347. if (nickname_matches && digest_matches)
  1348. r->is_verified = 1;
  1349. else if (digest_matches)
  1350. r->is_verified = 0;
  1351. }
  1352. if (digest_matches)
  1353. if (r->status_set_at < list_time) {
  1354. if (!authdir || is_running)
  1355. /* If we're an authoritative directory, only believe that servers
  1356. * are down when we hear it ourselves. Otherwise, believe
  1357. * what we're told.
  1358. */
  1359. r->is_running = is_running;
  1360. r->status_set_at = time(NULL);
  1361. }
  1362. });
  1363. return 0;
  1364. }
  1365. /** As router_update_status_from_entry, but consider all entries in
  1366. * running_list. */
  1367. int
  1368. router_update_status_from_smartlist(routerinfo_t *router,
  1369. time_t list_time,
  1370. smartlist_t *running_list)
  1371. {
  1372. smartlist_t *rl;
  1373. rl = smartlist_create();
  1374. smartlist_add(rl,router);
  1375. SMARTLIST_FOREACH(running_list, const char *, cp,
  1376. routers_update_status_from_entry(rl,list_time,cp));
  1377. smartlist_free(rl);
  1378. return 0;
  1379. }
  1380. /** Add to the list of authorized directory servers one at
  1381. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  1382. * <b>address</b> is NULL, add ourself. */
  1383. void
  1384. add_trusted_dir_server(const char *address, uint16_t port, const char *digest)
  1385. {
  1386. trusted_dir_server_t *ent;
  1387. uint32_t a;
  1388. char *hostname = NULL;
  1389. if (!trusted_dir_servers)
  1390. trusted_dir_servers = smartlist_create();
  1391. if (!address) { /* The address is us; we should guess. */
  1392. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  1393. log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
  1394. return;
  1395. }
  1396. } else {
  1397. if (tor_lookup_hostname(address, &a)) {
  1398. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1399. address);
  1400. return;
  1401. }
  1402. hostname = tor_strdup(address);
  1403. a = ntohl(a);
  1404. }
  1405. ent = tor_malloc(sizeof(trusted_dir_server_t));
  1406. ent->address = hostname;
  1407. ent->addr = a;
  1408. ent->dir_port = port;
  1409. ent->is_running = 1;
  1410. memcpy(ent->digest, digest, DIGEST_LEN);
  1411. smartlist_add(trusted_dir_servers, ent);
  1412. }
  1413. /** Remove all members from the list of trusted dir servers. */
  1414. void
  1415. clear_trusted_dir_servers(void)
  1416. {
  1417. if (trusted_dir_servers) {
  1418. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1419. { tor_free(ent->address); tor_free(ent); });
  1420. smartlist_clear(trusted_dir_servers);
  1421. } else {
  1422. trusted_dir_servers = smartlist_create();
  1423. }
  1424. }