routerlist.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  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 storage held by the routerstatus object <b>rs</b>. */
  731. void
  732. routerstatus_free(routerstatus_t *rs)
  733. {
  734. tor_free(rs);
  735. }
  736. /** Free all storage held by the networkstatus object <b>ns</b>. */
  737. void
  738. networkstatus_free(networkstatus_t *ns)
  739. {
  740. tor_free(ns->source_address);
  741. tor_free(ns->contact);
  742. crypto_free_pk_env(ns->signing_key);
  743. tor_free(ns->client_versions);
  744. tor_free(ns->server_versions);
  745. if (ns->entries) {
  746. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
  747. smartlist_free(ns->entries);
  748. }
  749. tor_free(ns);
  750. }
  751. /** Free all entries in the list of trusted directory servers. */
  752. void
  753. free_trusted_dir_servers(void)
  754. {
  755. if (trusted_dir_servers) {
  756. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  757. { tor_free(ds->address); tor_free(ds); });
  758. smartlist_free(trusted_dir_servers);
  759. trusted_dir_servers = NULL;
  760. }
  761. }
  762. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  763. void
  764. router_mark_as_down(const char *digest)
  765. {
  766. routerinfo_t *router;
  767. tor_assert(digest);
  768. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  769. if (!memcmp(d->digest, digest, DIGEST_LEN))
  770. d->is_running = 0);
  771. router = router_get_by_digest(digest);
  772. if (!router) /* we don't seem to know about him in the first place */
  773. return;
  774. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  775. if (router_is_me(router) && !we_are_hibernating())
  776. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  777. router->is_running = 0;
  778. router->status_set_at = time(NULL);
  779. }
  780. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  781. * older entries (if any) with the same name. Note: Callers should not hold
  782. * their pointers to <b>router</b> if this function fails; <b>router</b>
  783. * will either be inserted into the routerlist or freed.
  784. *
  785. * Returns >= 0 if the router was added; less than 0 if it was not.
  786. *
  787. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  788. * describing the reason for not liking the routerinfo.
  789. *
  790. * If the return value is less than -1, there was a problem with the
  791. * routerinfo. If the return value is equal to -1, then the routerinfo was
  792. * fine, but out-of-date. If the return value is equal to 1, the
  793. * routerinfo was accepted, but we should notify the generator of the
  794. * descriptor using the message *<b>msg</b>.
  795. */
  796. int
  797. router_add_to_routerlist(routerinfo_t *router, const char **msg)
  798. {
  799. int i;
  800. char id_digest[DIGEST_LEN];
  801. int authdir = get_options()->AuthoritativeDir;
  802. int authdir_verified = 0;
  803. tor_assert(msg);
  804. if (!routerlist) {
  805. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  806. routerlist->routers = smartlist_create();
  807. }
  808. crypto_pk_get_digest(router->identity_pkey, id_digest);
  809. if (authdir) {
  810. if (dirserv_wants_to_reject_router(router, &authdir_verified, msg)) {
  811. tor_assert(*msg);
  812. routerinfo_free(router);
  813. return -2;
  814. }
  815. router->is_verified = authdir_verified;
  816. if (tor_version_as_new_as(router->platform,"0.1.0.2-rc"))
  817. router->is_verified = 1;
  818. }
  819. /* If we have a router with this name, and the identity key is the same,
  820. * choose the newer one. If the identity key has changed, drop the router.
  821. */
  822. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  823. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  824. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  825. if (router->published_on <= old_router->published_on) {
  826. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  827. router->nickname);
  828. if (authdir) {
  829. /* Update the is_verified status based on our lookup. */
  830. old_router->is_verified = router->is_verified;
  831. } else {
  832. /* Update the is_running status to whatever we were told. */
  833. old_router->is_running = router->is_running;
  834. }
  835. routerinfo_free(router);
  836. *msg = "Router descriptor was not new.";
  837. return -1;
  838. } else {
  839. int unreachable = 0;
  840. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  841. router->nickname, old_router->nickname,
  842. hex_str(id_digest,DIGEST_LEN));
  843. if (router->addr == old_router->addr &&
  844. router->or_port == old_router->or_port) {
  845. /* these carry over when the address and orport are unchanged.*/
  846. router->last_reachable = old_router->last_reachable;
  847. router->testing_since = old_router->testing_since;
  848. router->num_unreachable_notifications =
  849. old_router->num_unreachable_notifications;
  850. }
  851. if (authdir &&
  852. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  853. if (router->num_unreachable_notifications >= 3) {
  854. unreachable = 1;
  855. log_fn(LOG_WARN, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
  856. router->nickname, router->contact_info ? router->contact_info : "",
  857. router->platform ? router->platform : "");
  858. } else {
  859. log_fn(LOG_NOTICE,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
  860. router->num_unreachable_notifications++;
  861. }
  862. }
  863. routerinfo_free(old_router);
  864. smartlist_set(routerlist->routers, i, router);
  865. directory_set_dirty();
  866. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  867. authdir_verified ? "Verified server updated" :
  868. "Unverified server updated. (Have you sent us your key fingerprint?)";
  869. return unreachable ? 1 : 0;
  870. }
  871. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  872. /* nicknames match, keys don't. */
  873. if (router->is_verified) {
  874. /* The new verified router replaces the old one; remove the
  875. * old one. And carry on to the end of the list, in case
  876. * there are more old unverified routers with this nickname
  877. */
  878. /* mark-for-close connections using the old key, so we can
  879. * make new ones with the new key.
  880. */
  881. connection_t *conn;
  882. while ((conn = connection_get_by_identity_digest(
  883. old_router->identity_digest, CONN_TYPE_OR))) {
  884. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
  885. old_router->nickname);
  886. connection_mark_for_close(conn);
  887. }
  888. routerinfo_free(old_router);
  889. smartlist_del_keeporder(routerlist->routers, i--);
  890. } else if (old_router->is_verified) {
  891. /* Can't replace a verified router with an unverified one. */
  892. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  893. router->nickname);
  894. routerinfo_free(router);
  895. *msg = "Already have verified router with same nickname and different key.";
  896. return -2;
  897. }
  898. }
  899. }
  900. /* We haven't seen a router with this name before. Add it to the end of
  901. * the list. */
  902. smartlist_add(routerlist->routers, router);
  903. directory_set_dirty();
  904. return 0;
  905. }
  906. /** Remove any routers from the routerlist that are more than <b>age</b>
  907. * seconds old.
  908. */
  909. void
  910. routerlist_remove_old_routers(int age)
  911. {
  912. int i;
  913. time_t cutoff;
  914. routerinfo_t *router;
  915. if (!routerlist)
  916. return;
  917. cutoff = time(NULL) - age;
  918. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  919. router = smartlist_get(routerlist->routers, i);
  920. if (router->published_on <= cutoff) {
  921. /* Too old. Remove it. */
  922. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  923. routerinfo_free(router);
  924. smartlist_del(routerlist->routers, i--);
  925. }
  926. }
  927. }
  928. /**
  929. * Code to parse a single router descriptor and insert it into the
  930. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  931. * descriptor was well-formed but could not be added; and 1 if the
  932. * descriptor was added.
  933. *
  934. * If we don't add it and <b>msg</b> is not NULL, then assign to
  935. * *<b>msg</b> a static string describing the reason for refusing the
  936. * descriptor.
  937. *
  938. * This is used only by the controller.
  939. */
  940. int
  941. router_load_single_router(const char *s, const char **msg)
  942. {
  943. routerinfo_t *ri;
  944. tor_assert(msg);
  945. *msg = NULL;
  946. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  947. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  948. *msg = "Couldn't parse router descriptor.";
  949. return -1;
  950. }
  951. if (router_is_me(ri)) {
  952. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  953. *msg = "Router's identity key matches mine.";
  954. routerinfo_free(ri);
  955. return 0;
  956. }
  957. if (routerlist && routerlist->running_routers) {
  958. running_routers_t *rr = routerlist->running_routers;
  959. router_update_status_from_smartlist(ri,
  960. rr->published_on,
  961. rr->running_routers);
  962. }
  963. if (router_add_to_routerlist(ri, msg)<0) {
  964. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  965. *msg?*msg:"(No message).");
  966. /* we've already assigned to *msg now, and ri is already freed */
  967. return 0;
  968. } else {
  969. smartlist_t *changed = smartlist_create();
  970. smartlist_add(changed, ri);
  971. control_event_descriptors_changed(changed);
  972. smartlist_free(changed);
  973. }
  974. log_fn(LOG_DEBUG, "Added router to list");
  975. return 1;
  976. }
  977. /** Add to the current routerlist each router stored in the
  978. * signed directory <b>s</b>. If pkey is provided, check the signature
  979. * against pkey; else check against the pkey of the signing directory
  980. * server.
  981. *
  982. * If <b>dir_is_recent</b> is non-zero, then examine the
  983. * Recommended-versions line and take appropriate action.
  984. *
  985. * If <b>dir_is_cached</b> is non-zero, then we're reading it
  986. * from the cache so don't bother to re-write it to the cache.
  987. */
  988. int
  989. router_load_routerlist_from_directory(const char *s,
  990. crypto_pk_env_t *pkey,
  991. int dir_is_recent,
  992. int dir_is_cached)
  993. {
  994. routerlist_t *new_list = NULL;
  995. if (router_parse_routerlist_from_directory(s, &new_list, pkey,
  996. dir_is_recent,
  997. !dir_is_cached)) {
  998. log_fn(LOG_WARN, "Couldn't parse directory.");
  999. return -1;
  1000. }
  1001. if (routerlist) {
  1002. /* Merge the new_list into routerlist, then free new_list. Also
  1003. * keep a list of changed descriptors to inform controllers. */
  1004. smartlist_t *changed = smartlist_create();
  1005. SMARTLIST_FOREACH(new_list->routers, routerinfo_t *, r,
  1006. {
  1007. const char *msg;
  1008. if (router_add_to_routerlist(r,&msg)>=0)
  1009. smartlist_add(changed, r);
  1010. });
  1011. smartlist_clear(new_list->routers);
  1012. routerlist->published_on = new_list->published_on;
  1013. tor_free(routerlist->software_versions);
  1014. routerlist->software_versions = new_list->software_versions;
  1015. new_list->software_versions = NULL;
  1016. routerlist_free(new_list);
  1017. control_event_descriptors_changed(changed);
  1018. smartlist_free(changed);
  1019. } else {
  1020. routerlist = new_list;
  1021. control_event_descriptors_changed(routerlist->routers);
  1022. }
  1023. router_normalize_routerlist(routerlist);
  1024. return 0;
  1025. }
  1026. /** Ensure that our own routerinfo is at the front, and remove duplicates
  1027. * of our routerinfo.
  1028. */
  1029. static void
  1030. router_normalize_routerlist(routerlist_t *rl)
  1031. {
  1032. int i=0;
  1033. routerinfo_t *r;
  1034. if ((r = router_get_my_routerinfo())) {
  1035. smartlist_insert(rl->routers, 0, routerinfo_copy(r));
  1036. ++i;
  1037. }
  1038. for ( ; i < smartlist_len(rl->routers); ++i) {
  1039. r = smartlist_get(rl->routers,i);
  1040. if (router_is_me(r)) {
  1041. routerinfo_free(r);
  1042. smartlist_del_keeporder(rl->routers, i--);
  1043. }
  1044. }
  1045. }
  1046. /** Decide whether a given addr:port is definitely accepted,
  1047. * definitely rejected, probably accepted, or probably rejected by a
  1048. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1049. * target address. If <b>port</b> is 0, we don't know the port of the
  1050. * target address.
  1051. *
  1052. * For now, the algorithm is pretty simple: we look for definite and
  1053. * uncertain matches. The first definite match is what we guess; if
  1054. * it was preceded by no uncertain matches of the opposite policy,
  1055. * then the guess is definite; otherwise it is probable. (If we
  1056. * have a known addr and port, all matches are definite; if we have an
  1057. * unknown addr/port, any address/port ranges other than "all" are
  1058. * uncertain.)
  1059. *
  1060. * We could do better by assuming that some ranges never match typical
  1061. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1062. */
  1063. addr_policy_result_t
  1064. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1065. addr_policy_t *policy)
  1066. {
  1067. int maybe_reject = 0;
  1068. int maybe_accept = 0;
  1069. int match = 0;
  1070. int maybe = 0;
  1071. addr_policy_t *tmpe;
  1072. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1073. maybe = 0;
  1074. if (!addr) {
  1075. /* Address is unknown. */
  1076. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1077. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1078. /* The port definitely matches. */
  1079. if (tmpe->msk == 0) {
  1080. match = 1;
  1081. } else {
  1082. maybe = 1;
  1083. }
  1084. } else if (!port) {
  1085. /* The port maybe matches. */
  1086. maybe = 1;
  1087. }
  1088. } else {
  1089. /* Address is known */
  1090. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1091. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1092. /* Exact match for the policy */
  1093. match = 1;
  1094. } else if (!port) {
  1095. maybe = 1;
  1096. }
  1097. }
  1098. }
  1099. if (maybe) {
  1100. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1101. maybe_reject = 1;
  1102. else
  1103. maybe_accept = 1;
  1104. }
  1105. if (match) {
  1106. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1107. /* If we already hit a clause that might trigger a 'reject', than we
  1108. * can't be sure of this certain 'accept'.*/
  1109. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1110. } else {
  1111. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1112. }
  1113. }
  1114. }
  1115. /* accept all by default. */
  1116. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1117. }
  1118. /** Return 1 if all running sufficiently-stable routers will reject
  1119. * addr:port, return 0 if any might accept it. */
  1120. int
  1121. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1122. int need_uptime)
  1123. {
  1124. int i;
  1125. routerinfo_t *router;
  1126. addr_policy_result_t r;
  1127. if (!routerlist) return 1;
  1128. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  1129. router = smartlist_get(routerlist->routers, i);
  1130. if (router->is_running &&
  1131. !router_is_unreliable(router, need_uptime, 0)) {
  1132. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1133. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1134. return 0; /* this one could be ok. good enough. */
  1135. }
  1136. }
  1137. return 1; /* all will reject. */
  1138. }
  1139. /**
  1140. * If <b>policy</b> implicitly allows connections to any port in the
  1141. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1142. * part of the policy that allows it, and return 1. Else return 0.
  1143. *
  1144. * A policy allows an IP:Port combination <em>implicitly</em> if
  1145. * it is included in a *: pattern, or in a fallback pattern.
  1146. */
  1147. static int
  1148. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1149. uint32_t addr, uint32_t mask,
  1150. addr_policy_t **policy_out)
  1151. {
  1152. uint32_t addr2;
  1153. tor_assert(policy_out);
  1154. addr &= mask;
  1155. addr2 = addr | ~mask;
  1156. for (; policy; policy=policy->next) {
  1157. /* Does this policy cover all of the address range we're looking at? */
  1158. /* Boolean logic time: range X is contained in range Y if, for
  1159. * each bit B, all possible values of B in X are values of B in Y.
  1160. * In "addr", we have every fixed bit set to its value, and every
  1161. * free bit set to 0. In "addr2", we have every fixed bit set to
  1162. * its value, and every free bit set to 1. So if addr and addr2 are
  1163. * both in the policy, the range is covered by the policy.
  1164. */
  1165. uint32_t p_addr = policy->addr & policy->msk;
  1166. if (p_addr == (addr & policy->msk) &&
  1167. p_addr == (addr2 & policy->msk) &&
  1168. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1169. return 0;
  1170. }
  1171. /* Does this policy cover some of the address range we're looking at? */
  1172. /* Boolean logic time: range X and range Y intersect if there is
  1173. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1174. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1175. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1176. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1177. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1178. */
  1179. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1180. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1181. *policy_out = policy;
  1182. return 1;
  1183. }
  1184. }
  1185. *policy_out = NULL;
  1186. return 1;
  1187. }
  1188. /** If <b>policy</b> implicitly allows connections to any port on
  1189. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1190. * true. Else return false.
  1191. **/
  1192. int
  1193. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1194. int warn)
  1195. {
  1196. addr_policy_t *p;
  1197. int r=0,i;
  1198. static struct {
  1199. uint32_t addr; uint32_t mask; const char *network;
  1200. } private_networks[] = {
  1201. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1202. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1203. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1204. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1205. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1206. { 0,0,NULL},
  1207. };
  1208. for (i=0; private_networks[i].addr; ++i) {
  1209. p = NULL;
  1210. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1211. if (policy_includes_addr_mask_implicitly(
  1212. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1213. if (warn)
  1214. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1215. p?p->string:"(default)",
  1216. private_networks[i].network);
  1217. r = 1;
  1218. }
  1219. }
  1220. return r;
  1221. }
  1222. /** Return true iff <b>router</b> does not permit exit streams.
  1223. */
  1224. int
  1225. router_exit_policy_rejects_all(routerinfo_t *router)
  1226. {
  1227. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1228. == ADDR_POLICY_REJECTED;
  1229. }
  1230. /** Release all space held in <b>rr</b>. */
  1231. void
  1232. running_routers_free(running_routers_t *rr)
  1233. {
  1234. if (!rr)
  1235. return;
  1236. if (rr->running_routers) {
  1237. SMARTLIST_FOREACH(rr->running_routers, char *, s, tor_free(s));
  1238. smartlist_free(rr->running_routers);
  1239. }
  1240. tor_free(rr);
  1241. }
  1242. /** Update the running/not-running status of every router in <b>list</b>, based
  1243. * on the contents of <b>rr</b>. */
  1244. static void
  1245. routerlist_update_from_runningrouters(routerlist_t *list,
  1246. running_routers_t *rr)
  1247. {
  1248. routerinfo_t *me = router_get_my_routerinfo();
  1249. smartlist_t *all_routers;
  1250. if (!list)
  1251. return;
  1252. if (list->published_on >= rr->published_on)
  1253. return;
  1254. if (list->running_routers_updated_on >= rr->published_on)
  1255. return;
  1256. all_routers = smartlist_create();
  1257. if (me) /* learn if the dirservers think I'm verified */
  1258. smartlist_add(all_routers, me);
  1259. smartlist_add_all(all_routers,list->routers);
  1260. SMARTLIST_FOREACH(rr->running_routers, const char *, cp,
  1261. routers_update_status_from_entry(all_routers, rr->published_on,
  1262. cp));
  1263. smartlist_free(all_routers);
  1264. list->running_routers_updated_on = rr->published_on;
  1265. }
  1266. /** We've just got a running routers list in <b>rr</b>; update the
  1267. * status of the routers in <b>list</b>, and cache <b>rr</b> */
  1268. void
  1269. routerlist_set_runningrouters(routerlist_t *list, running_routers_t *rr)
  1270. {
  1271. routerlist_update_from_runningrouters(list,rr);
  1272. if (list->running_routers != rr) {
  1273. running_routers_free(list->running_routers);
  1274. list->running_routers = rr;
  1275. }
  1276. }
  1277. /** Update the is_running and is_verified fields of the router <b>router</b>,
  1278. * based in its status in the list of strings stored in <b>running_list</b>.
  1279. * All entries in <b>running_list</b> follow one of these formats:
  1280. * <ol><li> <b>nickname</b> -- router is running and verified.
  1281. * (running-routers format)
  1282. * <li> !<b>nickname</b> -- router is not-running and verified.
  1283. * (running-routers format)
  1284. * <li> <b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1285. * verified. (router-status format)
  1286. * (router-status format)
  1287. * <li> !<b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1288. * verified. (router-status format)
  1289. * <li> !<b>nickname</b> -- router is not-running and verified.
  1290. * <li> $<b>hexdigest</b> -- router is running and unverified.
  1291. * <li> !$<b>hexdigest</b> -- router is not-running and unverified.
  1292. * </ol>
  1293. *
  1294. * Return 1 if we found router in running_list, else return 0.
  1295. */
  1296. int
  1297. routers_update_status_from_entry(smartlist_t *routers,
  1298. time_t list_time,
  1299. const char *s)
  1300. {
  1301. int authdir = get_options()->AuthoritativeDir;
  1302. int is_running = 1;
  1303. int is_verified = 0;
  1304. int hex_digest_set = 0;
  1305. char nickname[MAX_NICKNAME_LEN+1];
  1306. char hexdigest[HEX_DIGEST_LEN+1];
  1307. char digest[DIGEST_LEN];
  1308. const char *cp, *end;
  1309. /* First, parse the entry. */
  1310. cp = s;
  1311. if (*cp == '!') {
  1312. is_running = 0;
  1313. ++cp;
  1314. }
  1315. if (*cp != '$') {
  1316. /* It starts with a non-dollar character; that's a nickname. The nickname
  1317. * entry will either extend to a NUL (old running-routers format) or to an
  1318. * equals sign (new router-status format). */
  1319. is_verified = 1;
  1320. end = strchr(cp, '=');
  1321. if (!end)
  1322. end = strchr(cp,'\0');
  1323. tor_assert(end);
  1324. /* 'end' now points on character beyond the end of the nickname */
  1325. if (end == cp || end-cp > MAX_NICKNAME_LEN) {
  1326. log_fn(LOG_WARN, "Bad nickname length (%d) in router status entry (%s)",
  1327. (int)(end-cp), s);
  1328. return -1;
  1329. }
  1330. memcpy(nickname, cp, end-cp);
  1331. nickname[end-cp]='\0';
  1332. if (!is_legal_nickname(nickname)) {
  1333. log_fn(LOG_WARN, "Bad nickname (%s) in router status entry (%s)",
  1334. nickname, s);
  1335. return -1;
  1336. }
  1337. cp = end;
  1338. if (*cp == '=')
  1339. ++cp;
  1340. }
  1341. /* 'end' now points to the start of a hex digest, or EOS. */
  1342. /* Parse the hexdigest portion of the status. */
  1343. if (*cp == '$') {
  1344. hex_digest_set = 1;
  1345. ++cp;
  1346. if (strlen(cp) != HEX_DIGEST_LEN) {
  1347. log_fn(LOG_WARN, "Bad length (%d) on digest in router status entry (%s)",
  1348. (int)strlen(cp), s);
  1349. return -1;
  1350. }
  1351. strlcpy(hexdigest, cp, sizeof(hexdigest));
  1352. if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0) {
  1353. log_fn(LOG_WARN, "Invalid digest in router status entry (%s)", s);
  1354. return -1;
  1355. }
  1356. }
  1357. /* Make sure that the entry was in the right format. */
  1358. if (!hex_digest_set) {
  1359. log_fn(LOG_WARN, "Invalid syntax for router-status member (%s)", s);
  1360. return -1;
  1361. }
  1362. /* Okay, we're done parsing. For all routers that match, update their status.
  1363. */
  1364. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1365. {
  1366. int nickname_matches = is_verified && !strcasecmp(r->nickname, nickname);
  1367. int digest_matches = !memcmp(digest, r->identity_digest, DIGEST_LEN);
  1368. if (!authdir) {
  1369. /* If we're not an authoritative directory, update verified status.
  1370. */
  1371. if (nickname_matches && digest_matches)
  1372. r->is_verified = 1;
  1373. else if (digest_matches)
  1374. r->is_verified = 0;
  1375. }
  1376. if (digest_matches)
  1377. if (r->status_set_at < list_time) {
  1378. if (!authdir || is_running)
  1379. /* If we're an authoritative directory, only believe that servers
  1380. * are down when we hear it ourselves. Otherwise, believe
  1381. * what we're told.
  1382. */
  1383. r->is_running = is_running;
  1384. r->status_set_at = time(NULL);
  1385. }
  1386. });
  1387. return 0;
  1388. }
  1389. /** As router_update_status_from_entry, but consider all entries in
  1390. * running_list. */
  1391. int
  1392. router_update_status_from_smartlist(routerinfo_t *router,
  1393. time_t list_time,
  1394. smartlist_t *running_list)
  1395. {
  1396. smartlist_t *rl;
  1397. rl = smartlist_create();
  1398. smartlist_add(rl,router);
  1399. SMARTLIST_FOREACH(running_list, const char *, cp,
  1400. routers_update_status_from_entry(rl,list_time,cp));
  1401. smartlist_free(rl);
  1402. return 0;
  1403. }
  1404. /** Add to the list of authorized directory servers one at
  1405. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  1406. * <b>address</b> is NULL, add ourself. */
  1407. void
  1408. add_trusted_dir_server(const char *address, uint16_t port, const char *digest)
  1409. {
  1410. trusted_dir_server_t *ent;
  1411. uint32_t a;
  1412. char *hostname = NULL;
  1413. if (!trusted_dir_servers)
  1414. trusted_dir_servers = smartlist_create();
  1415. if (!address) { /* The address is us; we should guess. */
  1416. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  1417. log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
  1418. return;
  1419. }
  1420. } else {
  1421. if (tor_lookup_hostname(address, &a)) {
  1422. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1423. address);
  1424. return;
  1425. }
  1426. hostname = tor_strdup(address);
  1427. a = ntohl(a);
  1428. }
  1429. ent = tor_malloc(sizeof(trusted_dir_server_t));
  1430. ent->address = hostname;
  1431. ent->addr = a;
  1432. ent->dir_port = port;
  1433. ent->is_running = 1;
  1434. memcpy(ent->digest, digest, DIGEST_LEN);
  1435. smartlist_add(trusted_dir_servers, ent);
  1436. }
  1437. /** Remove all members from the list of trusted dir servers. */
  1438. void
  1439. clear_trusted_dir_servers(void)
  1440. {
  1441. if (trusted_dir_servers) {
  1442. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1443. { tor_free(ent->address); tor_free(ent); });
  1444. smartlist_clear(trusted_dir_servers);
  1445. } else {
  1446. trusted_dir_servers = smartlist_create();
  1447. }
  1448. }