routerlist.c 48 KB

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