Forward port changelog
[tor.git] / src / or / routerlist.c
blob10c43006e399ba51f0932973a62df28085ebf6fe
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char routerlist_c_id[] = "$Id$";
8 #include "or.h"
10 /**
11 * \file routerlist.c
13 * \brief Code to
14 * maintain and access the global list of routerinfos for known
15 * servers.
16 **/
18 /****************************************************************************/
20 static smartlist_t *trusted_dir_servers = NULL;
22 /* static function prototypes */
23 static routerinfo_t *
24 router_pick_directory_server_impl(int requireothers, int fascistfirewall,
25 int for_runningrouters);
26 static trusted_dir_server_t *
27 router_pick_trusteddirserver_impl(int requireother, int fascistfirewall);
28 static void mark_all_trusteddirservers_up(void);
29 static int router_resolve_routerlist(routerlist_t *dir);
31 /****************************************************************************/
33 /****
34 * Functions to manage and access our list of known routers. (Note:
35 * dirservers maintain a separate, independent list of known router
36 * descriptors.)
37 *****/
39 /** Global list of all of the routers that we, as an OR or OP, know about. */
40 static routerlist_t *routerlist = NULL;
42 extern int has_fetched_directory; /**< from main.c */
44 /**
45 * Reload the original list of trusted dirservers, and the most recent
46 * cached directory (if present).
48 int router_reload_router_list(void)
50 char filename[512];
51 int is_recent;
52 struct stat st;
53 char *s;
54 tor_assert(get_options()->DataDirectory);
56 tor_snprintf(filename,sizeof(filename),"%s/cached-directory",
57 get_options()->DataDirectory);
58 s = read_file_to_str(filename,0);
59 if (s) {
60 stat(filename, &st); /* if s is true, stat probably worked */
61 log_fn(LOG_INFO, "Loading cached directory from %s", filename);
62 is_recent = st.st_mtime > time(NULL) - 60*15;
63 if (router_load_routerlist_from_directory(s, NULL, is_recent, 1) < 0) {
64 log_fn(LOG_WARN, "Cached directory at '%s' was unparseable; ignoring.", filename);
66 if (routerlist &&
67 ((routerlist->published_on > time(NULL) - MIN_ONION_KEY_LIFETIME/2)
68 || is_recent)) {
69 directory_has_arrived(st.st_mtime); /* do things we've been waiting to do */
71 tor_free(s);
73 return 0;
76 /* Set *<b>outp</b> to a smartlist containing a list of
77 * trusted_dir_server_t * for all known trusted dirservers. Callers
78 * must not modify the list or its contents.
80 void router_get_trusted_dir_servers(smartlist_t **outp)
82 if (!trusted_dir_servers)
83 trusted_dir_servers = smartlist_create();
85 *outp = trusted_dir_servers;
88 /** Try to find a running dirserver. If there are no running dirservers
89 * in our routerlist, set all the authoritative ones as running again,
90 * and pick one. If there are no dirservers at all in our routerlist,
91 * reload the routerlist and try one last time. If for_runningrouters is
92 * true, then only pick a dirserver that can answer runningrouters queries
93 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
95 routerinfo_t *router_pick_directory_server(int requireothers,
96 int fascistfirewall,
97 int for_runningrouters,
98 int retry_if_no_servers) {
99 routerinfo_t *choice;
101 if (!routerlist)
102 return NULL;
104 choice = router_pick_directory_server_impl(requireothers, fascistfirewall,
105 for_runningrouters);
106 if (choice || !retry_if_no_servers)
107 return choice;
109 log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
110 /* mark all authdirservers as up again */
111 mark_all_trusteddirservers_up();
112 /* try again */
113 choice = router_pick_directory_server_impl(requireothers, fascistfirewall,
114 for_runningrouters);
115 if (choice)
116 return choice;
118 log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
119 get_options()->FascistFirewall ? "reachable" : "known");
120 has_fetched_directory=0; /* reset it */
121 if (router_reload_router_list()) {
122 return NULL;
124 /* give it one last try */
125 choice = router_pick_directory_server_impl(requireothers, 0,
126 for_runningrouters);
127 return choice;
130 trusted_dir_server_t *router_pick_trusteddirserver(int requireothers,
131 int fascistfirewall,
132 int retry_if_no_servers) {
133 trusted_dir_server_t *choice;
135 choice = router_pick_trusteddirserver_impl(requireothers, fascistfirewall);
136 if (choice || !retry_if_no_servers)
137 return choice;
139 log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
140 /* mark all authdirservers as up again */
141 mark_all_trusteddirservers_up();
142 /* try again */
143 choice = router_pick_trusteddirserver_impl(requireothers, fascistfirewall);
144 if (choice)
145 return choice;
147 log_fn(LOG_WARN,"Still no dirservers %s. Reloading and trying again.",
148 get_options()->FascistFirewall ? "reachable" : "known");
149 has_fetched_directory=0; /* reset it */
150 if (router_reload_router_list()) {
151 return NULL;
153 /* give it one last try */
154 choice = router_pick_trusteddirserver_impl(requireothers, 0);
155 return choice;
158 /** Pick a random running router from our routerlist. If requireauth,
159 * it has to be a trusted server. If requireothers, it cannot be us.
161 static routerinfo_t *
162 router_pick_directory_server_impl(int requireothers, int fascistfirewall,
163 int for_runningrouters)
165 int i;
166 routerinfo_t *router;
167 smartlist_t *sl;
169 if (!routerlist)
170 return NULL;
172 if (get_options()->HttpProxy)
173 fascistfirewall = 0;
175 /* Find all the running dirservers we know about. */
176 sl = smartlist_create();
177 for (i=0;i< smartlist_len(routerlist->routers); i++) {
178 router = smartlist_get(routerlist->routers, i);
179 if (!router->is_running || !router->dir_port)
180 continue;
181 if (requireothers && router_is_me(router))
182 continue;
183 if (fascistfirewall) {
184 if (!smartlist_string_num_isin(get_options()->FirewallPorts, router->dir_port))
185 continue;
187 /* before 0.0.9rc5-cvs, only trusted dirservers served status info. */
188 if (for_runningrouters &&
189 !(tor_version_as_new_as(router->platform,"0.0.9rc5-cvs") ||
190 router_digest_is_trusted_dir(router->identity_digest)))
191 continue;
192 smartlist_add(sl, router);
195 router = smartlist_choose(sl);
196 smartlist_free(sl);
197 return router;
200 static trusted_dir_server_t *
201 router_pick_trusteddirserver_impl(int requireother, int fascistfirewall)
203 smartlist_t *sl;
204 routerinfo_t *me;
205 trusted_dir_server_t *ds;
206 sl = smartlist_create();
207 me = router_get_my_routerinfo();
209 if (!trusted_dir_servers)
210 return NULL;
212 if (get_options()->HttpProxy)
213 fascistfirewall = 0;
215 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
217 if (!d->is_running) continue;
218 if (requireother && me &&
219 !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
220 continue;
221 if (fascistfirewall) {
222 if (!smartlist_string_num_isin(get_options()->FirewallPorts, d->dir_port))
223 continue;
225 smartlist_add(sl, d);
228 ds = smartlist_choose(sl);
229 smartlist_free(sl);
230 return ds;
233 /** Go through and mark the auth dirservers as up */
234 static void mark_all_trusteddirservers_up(void) {
235 if (routerlist) {
236 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
237 if (router_digest_is_trusted_dir(router->identity_digest)) {
238 tor_assert(router->dir_port > 0);
239 router->is_running = 1;
240 router->status_set_at = time(NULL);
243 if (trusted_dir_servers) {
244 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
245 dir->is_running = 1);
249 /** Return 0 if \exists an authoritative dirserver that's currently
250 * thought to be running, else return 1.
252 int all_trusted_directory_servers_down(void) {
253 if (!trusted_dir_servers)
254 return 1;
255 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
256 if (dir->is_running) return 0);
257 return 1;
260 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
262 void routerlist_add_family(smartlist_t *sl, routerinfo_t *router) {
263 routerinfo_t *r;
264 struct config_line_t *cl;
266 if (!router->declared_family)
267 return;
269 /* Add every r such that router declares familyness with r, and r
270 * declares familyhood with router. */
271 SMARTLIST_FOREACH(router->declared_family, const char *, n,
273 if (!(r = router_get_by_nickname(n)))
274 continue;
275 if (!r->declared_family)
276 continue;
277 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
279 if (router_nickname_matches(router, n2))
280 smartlist_add(sl, r);
284 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
285 if (router_nickname_is_in_list(router, cl->value)) {
286 add_nickname_list_to_smartlist(sl, cl->value, 0);
291 /** Given a comma-and-whitespace separated list of nicknames, see which
292 * nicknames in <b>list</b> name routers in our routerlist that are
293 * currently running. Add the routerinfos for those routers to <b>sl</b>.
295 void
296 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
298 routerinfo_t *router;
299 smartlist_t *nickname_list;
301 if (!list)
302 return; /* nothing to do */
303 tor_assert(sl);
305 nickname_list = smartlist_create();
307 smartlist_split_string(nickname_list, list, ",",
308 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
310 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
311 if (!is_legal_nickname_or_hexdigest(nick)) {
312 log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
313 continue;
315 router = router_get_by_nickname(nick);
316 if (router) {
317 if (router->is_running)
318 smartlist_add(sl,router);
319 else
320 log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
321 "Nickname list includes '%s' which is known but down.",nick);
322 } else
323 log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
324 "Nickname list includes '%s' which isn't a known router.",nick);
326 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
327 smartlist_free(nickname_list);
330 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
331 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
334 router_nickname_is_in_list(routerinfo_t *router, const char *list)
336 smartlist_t *nickname_list;
337 int v = 0;
339 if (!list)
340 return 0; /* definitely not */
341 tor_assert(router);
343 nickname_list = smartlist_create();
344 smartlist_split_string(nickname_list, list, ",",
345 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
346 SMARTLIST_FOREACH(nickname_list, const char *, cp,
347 if (router_nickname_matches(router, cp)) {v=1;break;});
348 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
349 smartlist_free(nickname_list);
350 return v;
353 /** Add every router from our routerlist that is currently running to
354 * <b>sl</b>.
356 static void
357 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
358 int need_uptime, int need_capacity)
360 routerinfo_t *router;
361 int i;
363 if (!routerlist)
364 return;
366 for (i=0;i<smartlist_len(routerlist->routers);i++) {
367 router = smartlist_get(routerlist->routers, i);
368 if (router->is_running &&
369 (router->is_verified ||
370 (allow_unverified &&
371 !router_is_unreliable(router, need_uptime, need_capacity)))) {
372 /* If it's running, and either it's verified or we're ok picking
373 * unverified routers and this one is suitable.
375 smartlist_add(sl, router);
380 routerinfo_t *
381 routerlist_find_my_routerinfo(void) {
382 routerinfo_t *router;
383 int i;
385 if (!routerlist)
386 return NULL;
388 for (i=0;i<smartlist_len(routerlist->routers);i++) {
389 router = smartlist_get(routerlist->routers, i);
390 if (router_is_me(router))
391 return router;
393 return NULL;
397 router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
399 if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
400 return 1;
401 if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
402 return 1;
403 return 0;
406 static void
407 routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
409 int i;
410 routerinfo_t *router;
412 for (i = 0; i < smartlist_len(sl); ++i) {
413 router = smartlist_get(sl, i);
414 if (router_is_unreliable(router, 1, 0)) {
415 log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
416 router->nickname);
417 smartlist_del(sl, i--);
422 routerinfo_t *
423 routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
425 int i;
426 routerinfo_t *router;
427 smartlist_t *bandwidths;
428 uint32_t this_bw, tmp, total_bw=0, rand_bw;
429 uint32_t *p;
431 bandwidths = smartlist_create();
432 for (i = 0; i < smartlist_len(sl); ++i) {
433 router = smartlist_get(sl, i);
434 this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
435 router->bandwidthcapacity : router->bandwidthrate;
436 if (this_bw > 1000000)
437 this_bw = 1000000; /* if they claim something huge, don't believe it */
438 p = tor_malloc(sizeof(uint32_t));
439 *p = this_bw;
440 smartlist_add(bandwidths, p);
441 total_bw += this_bw;
442 // log_fn(LOG_INFO,"Recording bw %d for node %s.", this_bw, router->nickname);
444 if (!total_bw) {
445 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
446 smartlist_free(bandwidths);
447 return smartlist_choose(sl);
449 rand_bw = crypto_pseudo_rand_int(total_bw);
450 // log_fn(LOG_INFO,"Total bw %d. Randomly chose %d.", total_bw, rand_bw);
451 tmp = 0;
452 for (i=0; ; i++) {
453 tor_assert(i < smartlist_len(sl));
454 p = smartlist_get(bandwidths, i);
455 tmp += *p;
456 router = smartlist_get(sl, i);
457 // log_fn(LOG_INFO,"Considering %s. tmp = %d.", router->nickname, tmp);
458 if (tmp >= rand_bw)
459 break;
461 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
462 smartlist_free(bandwidths);
463 router = smartlist_get(sl, i);
464 // log_fn(LOG_INFO,"Picked %s.", router->nickname);
465 return router;
468 /** Return a random running router from the routerlist. If any node
469 * named in <b>preferred</b> is available, pick one of those. Never
470 * pick a node named in <b>excluded</b>, or whose routerinfo is in
471 * <b>excludedsmartlist</b>, even if they are the only nodes
472 * available. If <b>strict</b> is true, never pick any node besides
473 * those in <b>preferred</b>.
475 routerinfo_t *router_choose_random_node(const char *preferred,
476 const char *excluded,
477 smartlist_t *excludedsmartlist,
478 int need_uptime, int need_capacity,
479 int allow_unverified, int strict)
481 smartlist_t *sl, *excludednodes;
482 routerinfo_t *choice;
484 excludednodes = smartlist_create();
485 add_nickname_list_to_smartlist(excludednodes,excluded,0);
487 /* try the preferred nodes first */
488 sl = smartlist_create();
489 add_nickname_list_to_smartlist(sl,preferred,1);
490 smartlist_subtract(sl,excludednodes);
491 if (excludedsmartlist)
492 smartlist_subtract(sl,excludedsmartlist);
493 if (need_uptime)
494 routerlist_sl_remove_unreliable_routers(sl);
495 if (need_capacity)
496 choice = routerlist_sl_choose_by_bandwidth(sl);
497 else
498 choice = smartlist_choose(sl);
499 smartlist_free(sl);
500 if (!choice && !strict) {
501 sl = smartlist_create();
502 router_add_running_routers_to_smartlist(sl, allow_unverified,
503 need_uptime, need_capacity);
504 smartlist_subtract(sl,excludednodes);
505 if (excludedsmartlist)
506 smartlist_subtract(sl,excludedsmartlist);
507 if (need_uptime)
508 routerlist_sl_remove_unreliable_routers(sl);
509 if (need_capacity)
510 choice = routerlist_sl_choose_by_bandwidth(sl);
511 else
512 choice = smartlist_choose(sl);
513 smartlist_free(sl);
515 smartlist_free(excludednodes);
516 if (!choice)
517 log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
518 return choice;
521 /** Return the router in our routerlist whose address is <b>addr</b> and
522 * whose OR port is <b>port</b>. Return NULL if no such router is known.
524 routerinfo_t *router_get_by_addr_port(uint32_t addr, uint16_t port) {
525 int i;
526 routerinfo_t *router;
528 if (!routerlist)
529 return NULL;
531 for (i=0;i<smartlist_len(routerlist->routers);i++) {
532 router = smartlist_get(routerlist->routers, i);
533 if ((router->addr == addr) && (router->or_port == port))
534 return router;
536 return NULL;
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 router_hex_digest_matches(routerinfo_t *router,
544 const char *hexdigest)
546 char digest[DIGEST_LEN];
547 tor_assert(hexdigest);
548 if (hexdigest[0] == '$')
549 ++hexdigest;
551 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
552 base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
553 return 0;
554 else
555 return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
558 /* Return true if <b>router</b>'s nickname matches <b>nickname</b>
559 * (case-insensitive), or if <b>router's</b> identity key digest
560 * matches a hexadecimal value stored in <b>nickname</b>. Return
561 * false otherwise.*/
562 int router_nickname_matches(routerinfo_t *router, const char *nickname)
564 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
565 return 1;
566 else
567 return router_hex_digest_matches(router, nickname);
570 /** Return the router in our routerlist whose (case-insensitive)
571 * nickname or (case-sensitive) hexadecimal key digest is
572 * <b>nickname</b>. Return NULL if no such router is known.
574 routerinfo_t *router_get_by_nickname(const char *nickname)
576 int i, maybedigest;
577 routerinfo_t *router;
578 char digest[DIGEST_LEN];
580 tor_assert(nickname);
581 if (!routerlist)
582 return NULL;
583 if (nickname[0] == '$')
584 return router_get_by_hexdigest(nickname);
586 maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
587 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
589 for (i=0;i<smartlist_len(routerlist->routers);i++) {
590 router = smartlist_get(routerlist->routers, i);
591 if (0 == strcasecmp(router->nickname, nickname) ||
592 (maybedigest && 0 == memcmp(digest, router->identity_digest,
593 DIGEST_LEN)))
594 return router;
597 return NULL;
600 /** Return true iff <b>digest</b> is the digest of the identity key of
601 * a trusted directory. */
602 int router_digest_is_trusted_dir(const char *digest) {
603 if (!trusted_dir_servers)
604 return 0;
605 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
606 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
607 return 0;
610 /** Return the router in our routerlist whose hexadecimal key digest
611 * is <b>hexdigest</b>. Return NULL if no such router is known. */
612 routerinfo_t *router_get_by_hexdigest(const char *hexdigest) {
613 char digest[DIGEST_LEN];
615 tor_assert(hexdigest);
616 if (!routerlist)
617 return NULL;
618 if (hexdigest[0]=='$')
619 ++hexdigest;
620 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
621 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
622 return NULL;
624 return router_get_by_digest(digest);
627 /** Return the router in our routerlist whose 20-byte key digest
628 * is <b>hexdigest</b>. Return NULL if no such router is known. */
629 routerinfo_t *router_get_by_digest(const char *digest) {
630 int i;
631 routerinfo_t *router;
633 tor_assert(digest);
634 if (!routerlist) return NULL;
636 for (i=0;i<smartlist_len(routerlist->routers);i++) {
637 router = smartlist_get(routerlist->routers, i);
638 if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
639 return router;
642 return NULL;
645 /** Set *<b>prouterlist</b> to the current list of all known routers. */
646 void router_get_routerlist(routerlist_t **prouterlist) {
647 *prouterlist = routerlist;
650 /** Return the publication time on the current routerlist, or 0 if we have no
651 * routerlist. */
652 time_t routerlist_get_published_time(void) {
653 return routerlist ? routerlist->published_on : 0;
656 /** Free all storage held by <b>router</b>. */
657 void routerinfo_free(routerinfo_t *router)
659 if (!router)
660 return;
662 tor_free(router->address);
663 tor_free(router->nickname);
664 tor_free(router->platform);
665 if (router->onion_pkey)
666 crypto_free_pk_env(router->onion_pkey);
667 if (router->identity_pkey)
668 crypto_free_pk_env(router->identity_pkey);
669 if (router->declared_family) {
670 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
671 smartlist_free(router->declared_family);
673 addr_policy_free(router->exit_policy);
674 tor_free(router);
677 /** Allocate a fresh copy of <b>router</b> */
678 routerinfo_t *routerinfo_copy(const routerinfo_t *router)
680 routerinfo_t *r;
681 addr_policy_t **e, *tmp;
683 r = tor_malloc(sizeof(routerinfo_t));
684 memcpy(r, router, sizeof(routerinfo_t));
686 r->address = tor_strdup(r->address);
687 r->nickname = tor_strdup(r->nickname);
688 r->platform = tor_strdup(r->platform);
689 if (r->onion_pkey)
690 r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
691 if (r->identity_pkey)
692 r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
693 e = &r->exit_policy;
694 while (*e) {
695 tmp = tor_malloc(sizeof(addr_policy_t));
696 memcpy(tmp,*e,sizeof(addr_policy_t));
697 *e = tmp;
698 (*e)->string = tor_strdup((*e)->string);
699 e = & ((*e)->next);
701 if (r->declared_family) {
702 r->declared_family = smartlist_create();
703 SMARTLIST_FOREACH(router->declared_family, const char *, s,
704 smartlist_add(r->declared_family, tor_strdup(s)));
706 return r;
709 /** Free all storage held by a routerlist <b>rl</b> */
710 void routerlist_free(routerlist_t *rl)
712 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
713 routerinfo_free(r));
714 smartlist_free(rl->routers);
715 tor_free(rl->software_versions);
716 tor_free(rl);
719 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
720 void router_mark_as_down(const char *digest) {
721 routerinfo_t *router;
722 tor_assert(digest);
724 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
725 if (!memcmp(d->digest, digest, DIGEST_LEN))
726 d->is_running = 0);
728 router = router_get_by_digest(digest);
729 if (!router) /* we don't seem to know about him in the first place */
730 return;
731 log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
732 if (router_is_me(router))
733 log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
734 router->is_running = 0;
735 router->status_set_at = time(NULL);
738 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
739 * older entries (if any) with the same name. Note: Callers should not hold
740 * their pointers to <b>router</b> after invoking this function; <b>router</b>
741 * will either be inserted into the routerlist or freed. Returns 0 if the
742 * router was added; -1 if it was not.
744 static int
745 router_add_to_routerlist(routerinfo_t *router) {
746 int i;
747 routerinfo_t *r;
748 char id_digest[DIGEST_LEN];
750 tor_assert(routerlist);
751 crypto_pk_get_digest(router->identity_pkey, id_digest);
753 /* If we have a router with this name, and the identity key is the same,
754 * choose the newer one. If the identity key has changed, drop the router.
756 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
757 r = smartlist_get(routerlist->routers, i);
759 if (!crypto_pk_cmp_keys(router->identity_pkey, r->identity_pkey)) {
760 if (router->published_on > r->published_on) {
761 log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
762 router->nickname, r->nickname, hex_str(id_digest,DIGEST_LEN));
763 /* Remember whether we trust this router as a dirserver. */
764 /* If the address hasn't changed; no need to re-resolve. */
765 if (!strcasecmp(r->address, router->address))
766 router->addr = r->addr;
767 routerinfo_free(r);
768 smartlist_set(routerlist->routers, i, router);
769 return 0;
770 } else {
771 log_fn(LOG_DEBUG, "Skipping old entry for router '%s'",
772 router->nickname);
773 /* Update the is_running status to whatever we were told. */
774 r->is_running = router->is_running;
775 routerinfo_free(router);
776 return -1;
778 } else if (!strcasecmp(router->nickname, r->nickname)) {
779 /* nicknames match, keys don't. */
780 if (router->is_verified) {
781 /* The new verified router replaces the old one; remove the
782 * old one. And carry on to the end of the list, in case
783 * there are more old unverified routers with this nickname
785 /* mark-for-close connections using the old key, so we can
786 * make new ones with the new key.
788 connection_t *conn;
789 while ((conn = connection_get_by_identity_digest(r->identity_digest,
790 CONN_TYPE_OR))) {
791 log_fn(LOG_INFO,"Closing conn to obsolete router '%s'", r->nickname);
792 connection_mark_for_close(conn);
794 routerinfo_free(r);
795 smartlist_del_keeporder(routerlist->routers, i--);
796 } else if (r->is_verified) {
797 /* Can't replace a verified router with an unverified one. */
798 log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
799 router->nickname);
800 routerinfo_free(router);
801 return -1;
805 /* We haven't seen a router with this name before. Add it to the end of
806 * the list. */
807 smartlist_add(routerlist->routers, router);
808 return 0;
811 /** Remove any routers from the routerlist that are more than <b>age</b>
812 * seconds old.
814 * (This function is just like dirserv_remove_old_servers. One day we should
815 * merge them.)
817 void
818 routerlist_remove_old_routers(int age)
820 int i;
821 time_t cutoff;
822 routerinfo_t *router;
823 if (!routerlist)
824 return;
826 cutoff = time(NULL) - age;
827 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
828 router = smartlist_get(routerlist->routers, i);
829 if (router->published_on <= cutoff) {
830 /* Too old. Remove it. */
831 log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
832 routerinfo_free(router);
833 smartlist_del(routerlist->routers, i--);
839 * Code to parse router descriptors and directories.
842 /** Add to the current routerlist each router stored in the
843 * signed directory <b>s</b>. If pkey is provided, check the signature against
844 * pkey; else check against the pkey of the signing directory server.
846 * If <b>dir_is_recent</b> is non-zero, then examine the
847 * Recommended-versions line and take appropriate action.
849 * If <b>dir_is_cached</b> is non-zero, then we're reading it
850 * from the cache so don't bother to re-write it to the cache.
852 int router_load_routerlist_from_directory(const char *s,
853 crypto_pk_env_t *pkey,
854 int dir_is_recent,
855 int dir_is_cached)
857 routerlist_t *new_list = NULL;
858 if (router_parse_routerlist_from_directory(s, &new_list, pkey,
859 dir_is_recent,
860 !dir_is_cached)) {
861 log_fn(LOG_WARN, "Couldn't parse directory.");
862 return -1;
864 if (routerlist) {
865 SMARTLIST_FOREACH(new_list->routers, routerinfo_t *, r,
866 router_add_to_routerlist(r));
867 smartlist_clear(new_list->routers);
868 routerlist->published_on = new_list->published_on;
869 tor_free(routerlist->software_versions);
870 routerlist->software_versions = new_list->software_versions;
871 new_list->software_versions = NULL;
872 routerlist_free(new_list);
873 } else {
874 routerlist = new_list;
876 if (router_resolve_routerlist(routerlist)) {
877 log_fn(LOG_WARN, "Error resolving routerlist");
878 return -1;
880 if (get_options()->AuthoritativeDir) {
881 /* Learn about the descriptors in the directory. */
882 dirserv_load_from_directory_string(s);
884 return 0;
887 /** Helper function: resolve the hostname for <b>router</b>. */
888 static int
889 router_resolve(routerinfo_t *router)
891 if (tor_lookup_hostname(router->address, &router->addr) != 0
892 || !router->addr) {
893 log_fn(LOG_WARN,"Could not resolve address for router '%s' at %s",
894 router->nickname, router->address);
895 return -1;
897 router->addr = ntohl(router->addr); /* get it back into host order */
899 return 0;
902 /** Helper function: resolve every router in rl, and ensure that our own
903 * routerinfo is at the front.
905 static int
906 router_resolve_routerlist(routerlist_t *rl)
908 int i, remove;
909 routerinfo_t *r;
910 if (!rl)
911 rl = routerlist;
913 i = 0;
914 if ((r = router_get_my_routerinfo())) {
915 smartlist_insert(rl->routers, 0, routerinfo_copy(r));
916 ++i;
919 for ( ; i < smartlist_len(rl->routers); ++i) {
920 remove = 0;
921 r = smartlist_get(rl->routers,i);
922 if (router_is_me(r)) {
923 remove = 1;
924 } else if (r->addr) {
925 /* already resolved. */
926 } else if (router_resolve(r)) {
927 log_fn(LOG_WARN, "Couldn't resolve router '%s' at '%s'; not using",
928 r->nickname, r->address);
929 remove = 1;
931 if (remove) {
932 routerinfo_free(r);
933 smartlist_del_keeporder(rl->routers, i--);
937 return 0;
940 /** Decide whether a given addr:port is definitely accepted, definitely
941 * rejected, or neither by a given policy. If <b>addr</b> is 0, we
942 * don't know the IP of the target address. If <b>port</b> is 0, we
943 * don't know the port of the target address.
945 * Returns -1 for "rejected", 0 for "accepted", 1 for "maybe" (since IP or
946 * port is unknown).
948 int router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
949 addr_policy_t *policy)
951 int maybe_reject = 0;
952 int maybe_accept = 0;
953 int match = 0;
954 int maybe = 0;
955 addr_policy_t *tmpe;
957 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
958 // log_fn(LOG_DEBUG,"Considering exit policy %s", tmpe->string);
959 maybe = 0;
960 if (!addr) {
961 /* Address is unknown. */
962 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
963 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
964 /* The port definitely matches. */
965 if (tmpe->msk == 0) {
966 match = 1;
967 } else {
968 maybe = 1;
970 } else if (!port) {
971 /* The port maybe matches. */
972 maybe = 1;
974 } else {
975 /* Address is known */
976 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
977 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
978 /* Exact match for the policy */
979 match = 1;
980 } else if (!port) {
981 maybe = 1;
985 if (maybe) {
986 if (tmpe->policy_type == ADDR_POLICY_REJECT)
987 maybe_reject = 1;
988 else
989 maybe_accept = 1;
991 if (match) {
992 // struct in_addr in;
993 // in.s_addr = htonl(addr);
994 // log_fn(LOG_DEBUG,"Address %s:%d matches policy '%s'",
995 // inet_ntoa(in), port, tmpe->string);
996 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
997 /* If we already hit a clause that might trigger a 'reject', than we
998 * can't be sure of this certain 'accept'.*/
999 return maybe_reject ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_ACCEPTED;
1000 } else {
1001 return maybe_accept ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_REJECTED;
1005 /* accept all by default. */
1006 return maybe_reject ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_ACCEPTED;
1009 /** Return 1 if all running sufficiently-stable routers will reject
1010 * addr:port, return 0 if any might accept it. */
1011 int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
1012 int need_uptime) {
1013 int i;
1014 routerinfo_t *router;
1015 if (!routerlist) return 1;
1017 for (i=0;i<smartlist_len(routerlist->routers);i++) {
1018 router = smartlist_get(routerlist->routers, i);
1019 if (router->is_running &&
1020 !router_is_unreliable(router, need_uptime, 0) &&
1021 router_compare_addr_to_addr_policy(
1022 addr, port, router->exit_policy) != ADDR_POLICY_REJECTED)
1023 return 0; /* this one could be ok. good enough. */
1025 return 1; /* all will reject. */
1029 * If <b>policy</b> implicitly allows connections to any port in the
1030 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
1031 * part of the policy that allows it, and return 1. Else return 0.
1033 * A policy allows an IP:Port combination <em>implicitly</em> if
1034 * it is included in a *: pattern, or in a fallback pattern.
1036 static int
1037 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
1038 uint32_t addr, uint32_t mask,
1039 addr_policy_t **policy_out)
1041 uint32_t addr2;
1042 tor_assert(policy_out);
1043 addr &= mask;
1044 addr2 = addr | ~mask;
1045 for (; policy; policy=policy->next) {
1046 /* Does this policy cover all of the address range we're looking at? */
1047 /* Boolean logic time: range X is contained in range Y if, for
1048 * each bit B, all possible values of B in X are values of B in Y.
1049 * In "addr", we have every fixed bit set to its value, and every
1050 * free bit set to 0. In "addr2", we have every fixed bit set to
1051 * its value, and every free bit set to 1. So if addr and addr2 are
1052 * both in the policy, the range is covered by the policy.
1054 if ((policy->addr & policy->msk) == (addr & policy->msk) &&
1055 (policy->addr & policy->msk) == (addr2 & policy->msk) &&
1056 (policy->prt_min <= 1 && policy->prt_max == 65535)) {
1057 return 0;
1059 /* Does this policy cover some of the address range we're looking at? */
1060 /* Boolean logic time: range X and range Y intersect if there is
1061 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
1062 * This is FALSE iff there is some bit b where Xmask == yMask == 1
1063 * and Xaddr != Yaddr. So if X intersects with Y iff at every
1064 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
1065 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
1067 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
1068 policy->policy_type == ADDR_POLICY_ACCEPT) {
1069 *policy_out = policy;
1070 return 1;
1073 *policy_out = NULL;
1074 return 1;
1077 /** If <b>policy</b> implicitly allows connections to any port on
1078 * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
1079 * true. Else return false.
1082 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
1083 int warn)
1085 addr_policy_t *p;
1086 int r=0,i;
1087 static struct {
1088 uint32_t addr; uint32_t mask; const char *network;
1089 } private_networks[] = {
1090 { 0x7f000000, 0xff000000, "localhost (127.x)" },
1091 { 0x0a000000, 0xff000000, "addresses in private network 10.x" },
1092 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.x" },
1093 { 0xac100000, 0xfff00000, "addresses in private network 172.16.x" },
1094 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.x" },
1095 { 0,0,NULL},
1097 for (i=0; private_networks[i].addr; ++i) {
1098 p = NULL;
1099 if (policy_includes_addr_mask_implicitly(
1100 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
1101 if (warn)
1102 log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
1103 p?p->string:"(default)",
1104 private_networks[i].network);
1105 r = 1;
1109 return r;
1112 /** Return true iff <b>router</b> does not permit exit streams.
1114 int router_exit_policy_rejects_all(routerinfo_t *router) {
1115 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
1116 == ADDR_POLICY_REJECTED;
1119 /** Release all space held in <b>rr</b>. */
1120 void running_routers_free(running_routers_t *rr)
1122 tor_assert(rr);
1123 if (rr->running_routers) {
1124 SMARTLIST_FOREACH(rr->running_routers, char *, s, tor_free(s));
1125 smartlist_free(rr->running_routers);
1127 tor_free(rr);
1130 /** Update the running/not-running status of every router in <b>list</b>, based
1131 * on the contents of <b>rr</b>. */
1132 /* Note: this function is not yet used, since nobody publishes just
1133 * running-router lists yet. */
1134 void routerlist_update_from_runningrouters(routerlist_t *list,
1135 running_routers_t *rr)
1137 routerinfo_t *me = router_get_my_routerinfo();
1138 smartlist_t *all_routers;
1139 if (!list)
1140 return;
1141 if (list->published_on >= rr->published_on)
1142 return;
1143 if (list->running_routers_updated_on >= rr->published_on)
1144 return;
1146 all_routers = smartlist_create();
1147 if (me) /* learn if the dirservers think I'm verified */
1148 smartlist_add(all_routers, me);
1150 smartlist_add_all(all_routers,list->routers);
1151 SMARTLIST_FOREACH(rr->running_routers, const char *, cp,
1152 routers_update_status_from_entry(all_routers, rr->published_on,
1153 cp, rr->is_running_routers_format));
1154 smartlist_free(all_routers);
1155 list->running_routers_updated_on = rr->published_on;
1158 /** Update the is_running and is_verified fields of the router <b>router</b>,
1159 * based in its status in the list of strings stored in <b>running_list</b>.
1160 * All entries in <b>running_list</b> follow one of these formats:
1161 * <ol><li> <b>nickname</b> -- router is running and verified.
1162 * (running-routers format)
1163 * <li> !<b>nickname</b> -- router is not-running and verified.
1164 * (running-routers format)
1165 * <li> <b>nickname</b>=$<b>hexdigest</b> -- router is running and
1166 * verified. (router-status format)
1167 * (router-status format)
1168 * <li> !<b>nickname</b>=$<b>hexdigest</b> -- router is running and
1169 * verified. (router-status format)
1170 * <li> !<b>nickname</b> -- router is not-running and verified.
1171 * <li> $<b>hexdigest</b> -- router is running and unverified.
1172 * <li> !$<b>hexdigest</b> -- router is not-running and unverified.
1173 * </ol>
1175 * Return 1 if we found router in running_list, else return 0.
1177 int routers_update_status_from_entry(smartlist_t *routers,
1178 time_t list_time,
1179 const char *s,
1180 int rr_format)
1182 int is_running = 1;
1183 int is_verified = 0;
1184 int hex_digest_set = 0;
1185 char nickname[MAX_NICKNAME_LEN+1];
1186 char hexdigest[HEX_DIGEST_LEN+1];
1187 char digest[DIGEST_LEN];
1188 const char *cp, *end;
1190 /* First, parse the entry. */
1191 cp = s;
1192 if (*cp == '!') {
1193 is_running = 0;
1194 ++cp;
1197 if (*cp != '$') {
1198 /* It starts with a non-dollar character; that's a nickname. The nickname
1199 * entry will either extend to a NUL (old running-routers format) or to an
1200 * equals sign (new router-status format). */
1201 is_verified = 1;
1202 end = strchr(cp, '=');
1203 if (!end)
1204 end = strchr(cp,'\0');
1205 tor_assert(end);
1206 /* 'end' now points on character beyond the end of the nickname */
1207 if (end == cp || end-cp > MAX_NICKNAME_LEN) {
1208 log_fn(LOG_WARN, "Bad nickname length (%d) in router status entry (%s)",
1209 (int)(end-cp), s);
1210 return -1;
1212 memcpy(nickname, cp, end-cp);
1213 nickname[end-cp]='\0';
1214 if (!is_legal_nickname(nickname)) {
1215 log_fn(LOG_WARN, "Bad nickname (%s) in router status entry (%s)",
1216 nickname, s);
1217 return -1;
1219 cp = end;
1220 if (*cp == '=')
1221 ++cp;
1223 /* 'end' now points to the start of a hex digest, or EOS. */
1225 /* Parse the hexdigest portion of the status. */
1226 if (*cp == '$') {
1227 hex_digest_set = 1;
1228 ++cp;
1229 if (strlen(cp) != HEX_DIGEST_LEN) {
1230 log_fn(LOG_WARN, "Bad length (%d) on digest in router status entry (%s)",
1231 (int)strlen(cp), s);
1232 return -1;
1234 strlcpy(hexdigest, cp, sizeof(hexdigest));
1235 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0) {
1236 log_fn(LOG_WARN, "Invalid digest in router status entry (%s)", s);
1237 return -1;
1241 /* Make sure that the entry was in the right format. */
1242 if (rr_format) {
1243 if (is_verified == hex_digest_set) {
1244 log_fn(LOG_WARN, "Invalid syntax for running-routers member (%s)", s);
1245 return -1;
1247 } else {
1248 if (!hex_digest_set) {
1249 log_fn(LOG_WARN, "Invalid syntax for router-status member (%s)", s);
1250 return -1;
1254 /* Okay, we're done parsing. For all routers that match, update their status.
1256 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
1258 int nickname_matches = is_verified && !strcasecmp(r->nickname, nickname);
1259 int digest_matches = !memcmp(digest, r->identity_digest, DIGEST_LEN);
1260 if (nickname_matches && (digest_matches||rr_format))
1261 r->is_verified = 1;
1262 else if (digest_matches)
1263 r->is_verified = 0;
1264 if (digest_matches || (nickname_matches&&rr_format))
1265 if (r->status_set_at < list_time) {
1266 r->is_running = is_running;
1267 r->status_set_at = time(NULL);
1271 return 0;
1274 /** As router_update_status_from_entry, but consider all entries in
1275 * running_list. */
1277 router_update_status_from_smartlist(routerinfo_t *router,
1278 time_t list_time,
1279 smartlist_t *running_list,
1280 int rr_format)
1282 smartlist_t *rl;
1283 rl = smartlist_create();
1284 smartlist_add(rl,router);
1285 SMARTLIST_FOREACH(running_list, const char *, cp,
1286 routers_update_status_from_entry(rl,list_time,cp,rr_format));
1287 smartlist_free(rl);
1288 return 0;
1291 /** Add to the list of authorized directory servers one at
1292 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. */
1293 void
1294 add_trusted_dir_server(const char *address, uint16_t port, const char *digest)
1296 trusted_dir_server_t *ent;
1297 uint32_t a;
1298 if (!trusted_dir_servers)
1299 trusted_dir_servers = smartlist_create();
1301 if (tor_lookup_hostname(address, &a)) {
1302 log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
1303 address);
1304 return;
1307 ent = tor_malloc(sizeof(trusted_dir_server_t));
1308 ent->address = tor_strdup(address);
1309 ent->addr = ntohl(a);
1310 ent->dir_port = port;
1311 ent->is_running = 1;
1312 memcpy(ent->digest, digest, DIGEST_LEN);
1313 smartlist_add(trusted_dir_servers, ent);
1316 void clear_trusted_dir_servers(void)
1318 if (trusted_dir_servers) {
1319 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1320 { tor_free(ent->address); tor_free(ent); });
1321 smartlist_clear(trusted_dir_servers);
1322 } else {
1323 trusted_dir_servers = smartlist_create();