r13086@catbus: nickm | 2007-05-30 01:08:30 -0400
[tor.git] / src / or / routerlist.c
bloba3228a351735316a81a67787a6d53545fe3bc9c7
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char routerlist_c_id[] =
7 "$Id$";
9 /**
10 * \file routerlist.c
11 * \brief Code to
12 * maintain and access the global list of routerinfos for known
13 * servers.
14 **/
16 #include "or.h"
18 /****************************************************************************/
20 /* static function prototypes */
21 static routerstatus_t *router_pick_directory_server_impl(int requireother,
22 int fascistfirewall,
23 int prefer_tunnel,
24 int for_v2_directory);
25 static routerstatus_t *router_pick_trusteddirserver_impl(
26 authority_type_t type, int requireother,
27 int fascistfirewall, int prefer_tunnel);
28 static void mark_all_trusteddirservers_up(void);
29 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
30 static void routerstatus_list_update_from_networkstatus(time_t now);
31 static void local_routerstatus_free(local_routerstatus_t *rs);
32 static void trusted_dir_server_free(trusted_dir_server_t *ds);
33 static void update_networkstatus_cache_downloads(time_t now);
34 static void update_networkstatus_client_downloads(time_t now);
35 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
36 static void routerlist_assert_ok(routerlist_t *rl);
37 static int have_tried_downloading_all_statuses(int n_failures);
38 static routerstatus_t *networkstatus_find_entry(networkstatus_t *ns,
39 const char *digest);
40 static local_routerstatus_t *router_get_combined_status_by_nickname(
41 const char *nickname,
42 int warn_if_unnamed);
43 static void update_router_have_minimum_dir_info(void);
44 static void router_dir_info_changed(void);
46 /****************************************************************************/
48 /** Global list of a trusted_dir_server_t object for each trusted directory
49 * server. */
50 static smartlist_t *trusted_dir_servers = NULL;
52 /** Global list of all of the routers that we know about. */
53 static routerlist_t *routerlist = NULL;
55 /** Global list of all of the current network_status documents that we know
56 * about. This list is kept sorted by published_on. */
57 static smartlist_t *networkstatus_list = NULL;
59 /** Global list of local_routerstatus_t for each router, known or unknown.
60 * Kept sorted by digest. */
61 static smartlist_t *routerstatus_list = NULL;
63 /** Map from lowercase nickname to digest of named server, if any. */
64 static strmap_t *named_server_map = NULL;
66 /** True iff any member of networkstatus_list has changed since the last time
67 * we called routerstatus_list_update_from_networkstatus(). */
68 static int networkstatus_list_has_changed = 0;
70 /** True iff any element of routerstatus_list has changed since the last
71 * time we called routers_update_all_from_networkstatus().*/
72 static int routerstatus_list_has_changed = 0;
74 /** List of strings for nicknames we've already warned about and that are
75 * still unknown / unavailable. */
76 static smartlist_t *warned_nicknames = NULL;
78 /** List of strings for nicknames or fingerprints we've already warned about
79 * and that are still conflicted. */
80 static smartlist_t *warned_conflicts = NULL;
82 /** The last time we tried to download any routerdesc, or 0 for "never". We
83 * use this to rate-limit download attempts when the number of routerdescs to
84 * download is low. */
85 static time_t last_routerdesc_download_attempted = 0;
87 /** The last time we tried to download a networkstatus, or 0 for "never". We
88 * use this to rate-limit download attempts for directory caches (including
89 * mirrors). Clients don't use this now. */
90 static time_t last_networkstatus_download_attempted = 0;
92 /** True iff we have logged a warning about this OR not being valid or
93 * not being named. */
94 static int have_warned_about_invalid_status = 0;
95 /** True iff we have logged a warning about this OR's version being older than
96 * listed by the authorities */
97 static int have_warned_about_old_version = 0;
98 /** True iff we have logged a warning about this OR's version being newer than
99 * listed by the authorities */
100 static int have_warned_about_new_version = 0;
102 /** Return the number of v2 directory authorities */
103 static INLINE int
104 get_n_v2_authorities(void)
106 int n = 0;
107 if (!trusted_dir_servers)
108 return 0;
109 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
110 if (ds->is_v2_authority)
111 ++n);
112 return n;
115 /** Repopulate our list of network_status_t objects from the list cached on
116 * disk. Return 0 on success, -1 on failure. */
118 router_reload_networkstatus(void)
120 char filename[512];
121 smartlist_t *entries;
122 struct stat st;
123 char *s;
124 tor_assert(get_options()->DataDirectory);
125 if (!networkstatus_list)
126 networkstatus_list = smartlist_create();
128 tor_snprintf(filename,sizeof(filename),"%s/cached-status",
129 get_options()->DataDirectory);
130 entries = tor_listdir(filename);
131 SMARTLIST_FOREACH(entries, const char *, fn, {
132 char buf[DIGEST_LEN];
133 if (strlen(fn) != HEX_DIGEST_LEN ||
134 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
135 log_info(LD_DIR,
136 "Skipping cached-status file with unexpected name \"%s\"",fn);
137 continue;
139 tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
140 get_options()->DataDirectory, fn);
141 s = read_file_to_str(filename, 0, &st);
142 if (s) {
143 if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
144 log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
146 tor_free(s);
149 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
150 smartlist_free(entries);
151 networkstatus_list_clean(time(NULL));
152 routers_update_all_from_networkstatus();
153 return 0;
156 /* Router descriptor storage.
158 * Routerdescs are stored in a big file, named "cached-routers". As new
159 * routerdescs arrive, we append them to a journal file named
160 * "cached-routers.new".
162 * From time to time, we replace "cached-routers" with a new file containing
163 * only the live, non-superseded descriptors, and clear cached-routers.new.
165 * On startup, we read both files.
168 /** The size of the router log, in bytes. */
169 static size_t router_journal_len = 0;
170 /** The size of the router store, in bytes. */
171 static size_t router_store_len = 0;
172 /** Total bytes dropped since last rebuild. */
173 static size_t router_bytes_dropped = 0;
175 /** Helper: return 1 iff the router log is so big we want to rebuild the
176 * store. */
177 static int
178 router_should_rebuild_store(void)
180 if (router_store_len > (1<<16))
181 return (router_journal_len > router_store_len / 2 ||
182 router_bytes_dropped > router_store_len / 2);
183 else
184 return router_journal_len > (1<<15);
187 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
188 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
189 * offset appropriately. */
190 static int
191 router_append_to_journal(signed_descriptor_t *desc)
193 or_options_t *options = get_options();
194 size_t fname_len = strlen(options->DataDirectory)+32;
195 char *fname = tor_malloc(fname_len);
196 const char *body = signed_descriptor_get_body(desc);
197 size_t len = desc->signed_descriptor_len;
199 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
200 options->DataDirectory);
202 tor_assert(len == strlen(body));
204 if (append_bytes_to_file(fname, body, len, 1)) {
205 log_warn(LD_FS, "Unable to store router descriptor");
206 tor_free(fname);
207 return -1;
209 desc->saved_location = SAVED_IN_JOURNAL;
210 desc->saved_offset = router_journal_len;
212 tor_free(fname);
213 router_journal_len += len;
214 return 0;
217 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
218 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
219 * the signed_descriptor_t* in *<b>b</b>. */
220 static int
221 _compare_old_routers_by_age(const void **_a, const void **_b)
223 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
224 return r1->published_on - r2->published_on;
227 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
228 * routerinfo_t* in *<b>a</b> is older, the same age as, or newer than
229 * the routerinfo_t* in *<b>b</b>. */
230 static int
231 _compare_routers_by_age(const void **_a, const void **_b)
233 const routerinfo_t *r1 = *_a, *r2 = *_b;
234 return r1->cache_info.published_on - r2->cache_info.published_on;
237 /** If the journal is too long, or if <b>force</b> is true, then atomically
238 * replace the router store with the routers currently in our routerlist, and
239 * clear the journal. Return 0 on success, -1 on failure.
241 static int
242 router_rebuild_store(int force)
244 or_options_t *options;
245 size_t fname_len;
246 smartlist_t *chunk_list = NULL;
247 char *fname = NULL, *fname_tmp = NULL;
248 int r = -1, i;
249 off_t offset = 0;
250 smartlist_t *old_routers, *routers;
252 if (!force && !router_should_rebuild_store())
253 return 0;
254 if (!routerlist)
255 return 0;
257 /* Don't save deadweight. */
258 routerlist_remove_old_routers();
260 log_info(LD_DIR, "Rebuilding router descriptor cache");
262 options = get_options();
263 fname_len = strlen(options->DataDirectory)+32;
264 fname = tor_malloc(fname_len);
265 fname_tmp = tor_malloc(fname_len);
266 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
267 tor_snprintf(fname_tmp, fname_len, "%s/cached-routers.tmp",
268 options->DataDirectory);
270 chunk_list = smartlist_create();
272 old_routers = smartlist_create();
273 smartlist_add_all(old_routers, routerlist->old_routers);
274 smartlist_sort(old_routers, _compare_old_routers_by_age);
275 routers = smartlist_create();
276 smartlist_add_all(routers, routerlist->routers);
277 smartlist_sort(routers, _compare_routers_by_age);
278 for (i = 0; i < 2; ++i) {
279 /* We sort the routers by age to enhance locality on disk. */
280 smartlist_t *lst = (i == 0) ? old_routers : routers;
281 /* Now, add the appropriate members to chunk_list */
282 SMARTLIST_FOREACH(lst, void *, ptr,
284 signed_descriptor_t *sd = (i==0) ?
285 ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
286 sized_chunk_t *c;
287 const char *body = signed_descriptor_get_body(sd);
288 if (!body) {
289 log_warn(LD_BUG, "Bug! No descriptor available for router.");
290 goto done;
292 c = tor_malloc(sizeof(sized_chunk_t));
293 c->bytes = body;
294 c->len = sd->signed_descriptor_len;
295 smartlist_add(chunk_list, c);
298 if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
299 log_warn(LD_FS, "Error writing router store to disk.");
300 goto done;
302 /* Our mmap is now invalid. */
303 if (routerlist->mmap_descriptors) {
304 tor_munmap_file(routerlist->mmap_descriptors);
306 if (replace_file(fname_tmp, fname)<0) {
307 log_warn(LD_FS, "Error replacing old router store.");
308 goto done;
311 routerlist->mmap_descriptors = tor_mmap_file(fname);
312 if (! routerlist->mmap_descriptors)
313 log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
315 offset = 0;
316 for (i = 0; i < 2; ++i) {
317 smartlist_t *lst = (i == 0) ? old_routers : routers;
318 SMARTLIST_FOREACH(lst, void *, ptr,
320 signed_descriptor_t *sd = (i==0) ?
321 ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
323 sd->saved_location = SAVED_IN_CACHE;
324 if (routerlist->mmap_descriptors) {
325 tor_free(sd->signed_descriptor_body); // sets it to null
326 sd->saved_offset = offset;
328 offset += sd->signed_descriptor_len;
329 signed_descriptor_get_body(sd);
333 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
334 options->DataDirectory);
336 write_str_to_file(fname, "", 1);
338 r = 0;
339 tor_assert(offset >= 0);
340 router_store_len = (size_t) offset;
341 router_journal_len = 0;
342 router_bytes_dropped = 0;
343 done:
344 smartlist_free(old_routers);
345 smartlist_free(routers);
346 tor_free(fname);
347 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
348 smartlist_free(chunk_list);
349 return r;
352 /** Load all cached router descriptors from the store. Return 0 on success and
353 * -1 on failure.
356 router_reload_router_list(void)
358 or_options_t *options = get_options();
359 size_t fname_len = strlen(options->DataDirectory)+32;
360 char *fname = tor_malloc(fname_len), *contents = NULL;
362 if (!routerlist)
363 router_get_routerlist(); /* mallocs and inits it in place */
365 router_journal_len = router_store_len = 0;
367 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
369 if (routerlist->mmap_descriptors) /* get rid of it first */
370 tor_munmap_file(routerlist->mmap_descriptors);
372 routerlist->mmap_descriptors = tor_mmap_file(fname);
373 if (routerlist->mmap_descriptors) {
374 router_store_len = routerlist->mmap_descriptors->size;
375 router_load_routers_from_string(routerlist->mmap_descriptors->data,
376 routerlist->mmap_descriptors->size,
377 SAVED_IN_CACHE, NULL);
380 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
381 options->DataDirectory);
382 if (file_status(fname) == FN_FILE)
383 contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, NULL);
384 if (contents) {
385 router_load_routers_from_string(contents, strlen(contents),
386 SAVED_IN_JOURNAL, NULL);
387 tor_free(contents);
390 tor_free(fname);
392 if (router_journal_len) {
393 /* Always clear the journal on startup.*/
394 router_rebuild_store(1);
395 } else {
396 /* Don't cache expired routers. (This is in an else because
397 * router_rebuild_store() also calls remove_old_routers().) */
398 routerlist_remove_old_routers();
401 return 0;
404 /** Return a smartlist containing a list of trusted_dir_server_t * for all
405 * known trusted dirservers. Callers must not modify the list or its
406 * contents.
408 smartlist_t *
409 router_get_trusted_dir_servers(void)
411 if (!trusted_dir_servers)
412 trusted_dir_servers = smartlist_create();
414 return trusted_dir_servers;
417 /** Try to find a running dirserver. If there are no running dirservers
418 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
419 * set all the authoritative ones as running again, and pick one;
420 * if there are then no dirservers at all in our routerlist,
421 * reload the routerlist and try one last time. If for_runningrouters is
422 * true, then only pick a dirserver that can answer runningrouters queries
423 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
424 * Don't pick an authority if any non-authority is viable.
425 * Other args are as in router_pick_directory_server_impl().
427 routerstatus_t *
428 router_pick_directory_server(int requireother,
429 int fascistfirewall,
430 int for_v2_directory,
431 int retry_if_no_servers)
433 routerstatus_t *choice;
434 int prefer_tunnel = get_options()->PreferTunneledDirConns;
436 if (!routerlist)
437 return NULL;
439 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
440 prefer_tunnel, for_v2_directory);
441 if (choice || !retry_if_no_servers)
442 return choice;
444 log_info(LD_DIR,
445 "No reachable router entries for dirservers. "
446 "Trying them all again.");
447 /* mark all authdirservers as up again */
448 mark_all_trusteddirservers_up();
449 /* try again */
450 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
451 prefer_tunnel, for_v2_directory);
452 if (choice)
453 return choice;
455 log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
456 fascistfirewall ? "reachable" : "known");
457 if (router_reload_router_list()) {
458 return NULL;
460 /* give it one last try */
461 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
462 prefer_tunnel, for_v2_directory);
463 return choice;
466 /** Return the trusted_dir_server_t for the directory authority whose identity
467 * key hashes to <b>digest</b>, or NULL if no such authority is known.
469 trusted_dir_server_t *
470 router_get_trusteddirserver_by_digest(const char *digest)
472 if (!trusted_dir_servers)
473 return NULL;
475 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
477 if (!memcmp(ds->digest, digest, DIGEST_LEN))
478 return ds;
481 return NULL;
484 /** Try to find a running trusted dirserver. If there are no running
485 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
486 * set them all as running again, and try again.
487 * If <b>need_v1_authority</b> is set, return only trusted servers
488 * that are authorities for the V1 directory protocol.
489 * Other args are as in router_pick_trusteddirserver_impl().
491 routerstatus_t *
492 router_pick_trusteddirserver(authority_type_t type,
493 int requireother,
494 int fascistfirewall,
495 int retry_if_no_servers)
497 routerstatus_t *choice;
498 int prefer_tunnel = get_options()->PreferTunneledDirConns;
500 choice = router_pick_trusteddirserver_impl(type, requireother,
501 fascistfirewall, prefer_tunnel);
502 if (choice || !retry_if_no_servers)
503 return choice;
505 log_info(LD_DIR,
506 "No trusted dirservers are reachable. Trying them all again.");
507 mark_all_trusteddirservers_up();
508 return router_pick_trusteddirserver_impl(type, requireother,
509 fascistfirewall, prefer_tunnel);
512 /** How long do we avoid using a directory server after it's given us a 503? */
513 #define DIR_503_TIMEOUT (60*60)
515 /** Pick a random running valid directory server/mirror from our
516 * routerlist. Don't pick an authority if any non-authorities are viable.
517 * If <b>fascistfirewall</b>, make sure the router we pick is allowed
518 * by our firewall options.
519 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
520 * choose a directory server new enough to support the v2 directory
521 * functionality.
522 * If <b>prefer_tunnel</b>, choose a directory server that is reachable
523 * and supports BEGIN_DIR cells, if possible.
524 * Try to avoid using servers that are overloaded (have returned 503
525 * recently).
527 static routerstatus_t *
528 router_pick_directory_server_impl(int requireother, int fascistfirewall,
529 int prefer_tunnel, int for_v2_directory)
531 routerstatus_t *result;
532 smartlist_t *direct, *tunnel;
533 smartlist_t *trusted_direct, *trusted_tunnel;
534 smartlist_t *overloaded_direct, *overloaded_tunnel;
535 time_t now = time(NULL);
537 if (!routerstatus_list)
538 return NULL;
540 direct = smartlist_create();
541 tunnel = smartlist_create();
542 trusted_direct = smartlist_create();
543 trusted_tunnel = smartlist_create();
544 overloaded_direct = smartlist_create();
545 overloaded_tunnel = smartlist_create();
547 /* Find all the running dirservers we know about. */
548 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, _local_status,
550 routerstatus_t *status = &(_local_status->status);
551 int is_trusted;
552 int is_overloaded = _local_status->last_dir_503_at + DIR_503_TIMEOUT > now;
553 if (!status->is_running || !status->dir_port || !status->is_valid)
554 continue;
555 if (status->is_bad_directory)
556 continue;
557 if (requireother && router_digest_is_me(status->identity_digest))
558 continue;
559 is_trusted = router_digest_is_trusted_dir(status->identity_digest);
560 if (for_v2_directory && !(status->is_v2_dir || is_trusted))
561 continue;
562 if (fascistfirewall &&
563 prefer_tunnel &&
564 status->version_supports_begindir &&
565 router_get_by_digest(status->identity_digest) &&
566 fascist_firewall_allows_address_or(status->addr, status->or_port))
567 smartlist_add(is_trusted ? trusted_tunnel :
568 is_overloaded ? overloaded_tunnel : tunnel, status);
569 else if (!fascistfirewall || (fascistfirewall &&
570 fascist_firewall_allows_address_dir(status->addr,
571 status->dir_port)))
572 smartlist_add(is_trusted ? trusted_direct :
573 is_overloaded ? overloaded_direct : direct, status);
576 if (smartlist_len(tunnel)) {
577 result = routerstatus_sl_choose_by_bandwidth(tunnel);
578 } else if (smartlist_len(overloaded_tunnel)) {
579 result = routerstatus_sl_choose_by_bandwidth(overloaded_tunnel);
580 } else if (smartlist_len(trusted_tunnel)) {
581 /* FFFF We don't distinguish between trusteds and overloaded trusteds
582 * yet. Maybe one day we should. */
583 /* FFFF We also don't load balance over authorities yet. I think this
584 * is a feature, but it could easily be a bug. -RD */
585 result = smartlist_choose(trusted_tunnel);
586 } else if (smartlist_len(direct)) {
587 result = routerstatus_sl_choose_by_bandwidth(direct);
588 } else if (smartlist_len(overloaded_direct)) {
589 result = routerstatus_sl_choose_by_bandwidth(overloaded_direct);
590 } else {
591 result = smartlist_choose(trusted_direct);
593 smartlist_free(direct);
594 smartlist_free(tunnel);
595 smartlist_free(trusted_direct);
596 smartlist_free(trusted_tunnel);
597 smartlist_free(overloaded_direct);
598 smartlist_free(overloaded_tunnel);
599 return result;
602 /** Choose randomly from among the trusted dirservers that are up. If
603 * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
604 * firewall options. If <b>requireother</b>, it cannot be us. If
605 * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
606 * system.
608 static routerstatus_t *
609 router_pick_trusteddirserver_impl(authority_type_t type,
610 int requireother, int fascistfirewall,
611 int prefer_tunnel)
613 smartlist_t *direct, *tunnel;
614 smartlist_t *overloaded_direct, *overloaded_tunnel;
615 routerinfo_t *me = router_get_my_routerinfo();
616 routerstatus_t *result;
617 time_t now = time(NULL);
619 direct = smartlist_create();
620 tunnel = smartlist_create();
621 overloaded_direct = smartlist_create();
622 overloaded_tunnel = smartlist_create();
624 if (!trusted_dir_servers)
625 return NULL;
627 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
629 int is_overloaded =
630 d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
631 if (!d->is_running) continue;
632 if (type == V1_AUTHORITY && !d->is_v1_authority)
633 continue;
634 if (type == V2_AUTHORITY && !d->is_v2_authority)
635 continue;
636 if (type == HIDSERV_AUTHORITY && !d->is_hidserv_authority)
637 continue;
638 if (requireother && me && router_digest_is_me(d->digest))
639 continue;
641 if (fascistfirewall &&
642 prefer_tunnel &&
643 d->or_port &&
644 router_get_by_digest(d->digest) &&
645 fascist_firewall_allows_address_or(d->addr, d->or_port))
646 smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
647 &d->fake_status.status);
648 else if (!fascistfirewall || (fascistfirewall &&
649 fascist_firewall_allows_address_dir(d->addr,
650 d->dir_port)))
651 smartlist_add(is_overloaded ? overloaded_direct : direct,
652 &d->fake_status.status);
655 if (smartlist_len(tunnel)) {
656 result = smartlist_choose(tunnel);
657 } else if (smartlist_len(overloaded_tunnel)) {
658 result = smartlist_choose(overloaded_tunnel);
659 } else if (smartlist_len(direct)) {
660 result = smartlist_choose(direct);
661 } else {
662 result = smartlist_choose(overloaded_direct);
665 smartlist_free(direct);
666 smartlist_free(tunnel);
667 smartlist_free(overloaded_direct);
668 smartlist_free(overloaded_tunnel);
669 return result;
672 /** Go through and mark the authoritative dirservers as up. */
673 static void
674 mark_all_trusteddirservers_up(void)
676 if (routerlist) {
677 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
678 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
679 router->dir_port > 0) {
680 router->is_running = 1;
683 if (trusted_dir_servers) {
684 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
686 local_routerstatus_t *rs;
687 dir->is_running = 1;
688 dir->n_networkstatus_failures = 0;
689 dir->fake_status.last_dir_503_at = 0;
690 rs = router_get_combined_status_by_digest(dir->digest);
691 if (rs && !rs->status.is_running) {
692 rs->status.is_running = 1;
693 rs->last_dir_503_at = 0;
694 control_event_networkstatus_changed_single(rs);
698 last_networkstatus_download_attempted = 0;
699 router_dir_info_changed();
702 /** Reset all internal variables used to count failed downloads of network
703 * status objects. */
704 void
705 router_reset_status_download_failures(void)
707 mark_all_trusteddirservers_up();
710 /** Look through the routerlist and identify routers that
711 * advertise the same /16 network address as <b>router</b>.
712 * Add each of them to <b>sl</b>.
714 static void
715 routerlist_add_network_family(smartlist_t *sl, routerinfo_t *router)
717 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
719 if (router != r &&
720 (router->addr & 0xffff0000) == (r->addr & 0xffff0000))
721 smartlist_add(sl, r);
725 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
726 * This is used to make sure we don't pick siblings in a single path.
728 void
729 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
731 routerinfo_t *r;
732 config_line_t *cl;
733 or_options_t *options = get_options();
735 /* First, add any routers with similar network addresses. */
736 if (options->EnforceDistinctSubnets)
737 routerlist_add_network_family(sl, router);
739 if (!router->declared_family)
740 return;
742 /* Add every r such that router declares familyness with r, and r
743 * declares familyhood with router. */
744 SMARTLIST_FOREACH(router->declared_family, const char *, n,
746 if (!(r = router_get_by_nickname(n, 0)))
747 continue;
748 if (!r->declared_family)
749 continue;
750 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
752 if (router_nickname_matches(router, n2))
753 smartlist_add(sl, r);
757 /* If the user declared any families locally, honor those too. */
758 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
759 if (router_nickname_is_in_list(router, cl->value)) {
760 add_nickname_list_to_smartlist(sl, cl->value, 0);
765 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
766 * see which nicknames in <b>list</b> name routers in our routerlist, and add
767 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
768 * only include routers that we think are running.
769 * Warn if any non-Named routers are specified by nickname.
771 void
772 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
773 int must_be_running)
775 routerinfo_t *router;
776 smartlist_t *nickname_list;
777 int have_dir_info = router_have_minimum_dir_info();
779 if (!list)
780 return; /* nothing to do */
781 tor_assert(sl);
783 nickname_list = smartlist_create();
784 if (!warned_nicknames)
785 warned_nicknames = smartlist_create();
787 smartlist_split_string(nickname_list, list, ",",
788 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
790 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
791 int warned;
792 if (!is_legal_nickname_or_hexdigest(nick)) {
793 log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
794 continue;
796 router = router_get_by_nickname(nick, 1);
797 warned = smartlist_string_isin(warned_nicknames, nick);
798 if (router) {
799 if (!must_be_running || router->is_running) {
800 smartlist_add(sl,router);
802 } else if (!router_get_combined_status_by_nickname(nick,1)) {
803 if (!warned) {
804 log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
805 "Nickname list includes '%s' which isn't a known router.",nick);
806 smartlist_add(warned_nicknames, tor_strdup(nick));
810 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
811 smartlist_free(nickname_list);
814 /** Return 1 iff any member of the (possibly NULL) comma-separated list
815 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
816 * return 0.
819 router_nickname_is_in_list(routerinfo_t *router, const char *list)
821 smartlist_t *nickname_list;
822 int v = 0;
824 if (!list)
825 return 0; /* definitely not */
826 tor_assert(router);
828 nickname_list = smartlist_create();
829 smartlist_split_string(nickname_list, list, ",",
830 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
831 SMARTLIST_FOREACH(nickname_list, const char *, cp,
832 if (router_nickname_matches(router, cp)) {v=1;break;});
833 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
834 smartlist_free(nickname_list);
835 return v;
838 /** Add every suitable router from our routerlist to <b>sl</b>, so that
839 * we can pick a node for a circuit.
841 static void
842 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
843 int need_uptime, int need_capacity,
844 int need_guard)
846 if (!routerlist)
847 return;
849 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
851 if (router->is_running &&
852 router->purpose == ROUTER_PURPOSE_GENERAL &&
853 (router->is_valid || allow_invalid) &&
854 !router_is_unreliable(router, need_uptime,
855 need_capacity, need_guard)) {
856 /* If it's running, and it's suitable according to the
857 * other flags we had in mind */
858 smartlist_add(sl, router);
863 /** Look through the routerlist until we find a router that has my key.
864 Return it. */
865 routerinfo_t *
866 routerlist_find_my_routerinfo(void)
868 if (!routerlist)
869 return NULL;
871 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
873 if (router_is_me(router))
874 return router;
876 return NULL;
879 /** Find a router that's up, that has this IP address, and
880 * that allows exit to this address:port, or return NULL if there
881 * isn't a good one.
883 routerinfo_t *
884 router_find_exact_exit_enclave(const char *address, uint16_t port)
886 uint32_t addr;
887 struct in_addr in;
889 if (!tor_inet_aton(address, &in))
890 return NULL; /* it's not an IP already */
891 addr = ntohl(in.s_addr);
893 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
895 if (router->is_running &&
896 router->addr == addr &&
897 compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
898 ADDR_POLICY_ACCEPTED)
899 return router;
901 return NULL;
904 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
905 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
906 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
907 * bandwidth.
908 * If <b>need_guard</b>, we require that the router is a possible entry guard.
911 router_is_unreliable(routerinfo_t *router, int need_uptime,
912 int need_capacity, int need_guard)
914 if (need_uptime && !router->is_stable)
915 return 1;
916 if (need_capacity && !router->is_fast)
917 return 1;
918 if (need_guard && !router->is_possible_guard)
919 return 1;
920 return 0;
923 /** Return the smaller of the router's configured BandwidthRate
924 * and its advertised capacity. */
925 uint32_t
926 router_get_advertised_bandwidth(routerinfo_t *router)
928 if (router->bandwidthcapacity < router->bandwidthrate)
929 return router->bandwidthcapacity;
930 return router->bandwidthrate;
933 /** Do not weight any declared bandwidth more than this much when picking
934 * routers by bandwidth. */
935 #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
937 /** Helper function:
938 * choose a random element of smartlist <b>sl</b>, weighted by
939 * the advertised bandwidth of each element.
941 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
942 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
944 * If <b>for_exit</b>, we're picking an exit node: consider all nodes'
945 * bandwidth equally regardless of their Exit status. If not <b>for_exit</b>,
946 * we're picking a non-exit node: weight exit-node's bandwidth downwards
947 * depending on the smallness of the fraction of Exit-to-total bandwidth.
949 static void *
950 smartlist_choose_by_bandwidth(smartlist_t *sl, int for_exit, int statuses)
952 int i;
953 routerinfo_t *router;
954 routerstatus_t *status;
955 int32_t *bandwidths;
956 int is_exit;
957 uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
958 uint64_t rand_bw, tmp;
959 double exit_weight;
960 int n_unknown = 0;
962 /* First count the total bandwidth weight, and make a list
963 * of each value. <0 means "unknown; no routerinfo." We use the
964 * bits of negative values to remember whether the router was fast (-x)&1
965 * and whether it was an exit (-x)&2. Yes, it's a hack. */
966 bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
968 /* Iterate over all the routerinfo_t or routerstatus_t, and */
969 for (i = 0; i < smartlist_len(sl); ++i) {
970 /* first, learn what bandwidth we think i has */
971 int is_known = 1;
972 int32_t flags = 0;
973 uint32_t this_bw = 0;
974 if (statuses) {
975 /* need to extract router info */
976 status = smartlist_get(sl, i);
977 router = router_get_by_digest(status->identity_digest);
978 is_exit = status->is_exit;
979 if (router) {
980 this_bw = router_get_advertised_bandwidth(router);
981 } else { /* guess */
982 is_known = 0;
983 flags = status->is_fast ? 1 : 0;
984 flags |= is_exit ? 2 : 0;
986 } else {
987 router = smartlist_get(sl, i);
988 is_exit = router->is_exit;
989 this_bw = router_get_advertised_bandwidth(router);
991 /* if they claim something huge, don't believe it */
992 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
993 this_bw = MAX_BELIEVABLE_BANDWIDTH;
994 if (is_known) {
995 bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
996 if (is_exit)
997 total_exit_bw += this_bw;
998 else
999 total_nonexit_bw += this_bw;
1000 } else {
1001 ++n_unknown;
1002 bandwidths[i] = -flags;
1006 /* Now, fill in the unknown values. */
1007 if (n_unknown) {
1008 int32_t avg_fast, avg_slow;
1009 if (total_exit_bw+total_nonexit_bw) {
1010 /* if there's some bandwidth, there's at least one known router,
1011 * so no worries about div by 0 here */
1012 int n_known = smartlist_len(sl)-n_unknown;
1013 avg_fast = avg_slow = (int32_t)
1014 ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
1015 } else {
1016 avg_fast = 40000;
1017 avg_slow = 20000;
1019 for (i=0; i<smartlist_len(sl); ++i) {
1020 int32_t bw = bandwidths[i];
1021 if (bw>=0)
1022 continue;
1023 is_exit = ((-bw)&2);
1024 bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
1025 if (is_exit)
1026 total_exit_bw += bandwidths[i];
1027 else
1028 total_nonexit_bw += bandwidths[i];
1032 /* If there's no bandwidth at all, pick at random. */
1033 if (!(total_exit_bw+total_nonexit_bw)) {
1034 tor_free(bandwidths);
1035 return smartlist_choose(sl);
1038 /* Figure out how to weight exits. */
1039 if (for_exit) {
1040 /* If we're choosing an exit node, exit bandwidth counts fully. */
1041 exit_weight = 1.0;
1042 total_bw = total_exit_bw + total_nonexit_bw;
1043 } else if (total_exit_bw < total_nonexit_bw / 2) {
1044 /* If we're choosing a relay and exits are greatly outnumbered, ignore
1045 * them. */
1046 exit_weight = 0.0;
1047 total_bw = total_nonexit_bw;
1048 } else {
1049 /* If we're choosing a relay and exits aren't outnumbered use the formula
1050 * from path-spec. */
1051 uint64_t leftover = (total_exit_bw - total_nonexit_bw / 2);
1052 exit_weight = U64_TO_DBL(leftover) /
1053 U64_TO_DBL(leftover + total_nonexit_bw);
1054 total_bw = total_nonexit_bw +
1055 DBL_TO_U64(exit_weight * U64_TO_DBL(total_exit_bw));
1058 log_debug(LD_CIRC, "Total bw = "U64_FORMAT", total exit bw = "U64_FORMAT
1059 ", total nonexit bw = "U64_FORMAT", exit weight = %lf "
1060 "(for exit == %d)",
1061 U64_PRINTF_ARG(total_bw), U64_PRINTF_ARG(total_exit_bw),
1062 U64_PRINTF_ARG(total_nonexit_bw), exit_weight, for_exit);
1065 /* Almost done: choose a random value from the bandwidth weights. */
1066 rand_bw = crypto_rand_uint64(total_bw);
1068 /* Last, count through sl until we get to the element we picked */
1069 tmp = 0;
1070 for (i=0; i < smartlist_len(sl); i++) {
1071 if (statuses) {
1072 status = smartlist_get(sl, i);
1073 is_exit = status->is_exit;
1074 } else {
1075 router = smartlist_get(sl, i);
1076 is_exit = router->is_exit;
1078 if (is_exit)
1079 tmp += ((uint64_t)(bandwidths[i] * exit_weight));
1080 else
1081 tmp += bandwidths[i];
1082 if (tmp >= rand_bw)
1083 break;
1085 tor_free(bandwidths);
1086 return smartlist_get(sl, i);
1089 /** Choose a random element of router list <b>sl</b>, weighted by
1090 * the advertised bandwidth of each router.
1092 routerinfo_t *
1093 routerlist_sl_choose_by_bandwidth(smartlist_t *sl, int for_exit)
1095 return smartlist_choose_by_bandwidth(sl, for_exit, 0);
1098 /** Choose a random element of status list <b>sl</b>, weighted by
1099 * the advertised bandwidth of each status.
1101 routerstatus_t *
1102 routerstatus_sl_choose_by_bandwidth(smartlist_t *sl)
1104 return smartlist_choose_by_bandwidth(sl, 1, 1);
1107 /** Return a random running router from the routerlist. If any node
1108 * named in <b>preferred</b> is available, pick one of those. Never
1109 * pick a node named in <b>excluded</b>, or whose routerinfo is in
1110 * <b>excludedsmartlist</b>, even if they are the only nodes
1111 * available. If <b>strict</b> is true, never pick any node besides
1112 * those in <b>preferred</b>.
1113 * If <b>need_uptime</b> is non-zero and any router has more than
1114 * a minimum uptime, return one of those.
1115 * If <b>need_capacity</b> is non-zero, weight your choice by the
1116 * advertised capacity of each router.
1117 * If ! <b>allow_invalid</b>, consider only Valid routers.
1118 * If <b>need_guard</b>, consider only Guard routers.
1119 * If <b>weight_for_exit</b>, we weight bandwidths as if picking an exit node,
1120 * otherwise we weight bandwidths for picking a relay node (that is, possibly
1121 * discounting exit nodes).
1123 routerinfo_t *
1124 router_choose_random_node(const char *preferred,
1125 const char *excluded,
1126 smartlist_t *excludedsmartlist,
1127 int need_uptime, int need_capacity,
1128 int need_guard,
1129 int allow_invalid, int strict,
1130 int weight_for_exit)
1132 smartlist_t *sl, *excludednodes;
1133 routerinfo_t *choice = NULL;
1135 excludednodes = smartlist_create();
1136 add_nickname_list_to_smartlist(excludednodes,excluded,0);
1138 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1139 * and need_guard, since the user explicitly asked for these nodes. */
1140 if (preferred) {
1141 sl = smartlist_create();
1142 add_nickname_list_to_smartlist(sl,preferred,1);
1143 smartlist_subtract(sl,excludednodes);
1144 if (excludedsmartlist)
1145 smartlist_subtract(sl,excludedsmartlist);
1146 choice = smartlist_choose(sl);
1147 smartlist_free(sl);
1149 if (!choice && !strict) {
1150 /* Then give up on our preferred choices: any node
1151 * will do that has the required attributes. */
1152 sl = smartlist_create();
1153 router_add_running_routers_to_smartlist(sl, allow_invalid,
1154 need_uptime, need_capacity,
1155 need_guard);
1156 smartlist_subtract(sl,excludednodes);
1157 if (excludedsmartlist)
1158 smartlist_subtract(sl,excludedsmartlist);
1160 if (need_capacity)
1161 choice = routerlist_sl_choose_by_bandwidth(sl, weight_for_exit);
1162 else
1163 choice = smartlist_choose(sl);
1165 smartlist_free(sl);
1166 if (!choice && (need_uptime || need_capacity || need_guard)) {
1167 /* try once more -- recurse but with fewer restrictions. */
1168 log_info(LD_CIRC,
1169 "We couldn't find any live%s%s%s routers; falling back "
1170 "to list of all routers.",
1171 need_capacity?", fast":"",
1172 need_uptime?", stable":"",
1173 need_guard?", guard":"");
1174 choice = router_choose_random_node(
1175 NULL, excluded, excludedsmartlist,
1176 0, 0, 0, allow_invalid, 0, weight_for_exit);
1179 smartlist_free(excludednodes);
1180 if (!choice) {
1181 if (strict) {
1182 log_warn(LD_CIRC, "All preferred nodes were down when trying to choose "
1183 "node, and the Strict[...]Nodes option is set. Failing.");
1184 } else {
1185 log_warn(LD_CIRC,
1186 "No available nodes when trying to choose node. Failing.");
1189 return choice;
1192 /** Return true iff the digest of <b>router</b>'s identity key,
1193 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1194 * optionally prefixed with a single dollar sign). Return false if
1195 * <b>hexdigest</b> is malformed, or it doesn't match. */
1196 static INLINE int
1197 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
1199 char digest[DIGEST_LEN];
1200 size_t len;
1201 tor_assert(hexdigest);
1202 if (hexdigest[0] == '$')
1203 ++hexdigest;
1205 len = strlen(hexdigest);
1206 if (len < HEX_DIGEST_LEN)
1207 return 0;
1208 else if (len > HEX_DIGEST_LEN &&
1209 (hexdigest[HEX_DIGEST_LEN] == '=' ||
1210 hexdigest[HEX_DIGEST_LEN] == '~')) {
1211 if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, router->nickname))
1212 return 0;
1213 if (hexdigest[HEX_DIGEST_LEN] == '=' && !router->is_named)
1214 return 0;
1217 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
1218 return 0;
1219 return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
1222 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1223 * (case-insensitive), or if <b>router's</b> identity key digest
1224 * matches a hexadecimal value stored in <b>nickname</b>. Return
1225 * false otherwise. */
1226 static int
1227 router_nickname_matches(routerinfo_t *router, const char *nickname)
1229 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
1230 return 1;
1231 return router_hex_digest_matches(router, nickname);
1234 /** Return the router in our routerlist whose (case-insensitive)
1235 * nickname or (case-sensitive) hexadecimal key digest is
1236 * <b>nickname</b>. Return NULL if no such router is known.
1238 routerinfo_t *
1239 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
1241 int maybedigest;
1242 char digest[DIGEST_LEN];
1243 routerinfo_t *best_match=NULL;
1244 int n_matches = 0;
1245 char *named_digest = NULL;
1247 tor_assert(nickname);
1248 if (!routerlist)
1249 return NULL;
1250 if (nickname[0] == '$')
1251 return router_get_by_hexdigest(nickname);
1252 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
1253 return NULL;
1254 if (server_mode(get_options()) &&
1255 !strcasecmp(nickname, get_options()->Nickname))
1256 return router_get_my_routerinfo();
1258 maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
1259 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
1261 if (named_server_map &&
1262 (named_digest = strmap_get_lc(named_server_map, nickname))) {
1263 return digestmap_get(routerlist->identity_map, named_digest);
1266 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1268 if (!strcasecmp(router->nickname, nickname)) {
1269 ++n_matches;
1270 if (n_matches <= 1 || router->is_running)
1271 best_match = router;
1272 } else if (maybedigest &&
1273 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
1275 if (router_hex_digest_matches(router, nickname))
1276 return router;
1277 else
1278 best_match = router; // XXXX NM not exactly right.
1282 if (best_match) {
1283 if (warn_if_unnamed && n_matches > 1) {
1284 smartlist_t *fps = smartlist_create();
1285 int any_unwarned = 0;
1286 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1288 local_routerstatus_t *rs;
1289 char *desc;
1290 size_t dlen;
1291 char fp[HEX_DIGEST_LEN+1];
1292 if (strcasecmp(router->nickname, nickname))
1293 continue;
1294 rs = router_get_combined_status_by_digest(
1295 router->cache_info.identity_digest);
1296 if (rs && !rs->name_lookup_warned) {
1297 rs->name_lookup_warned = 1;
1298 any_unwarned = 1;
1300 base16_encode(fp, sizeof(fp),
1301 router->cache_info.identity_digest, DIGEST_LEN);
1302 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
1303 desc = tor_malloc(dlen);
1304 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
1305 fp, router->address, router->or_port);
1306 smartlist_add(fps, desc);
1308 if (any_unwarned) {
1309 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
1310 log_warn(LD_CONFIG,
1311 "There are multiple matches for the nickname \"%s\","
1312 " but none is listed as named by the directory authorities. "
1313 "Choosing one arbitrarily. If you meant one in particular, "
1314 "you should say %s.", nickname, alternatives);
1315 tor_free(alternatives);
1317 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
1318 smartlist_free(fps);
1319 } else if (warn_if_unnamed) {
1320 local_routerstatus_t *rs = router_get_combined_status_by_digest(
1321 best_match->cache_info.identity_digest);
1322 if (rs && !rs->name_lookup_warned) {
1323 char fp[HEX_DIGEST_LEN+1];
1324 base16_encode(fp, sizeof(fp),
1325 best_match->cache_info.identity_digest, DIGEST_LEN);
1326 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
1327 "name is not registered, so it could be used by any server, "
1328 "not just the one you meant. "
1329 "To make sure you get the same server in the future, refer to "
1330 "it by key, as \"$%s\".", nickname, fp);
1331 rs->name_lookup_warned = 1;
1334 return best_match;
1337 return NULL;
1340 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
1341 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1344 router_digest_version_as_new_as(const char *digest, const char *cutoff)
1346 routerinfo_t *router = router_get_by_digest(digest);
1347 if (!router)
1348 return 1;
1349 return tor_version_as_new_as(router->platform, cutoff);
1352 /** Return true iff <b>digest</b> is the digest of the identity key of
1353 * a trusted directory. */
1355 router_digest_is_trusted_dir(const char *digest)
1357 if (!trusted_dir_servers)
1358 return 0;
1359 if (get_options()->AuthoritativeDir &&
1360 router_digest_is_me(digest))
1361 return 1;
1362 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1363 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
1364 return 0;
1367 /** Return the router in our routerlist whose hexadecimal key digest
1368 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1369 routerinfo_t *
1370 router_get_by_hexdigest(const char *hexdigest)
1372 char digest[DIGEST_LEN];
1373 size_t len;
1374 routerinfo_t *ri;
1376 tor_assert(hexdigest);
1377 if (!routerlist)
1378 return NULL;
1379 if (hexdigest[0]=='$')
1380 ++hexdigest;
1381 len = strlen(hexdigest);
1382 if (len < HEX_DIGEST_LEN ||
1383 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
1384 return NULL;
1386 ri = router_get_by_digest(digest);
1388 if (len > HEX_DIGEST_LEN) {
1389 if (hexdigest[HEX_DIGEST_LEN] == '=') {
1390 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
1391 !ri->is_named)
1392 return NULL;
1393 } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
1394 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
1395 return NULL;
1396 } else {
1397 return NULL;
1401 return ri;
1404 /** Return the router in our routerlist whose 20-byte key digest
1405 * is <b>digest</b>. Return NULL if no such router is known. */
1406 routerinfo_t *
1407 router_get_by_digest(const char *digest)
1409 tor_assert(digest);
1411 if (!routerlist) return NULL;
1413 // routerlist_assert_ok(routerlist);
1415 return digestmap_get(routerlist->identity_map, digest);
1418 /** Return the router in our routerlist whose 20-byte descriptor
1419 * is <b>digest</b>. Return NULL if no such router is known. */
1420 signed_descriptor_t *
1421 router_get_by_descriptor_digest(const char *digest)
1423 tor_assert(digest);
1425 if (!routerlist) return NULL;
1427 return digestmap_get(routerlist->desc_digest_map, digest);
1430 /** Return a pointer to the signed textual representation of a descriptor.
1431 * The returned string is not guaranteed to be NUL-terminated: the string's
1432 * length will be in desc-\>signed_descriptor_len. */
1433 const char *
1434 signed_descriptor_get_body(signed_descriptor_t *desc)
1436 const char *r;
1437 size_t len = desc->signed_descriptor_len;
1438 tor_assert(len > 32);
1439 if (desc->saved_location == SAVED_IN_CACHE && routerlist &&
1440 routerlist->mmap_descriptors) {
1441 tor_assert(desc->saved_offset + len <= routerlist->mmap_descriptors->size);
1442 r = routerlist->mmap_descriptors->data + desc->saved_offset;
1443 } else {
1444 r = desc->signed_descriptor_body;
1446 tor_assert(r);
1447 tor_assert(!memcmp("router ", r, 7));
1448 #if 0
1449 tor_assert(!memcmp("\n-----END SIGNATURE-----\n",
1450 r + len - 25, 25));
1451 #endif
1453 return r;
1456 /** Return the current list of all known routers. */
1457 routerlist_t *
1458 router_get_routerlist(void)
1460 if (!routerlist) {
1461 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1462 routerlist->routers = smartlist_create();
1463 routerlist->old_routers = smartlist_create();
1464 routerlist->identity_map = digestmap_new();
1465 routerlist->desc_digest_map = digestmap_new();
1467 return routerlist;
1470 /** Free all storage held by <b>router</b>. */
1471 void
1472 routerinfo_free(routerinfo_t *router)
1474 if (!router)
1475 return;
1477 tor_free(router->cache_info.signed_descriptor_body);
1478 tor_free(router->address);
1479 tor_free(router->nickname);
1480 tor_free(router->platform);
1481 tor_free(router->contact_info);
1482 if (router->onion_pkey)
1483 crypto_free_pk_env(router->onion_pkey);
1484 if (router->identity_pkey)
1485 crypto_free_pk_env(router->identity_pkey);
1486 if (router->declared_family) {
1487 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
1488 smartlist_free(router->declared_family);
1490 addr_policy_free(router->exit_policy);
1491 tor_free(router);
1494 /** Release storage held by <b>sd</b>. */
1495 static void
1496 signed_descriptor_free(signed_descriptor_t *sd)
1498 tor_free(sd->signed_descriptor_body);
1499 tor_free(sd);
1502 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
1504 static signed_descriptor_t *
1505 signed_descriptor_from_routerinfo(routerinfo_t *ri)
1507 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
1508 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
1509 ri->cache_info.signed_descriptor_body = NULL;
1510 routerinfo_free(ri);
1511 return sd;
1514 /** Free all storage held by a routerlist <b>rl</b> */
1515 void
1516 routerlist_free(routerlist_t *rl)
1518 tor_assert(rl);
1519 digestmap_free(rl->identity_map, NULL);
1520 digestmap_free(rl->desc_digest_map, NULL);
1521 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1522 routerinfo_free(r));
1523 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
1524 signed_descriptor_free(sd));
1525 smartlist_free(rl->routers);
1526 smartlist_free(rl->old_routers);
1527 if (routerlist->mmap_descriptors)
1528 tor_munmap_file(routerlist->mmap_descriptors);
1529 tor_free(rl);
1531 router_dir_info_changed();
1534 void
1535 dump_routerlist_mem_usage(int severity)
1537 uint64_t livedescs = 0;
1538 uint64_t olddescs = 0;
1539 if (!routerlist)
1540 return;
1541 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
1542 livedescs += r->cache_info.signed_descriptor_len);
1543 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
1544 olddescs += sd->signed_descriptor_len);
1546 log(severity, LD_GENERAL,
1547 "In %d live descriptors: "U64_FORMAT" bytes. "
1548 "In %d old descriptors: "U64_FORMAT" bytes.",
1549 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
1550 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
1553 /** Return the greatest number of routerdescs we'll hold for any given router.
1555 static int
1556 max_descriptors_per_router(void)
1558 int n_authorities = get_n_v2_authorities();
1559 return (n_authorities < 5) ? 5 : n_authorities;
1562 /** Return non-zero if we have a lot of extra descriptors in our
1563 * routerlist, and should get rid of some of them. Else return 0.
1565 * We should be careful to not return true too eagerly, since we
1566 * could churn. By using "+1" below, we make sure this function
1567 * only returns true at most every smartlist_len(rl-\>routers)
1568 * new descriptors.
1570 static INLINE int
1571 routerlist_is_overfull(routerlist_t *rl)
1573 return smartlist_len(rl->old_routers) >
1574 smartlist_len(rl->routers)*(max_descriptors_per_router()+1);
1577 static INLINE int
1578 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
1580 if (idx < 0 || smartlist_get(sl, idx) != ri) {
1581 idx = -1;
1582 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
1583 if (r == ri) {
1584 idx = r_sl_idx;
1585 break;
1588 return idx;
1591 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1592 * as needed. */
1593 static void
1594 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
1597 /* XXXX remove this code once bug 404 is fixed. */
1598 routerinfo_t *ri_generated = router_get_my_routerinfo();
1599 tor_assert(ri_generated != ri);
1602 digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
1603 digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
1604 &(ri->cache_info));
1605 smartlist_add(rl->routers, ri);
1606 ri->routerlist_index = smartlist_len(rl->routers) - 1;
1607 router_dir_info_changed();
1608 routerlist_assert_ok(rl);
1611 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
1612 * a copy of router <b>ri</b> yet, add it to the list of old (not
1613 * recommended but still served) descriptors. Else free it. */
1614 static void
1615 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
1618 /* XXXX remove this code once bug 404 is fixed. */
1619 routerinfo_t *ri_generated = router_get_my_routerinfo();
1620 tor_assert(ri_generated != ri);
1622 if (get_options()->DirPort &&
1623 !digestmap_get(rl->desc_digest_map,
1624 ri->cache_info.signed_descriptor_digest)) {
1625 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
1626 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1627 smartlist_add(rl->old_routers, sd);
1628 } else {
1629 routerinfo_free(ri);
1631 routerlist_assert_ok(rl);
1634 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
1635 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1636 * idx) == ri, we don't need to do a linear search over the list to decide
1637 * which to remove. We fill the gap in rl-&gt;routers with a later element in
1638 * the list, if any exists. <b>ri</b> is freed. */
1639 void
1640 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
1642 routerinfo_t *ri_tmp;
1643 idx = _routerlist_find_elt(rl->routers, ri, idx);
1644 if (idx < 0)
1645 return;
1646 ri->routerlist_index = -1;
1647 smartlist_del(rl->routers, idx);
1648 if (idx < smartlist_len(rl->routers)) {
1649 routerinfo_t *r = smartlist_get(rl->routers, idx);
1650 r->routerlist_index = idx;
1653 ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
1654 router_dir_info_changed();
1655 tor_assert(ri_tmp == ri);
1656 if (make_old && get_options()->DirPort) {
1657 signed_descriptor_t *sd;
1658 sd = signed_descriptor_from_routerinfo(ri);
1659 smartlist_add(rl->old_routers, sd);
1660 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1661 } else {
1662 ri_tmp = digestmap_remove(rl->desc_digest_map,
1663 ri->cache_info.signed_descriptor_digest);
1664 tor_assert(ri_tmp == ri);
1665 router_bytes_dropped += ri->cache_info.signed_descriptor_len;
1666 routerinfo_free(ri);
1668 routerlist_assert_ok(rl);
1671 /** DOCDOC */
1672 static void
1673 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
1675 signed_descriptor_t *sd_tmp;
1676 idx = _routerlist_find_elt(rl->old_routers, sd, idx);
1677 if (idx < 0)
1678 return;
1679 smartlist_del(rl->old_routers, idx);
1680 sd_tmp = digestmap_remove(rl->desc_digest_map,
1681 sd->signed_descriptor_digest);
1682 tor_assert(sd_tmp == sd);
1683 router_bytes_dropped += sd->signed_descriptor_len;
1684 signed_descriptor_free(sd);
1685 routerlist_assert_ok(rl);
1688 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1689 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1690 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1691 * search over the list to decide which to remove. We put ri_new in the same
1692 * index as ri_old, if possible. ri is freed as appropriate. */
1693 static void
1694 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
1695 routerinfo_t *ri_new, int idx, int make_old)
1698 /* XXXX remove this code once bug 404 is fixed. */
1699 routerinfo_t *ri_generated = router_get_my_routerinfo();
1700 tor_assert(ri_generated != ri_new);
1702 tor_assert(ri_old != ri_new);
1703 idx = _routerlist_find_elt(rl->routers, ri_old, idx);
1704 router_dir_info_changed();
1705 if (idx >= 0) {
1706 smartlist_set(rl->routers, idx, ri_new);
1707 ri_old->routerlist_index = -1;
1708 ri_new->routerlist_index = idx;
1709 } else {
1710 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
1711 routerlist_insert(rl, ri_new);
1712 return;
1714 if (memcmp(ri_old->cache_info.identity_digest,
1715 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
1716 /* digests don't match; digestmap_set won't replace */
1717 digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
1719 digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
1720 digestmap_set(rl->desc_digest_map,
1721 ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
1723 if (make_old && get_options()->DirPort) {
1724 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
1725 smartlist_add(rl->old_routers, sd);
1726 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1727 } else {
1728 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
1729 ri_new->cache_info.signed_descriptor_digest,
1730 DIGEST_LEN)) {
1731 /* digests don't match; digestmap_set didn't replace */
1732 digestmap_remove(rl->desc_digest_map,
1733 ri_old->cache_info.signed_descriptor_digest);
1735 router_bytes_dropped += ri_old->cache_info.signed_descriptor_len;
1736 routerinfo_free(ri_old);
1738 routerlist_assert_ok(rl);
1741 /** Free all memory held by the routerlist module. */
1742 void
1743 routerlist_free_all(void)
1745 if (routerlist)
1746 routerlist_free(routerlist);
1747 routerlist = NULL;
1748 if (warned_nicknames) {
1749 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1750 smartlist_free(warned_nicknames);
1751 warned_nicknames = NULL;
1753 if (warned_conflicts) {
1754 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1755 smartlist_free(warned_conflicts);
1756 warned_conflicts = NULL;
1758 if (trusted_dir_servers) {
1759 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1760 trusted_dir_server_free(ds));
1761 smartlist_free(trusted_dir_servers);
1762 trusted_dir_servers = NULL;
1764 if (networkstatus_list) {
1765 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1766 networkstatus_free(ns));
1767 smartlist_free(networkstatus_list);
1768 networkstatus_list = NULL;
1770 if (routerstatus_list) {
1771 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1772 local_routerstatus_free(rs));
1773 smartlist_free(routerstatus_list);
1774 routerstatus_list = NULL;
1776 if (named_server_map) {
1777 strmap_free(named_server_map, _tor_free);
1781 /** Free all storage held by the routerstatus object <b>rs</b>. */
1782 void
1783 routerstatus_free(routerstatus_t *rs)
1785 tor_free(rs);
1788 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1789 static void
1790 local_routerstatus_free(local_routerstatus_t *rs)
1792 tor_free(rs);
1795 /** Free all storage held by the networkstatus object <b>ns</b>. */
1796 void
1797 networkstatus_free(networkstatus_t *ns)
1799 tor_free(ns->source_address);
1800 tor_free(ns->contact);
1801 if (ns->signing_key)
1802 crypto_free_pk_env(ns->signing_key);
1803 tor_free(ns->client_versions);
1804 tor_free(ns->server_versions);
1805 if (ns->entries) {
1806 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
1807 routerstatus_free(rs));
1808 smartlist_free(ns->entries);
1810 tor_free(ns);
1813 /** Forget that we have issued any router-related warnings, so that we'll
1814 * warn again if we see the same errors. */
1815 void
1816 routerlist_reset_warnings(void)
1818 if (!warned_nicknames)
1819 warned_nicknames = smartlist_create();
1820 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1821 smartlist_clear(warned_nicknames); /* now the list is empty. */
1823 if (!warned_conflicts)
1824 warned_conflicts = smartlist_create();
1825 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1826 smartlist_clear(warned_conflicts); /* now the list is empty. */
1828 if (!routerstatus_list)
1829 routerstatus_list = smartlist_create();
1830 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1831 rs->name_lookup_warned = 0);
1833 have_warned_about_invalid_status = 0;
1834 have_warned_about_old_version = 0;
1835 have_warned_about_new_version = 0;
1838 /** Mark the router with ID <b>digest</b> as running or non-running
1839 * in our routerlist. */
1840 void
1841 router_set_status(const char *digest, int up)
1843 routerinfo_t *router;
1844 local_routerstatus_t *status;
1845 tor_assert(digest);
1847 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1848 if (!memcmp(d->digest, digest, DIGEST_LEN))
1849 d->is_running = up);
1851 router = router_get_by_digest(digest);
1852 if (router) {
1853 log_debug(LD_DIR,"Marking router '%s' as %s.",
1854 router->nickname, up ? "up" : "down");
1855 if (!up && router_is_me(router) && !we_are_hibernating())
1856 log_warn(LD_NET, "We just marked ourself as down. Are your external "
1857 "addresses reachable?");
1858 router->is_running = up;
1860 status = router_get_combined_status_by_digest(digest);
1861 if (status && status->status.is_running != up) {
1862 status->status.is_running = up;
1863 control_event_networkstatus_changed_single(status);
1865 router_dir_info_changed();
1868 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1869 * older entries (if any) with the same key. Note: Callers should not hold
1870 * their pointers to <b>router</b> if this function fails; <b>router</b>
1871 * will either be inserted into the routerlist or freed.
1873 * Returns >= 0 if the router was added; less than 0 if it was not.
1875 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1876 * describing the reason for not liking the routerinfo.
1878 * If the return value is less than -1, there was a problem with the
1879 * routerinfo. If the return value is equal to -1, then the routerinfo was
1880 * fine, but out-of-date. If the return value is equal to 1, the
1881 * routerinfo was accepted, but we should notify the generator of the
1882 * descriptor using the message *<b>msg</b>.
1884 * If <b>from_cache</b>, this descriptor came from our disk cache. If
1885 * <b>from_fetch</b>, we received it in response to a request we made.
1886 * (If both are false, that means it was uploaded to us as an auth dir
1887 * server or via the controller.)
1889 * This function should be called *after*
1890 * routers_update_status_from_networkstatus; subsequently, you should call
1891 * router_rebuild_store and control_event_descriptors_changed.
1894 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1895 int from_cache, int from_fetch)
1897 const char *id_digest;
1898 int authdir = get_options()->AuthoritativeDir;
1899 int authdir_believes_valid = 0;
1900 routerinfo_t *old_router;
1902 tor_assert(msg);
1904 if (!routerlist)
1905 router_get_routerlist();
1906 if (!networkstatus_list)
1907 networkstatus_list = smartlist_create();
1909 id_digest = router->cache_info.identity_digest;
1911 /* Make sure that we haven't already got this exact descriptor. */
1912 if (digestmap_get(routerlist->desc_digest_map,
1913 router->cache_info.signed_descriptor_digest)) {
1914 log_info(LD_DIR,
1915 "Dropping descriptor that we already have for router '%s'",
1916 router->nickname);
1917 *msg = "Router descriptor was not new.";
1918 routerinfo_free(router);
1919 return -1;
1922 if (routerlist_is_overfull(routerlist))
1923 routerlist_remove_old_routers();
1925 if (authdir) {
1926 if (authdir_wants_to_reject_router(router, msg,
1927 !from_cache && !from_fetch)) {
1928 tor_assert(*msg);
1929 routerinfo_free(router);
1930 return -2;
1932 authdir_believes_valid = router->is_valid;
1933 } else if (from_fetch) {
1934 /* Only check the descriptor digest against the network statuses when
1935 * we are receiving in response to a fetch. */
1937 if (!signed_desc_digest_is_recognized(&router->cache_info)) {
1938 /* We asked for it, so some networkstatus must have listed it when we
1939 * did. Save it if we're a cache in case somebody else asks for it. */
1940 log_info(LD_DIR,
1941 "Received a no-longer-recognized descriptor for router '%s'",
1942 router->nickname);
1943 *msg = "Router descriptor is not referenced by any network-status.";
1945 /* Only journal this desc if we'll be serving it. */
1946 if (!from_cache && get_options()->DirPort)
1947 router_append_to_journal(&router->cache_info);
1948 routerlist_insert_old(routerlist, router);
1949 return -1;
1953 /* We no longer need a router with this descriptor digest. */
1954 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1956 routerstatus_t *rs =
1957 networkstatus_find_entry(ns, router->cache_info.identity_digest);
1958 if (rs && !memcmp(rs->descriptor_digest,
1959 router->cache_info.signed_descriptor_digest,
1960 DIGEST_LEN))
1961 rs->need_to_mirror = 0;
1964 /* If we have a router with the same identity key, choose the newer one. */
1965 old_router = digestmap_get(routerlist->identity_map,
1966 router->cache_info.identity_digest);
1967 if (old_router) {
1968 int pos = old_router->routerlist_index;
1969 tor_assert(smartlist_get(routerlist->routers, pos) == old_router);
1971 if (router->cache_info.published_on <=
1972 old_router->cache_info.published_on) {
1973 /* Same key, but old */
1974 log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1975 router->nickname);
1976 /* Only journal this desc if we'll be serving it. */
1977 if (!from_cache && get_options()->DirPort)
1978 router_append_to_journal(&router->cache_info);
1979 routerlist_insert_old(routerlist, router);
1980 *msg = "Router descriptor was not new.";
1981 return -1;
1982 } else {
1983 /* Same key, new. */
1984 int unreachable = 0;
1985 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1986 router->nickname, old_router->nickname,
1987 hex_str(id_digest,DIGEST_LEN));
1988 if (router->addr == old_router->addr &&
1989 router->or_port == old_router->or_port) {
1990 /* these carry over when the address and orport are unchanged.*/
1991 router->last_reachable = old_router->last_reachable;
1992 router->testing_since = old_router->testing_since;
1993 router->num_unreachable_notifications =
1994 old_router->num_unreachable_notifications;
1996 if (authdir && !from_cache && !from_fetch &&
1997 router_have_minimum_dir_info() &&
1998 dirserv_thinks_router_is_blatantly_unreachable(router,
1999 time(NULL))) {
2000 if (router->num_unreachable_notifications >= 3) {
2001 unreachable = 1;
2002 log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
2003 "(ContactInfo '%s', platform '%s').",
2004 router->nickname,
2005 router->contact_info ? router->contact_info : "",
2006 router->platform ? router->platform : "");
2007 } else {
2008 log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
2009 "descriptors were thought to be unreachable.",
2010 router->nickname, router->num_unreachable_notifications);
2011 router->num_unreachable_notifications++;
2014 routerlist_replace(routerlist, old_router, router, pos, 1);
2015 if (!from_cache) {
2016 router_append_to_journal(&router->cache_info);
2018 directory_set_dirty();
2019 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
2020 authdir_believes_valid ? "Valid server updated" :
2021 ("Invalid server updated. (This dirserver is marking your "
2022 "server as unapproved.)");
2023 return unreachable ? 1 : 0;
2027 /* We haven't seen a router with this identity before. Add it to the end of
2028 * the list. */
2029 routerlist_insert(routerlist, router);
2030 if (!from_cache)
2031 router_append_to_journal(&router->cache_info);
2032 directory_set_dirty();
2033 return 0;
2036 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
2037 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
2038 * to, or later than that of *<b>b</b>. */
2039 static int
2040 _compare_old_routers_by_identity(const void **_a, const void **_b)
2042 int i;
2043 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
2044 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
2045 return i;
2046 return r1->published_on - r2->published_on;
2049 /** Internal type used to represent how long an old descriptor was valid,
2050 * where it appeared in the list of old descriptors, and whether it's extra
2051 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
2052 struct duration_idx_t {
2053 int duration;
2054 int idx;
2055 int old;
2058 /** Sorting helper: compare two duration_idx_t by their duration. */
2059 static int
2060 _compare_duration_idx(const void *_d1, const void *_d2)
2062 const struct duration_idx_t *d1 = _d1;
2063 const struct duration_idx_t *d2 = _d2;
2064 return d1->duration - d2->duration;
2067 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
2068 * must contain routerinfo_t with the same identity and with publication time
2069 * in ascending order. Remove members from this range until there are no more
2070 * than max_descriptors_per_router() remaining. Start by removing the oldest
2071 * members from before <b>cutoff</b>, then remove members which were current
2072 * for the lowest amount of time. The order of members of old_routers at
2073 * indices <b>lo</b> or higher may be changed.
2075 static void
2076 routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
2077 digestmap_t *retain)
2079 int i, n = hi-lo+1, n_extra;
2080 int n_rmv = 0;
2081 struct duration_idx_t *lifespans;
2082 uint8_t *rmv, *must_keep;
2083 smartlist_t *lst = routerlist->old_routers;
2084 #if 1
2085 const char *ident;
2086 tor_assert(hi < smartlist_len(lst));
2087 tor_assert(lo <= hi);
2088 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
2089 for (i = lo+1; i <= hi; ++i) {
2090 signed_descriptor_t *r = smartlist_get(lst, i);
2091 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
2093 #endif
2095 /* Check whether we need to do anything at all. */
2096 n_extra = n - max_descriptors_per_router();
2097 if (n_extra <= 0)
2098 return;
2100 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
2101 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
2102 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
2103 /* Set lifespans to contain the lifespan and index of each server. */
2104 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
2105 for (i = lo; i <= hi; ++i) {
2106 signed_descriptor_t *r = smartlist_get(lst, i);
2107 signed_descriptor_t *r_next;
2108 lifespans[i-lo].idx = i;
2109 if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
2110 must_keep[i-lo] = 1;
2112 if (i < hi) {
2113 r_next = smartlist_get(lst, i+1);
2114 tor_assert(r->published_on <= r_next->published_on);
2115 lifespans[i-lo].duration = (r_next->published_on - r->published_on);
2116 } else {
2117 r_next = NULL;
2118 lifespans[i-lo].duration = INT_MAX;
2120 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
2121 ++n_rmv;
2122 lifespans[i-lo].old = 1;
2123 rmv[i-lo] = 1;
2127 if (n_rmv < n_extra) {
2129 * We aren't removing enough servers for being old. Sort lifespans by
2130 * the duration of liveness, and remove the ones we're not already going to
2131 * remove based on how long they were alive.
2133 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
2134 for (i = 0; i < n && n_rmv < n_extra; ++i) {
2135 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
2136 rmv[lifespans[i].idx-lo] = 1;
2137 ++n_rmv;
2142 for (i = hi; i >= lo; --i) {
2143 if (rmv[i-lo])
2144 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
2146 tor_free(must_keep);
2147 tor_free(rmv);
2148 tor_free(lifespans);
2151 /** Deactivate any routers from the routerlist that are more than
2152 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
2153 * remove old routers from the list of cached routers if we have too many.
2155 void
2156 routerlist_remove_old_routers(void)
2158 int i, hi=-1;
2159 const char *cur_id = NULL;
2160 time_t now = time(NULL);
2161 time_t cutoff;
2162 routerinfo_t *router;
2163 signed_descriptor_t *sd;
2164 digestmap_t *retain;
2165 if (!routerlist || !networkstatus_list)
2166 return;
2168 routerlist_assert_ok(routerlist);
2170 retain = digestmap_new();
2171 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
2172 /* Build a list of all the descriptors that _anybody_ recommends. */
2173 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2175 /* XXXX The inner loop here gets pretty expensive, and actually shows up
2176 * on some profiles. It may be the reason digestmap_set shows up in
2177 * profiles too. If instead we kept a per-descriptor digest count of
2178 * how many networkstatuses recommended each descriptor, and changed
2179 * that only when the networkstatuses changed, that would be a speed
2180 * improvement, possibly 1-4% if it also removes digestmap_set from the
2181 * profile. Not worth it for 0.1.2.x, though. The new directory
2182 * system will obsolete this whole thing in 0.2.0.x. */
2183 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
2184 if (rs->published_on >= cutoff)
2185 digestmap_set(retain, rs->descriptor_digest, (void*)1));
2188 /* If we have a bunch of networkstatuses, we should consider pruning current
2189 * routers that are too old and that nobody recommends. (If we don't have
2190 * enough networkstatuses, then we should get more before we decide to kill
2191 * routers.) */
2192 if (smartlist_len(networkstatus_list) > get_n_v2_authorities() / 2) {
2193 cutoff = now - ROUTER_MAX_AGE;
2194 /* Remove too-old unrecommended members of routerlist->routers. */
2195 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
2196 router = smartlist_get(routerlist->routers, i);
2197 if (router->cache_info.published_on <= cutoff &&
2198 !digestmap_get(retain,router->cache_info.signed_descriptor_digest)) {
2199 /* Too old: remove it. (If we're a cache, just move it into
2200 * old_routers.) */
2201 log_info(LD_DIR,
2202 "Forgetting obsolete (too old) routerinfo for router '%s'",
2203 router->nickname);
2204 routerlist_remove(routerlist, router, i--, 1);
2209 routerlist_assert_ok(routerlist);
2211 /* Remove far-too-old members of routerlist->old_routers. */
2212 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
2213 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
2214 sd = smartlist_get(routerlist->old_routers, i);
2215 if (sd->published_on <= cutoff &&
2216 !digestmap_get(retain, sd->signed_descriptor_digest)) {
2217 /* Too old. Remove it. */
2218 routerlist_remove_old(routerlist, sd, i--);
2222 routerlist_assert_ok(routerlist);
2224 /* Now we might have to look at routerlist->old_routers for extraneous
2225 * members. (We'd keep all the members if we could, but we need to save
2226 * space.) First, check whether we have too many router descriptors, total.
2227 * We're okay with having too many for some given router, so long as the
2228 * total number doesn't approach max_descriptors_per_router()*len(router).
2230 if (smartlist_len(routerlist->old_routers) <
2231 smartlist_len(routerlist->routers) * (max_descriptors_per_router() - 1))
2232 goto done;
2234 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
2236 /* Iterate through the list from back to front, so when we remove descriptors
2237 * we don't mess up groups we haven't gotten to. */
2238 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
2239 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
2240 if (!cur_id) {
2241 cur_id = r->identity_digest;
2242 hi = i;
2244 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
2245 routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
2246 cur_id = r->identity_digest;
2247 hi = i;
2250 if (hi>=0)
2251 routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
2252 routerlist_assert_ok(routerlist);
2254 done:
2255 digestmap_free(retain, NULL);
2259 * Code to parse a single router descriptor and insert it into the
2260 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
2261 * descriptor was well-formed but could not be added; and 1 if the
2262 * descriptor was added.
2264 * If we don't add it and <b>msg</b> is not NULL, then assign to
2265 * *<b>msg</b> a static string describing the reason for refusing the
2266 * descriptor.
2268 * This is used only by the controller.
2271 router_load_single_router(const char *s, uint8_t purpose, const char **msg)
2273 routerinfo_t *ri;
2274 int r;
2275 smartlist_t *lst;
2276 tor_assert(msg);
2277 *msg = NULL;
2279 if (!(ri = router_parse_entry_from_string(s, NULL, 1))) {
2280 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
2281 *msg = "Couldn't parse router descriptor.";
2282 return -1;
2284 ri->purpose = purpose;
2285 if (router_is_me(ri)) {
2286 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
2287 *msg = "Router's identity key matches mine.";
2288 routerinfo_free(ri);
2289 return 0;
2292 lst = smartlist_create();
2293 smartlist_add(lst, ri);
2294 routers_update_status_from_networkstatus(lst, 0);
2296 if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
2297 /* we've already assigned to *msg now, and ri is already freed */
2298 tor_assert(*msg);
2299 if (r < -1)
2300 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
2301 smartlist_free(lst);
2302 return 0;
2303 } else {
2304 control_event_descriptors_changed(lst);
2305 smartlist_free(lst);
2306 log_debug(LD_DIR, "Added router to list");
2307 return 1;
2311 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
2312 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
2313 * are in response to a query to the network: cache them by adding them to
2314 * the journal.
2316 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2317 * uppercased identity fingerprints. Do not update any router whose
2318 * fingerprint is not on the list; after updating a router, remove its
2319 * fingerprint from the list.
2321 void
2322 router_load_routers_from_string(const char *s, size_t len,
2323 saved_location_t saved_location,
2324 smartlist_t *requested_fingerprints)
2326 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
2327 char fp[HEX_DIGEST_LEN+1];
2328 const char *msg;
2329 int from_cache = (saved_location != SAVED_NOWHERE);
2331 router_parse_list_from_string(&s, s+len, routers, saved_location);
2333 routers_update_status_from_networkstatus(routers, !from_cache);
2335 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
2337 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
2339 base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
2340 DIGEST_LEN);
2341 if (requested_fingerprints) {
2342 if (smartlist_string_isin(requested_fingerprints, fp)) {
2343 smartlist_string_remove(requested_fingerprints, fp);
2344 } else {
2345 char *requested =
2346 smartlist_join_strings(requested_fingerprints," ",0,NULL);
2347 log_warn(LD_DIR,
2348 "We received a router descriptor with a fingerprint (%s) "
2349 "that we never requested. (We asked for: %s.) Dropping.",
2350 fp, requested);
2351 tor_free(requested);
2352 routerinfo_free(ri);
2353 continue;
2357 if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
2358 smartlist_add(changed, ri);
2361 if (smartlist_len(changed))
2362 control_event_descriptors_changed(changed);
2364 routerlist_assert_ok(routerlist);
2365 router_rebuild_store(0);
2367 smartlist_free(routers);
2368 smartlist_free(changed);
2371 /** Helper: return a newly allocated string containing the name of the filename
2372 * where we plan to cache the network status with the given identity digest. */
2373 char *
2374 networkstatus_get_cache_filename(const char *identity_digest)
2376 const char *datadir = get_options()->DataDirectory;
2377 size_t len = strlen(datadir)+64;
2378 char fp[HEX_DIGEST_LEN+1];
2379 char *fn = tor_malloc(len+1);
2380 base16_encode(fp, HEX_DIGEST_LEN+1, identity_digest, DIGEST_LEN);
2381 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
2382 return fn;
2385 /** Helper for smartlist_sort: Compare two networkstatus objects by
2386 * publication date. */
2387 static int
2388 _compare_networkstatus_published_on(const void **_a, const void **_b)
2390 const networkstatus_t *a = *_a, *b = *_b;
2391 if (a->published_on < b->published_on)
2392 return -1;
2393 else if (a->published_on > b->published_on)
2394 return 1;
2395 else
2396 return 0;
2399 /** Add the parsed neworkstatus in <b>ns</b> (with original document in
2400 * <b>s</b> to the disk cache (and the in-memory directory server cache) as
2401 * appropriate. */
2402 static int
2403 add_networkstatus_to_cache(const char *s,
2404 networkstatus_source_t source,
2405 networkstatus_t *ns)
2407 if (source != NS_FROM_CACHE) {
2408 char *fn = networkstatus_get_cache_filename(ns->identity_digest);
2409 if (write_str_to_file(fn, s, 0)<0) {
2410 log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
2412 tor_free(fn);
2415 if (get_options()->DirPort)
2416 dirserv_set_cached_networkstatus_v2(s,
2417 ns->identity_digest,
2418 ns->published_on);
2420 return 0;
2423 /** How far in the future do we allow a network-status to get before removing
2424 * it? (seconds) */
2425 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
2427 /** Given a string <b>s</b> containing a network status that we received at
2428 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
2429 * store it, and put it into our cache as necessary.
2431 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
2432 * own networkstatus_t (if we're an authoritative directory server).
2434 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
2435 * cache.
2437 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2438 * uppercased identity fingerprints. Do not update any networkstatus whose
2439 * fingerprint is not on the list; after updating a networkstatus, remove its
2440 * fingerprint from the list.
2442 * Return 0 on success, -1 on failure.
2444 * Callers should make sure that routers_update_all_from_networkstatus() is
2445 * invoked after this function succeeds.
2448 router_set_networkstatus(const char *s, time_t arrived_at,
2449 networkstatus_source_t source, smartlist_t *requested_fingerprints)
2451 networkstatus_t *ns;
2452 int i, found;
2453 time_t now;
2454 int skewed = 0;
2455 trusted_dir_server_t *trusted_dir = NULL;
2456 const char *source_desc = NULL;
2457 char fp[HEX_DIGEST_LEN+1];
2458 char published[ISO_TIME_LEN+1];
2460 ns = networkstatus_parse_from_string(s);
2461 if (!ns) {
2462 log_warn(LD_DIR, "Couldn't parse network status.");
2463 return -1;
2465 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
2466 if (!(trusted_dir =
2467 router_get_trusteddirserver_by_digest(ns->identity_digest)) ||
2468 !trusted_dir->is_v2_authority) {
2469 log_info(LD_DIR, "Network status was signed, but not by an authoritative "
2470 "directory we recognize.");
2471 if (!get_options()->DirPort) {
2472 networkstatus_free(ns);
2473 return 0;
2475 source_desc = fp;
2476 } else {
2477 source_desc = trusted_dir->description;
2479 now = time(NULL);
2480 if (arrived_at > now)
2481 arrived_at = now;
2483 ns->received_on = arrived_at;
2485 format_iso_time(published, ns->published_on);
2487 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
2488 log_warn(LD_GENERAL, "Network status from %s was published in the future "
2489 "(%s GMT). Somebody is skewed here: check your clock. "
2490 "Not caching.",
2491 source_desc, published);
2492 control_event_general_status(LOG_WARN,
2493 "CLOCK_SKEW SOURCE=NETWORKSTATUS:%s:%d",
2494 ns->source_address, ns->source_dirport);
2495 skewed = 1;
2498 if (!networkstatus_list)
2499 networkstatus_list = smartlist_create();
2501 if ( (source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) &&
2502 router_digest_is_me(ns->identity_digest)) {
2503 /* Don't replace our own networkstatus when we get it from somebody else.*/
2504 networkstatus_free(ns);
2505 return 0;
2508 if (requested_fingerprints) {
2509 if (smartlist_string_isin(requested_fingerprints, fp)) {
2510 smartlist_string_remove(requested_fingerprints, fp);
2511 } else {
2512 if (source != NS_FROM_DIR_ALL) {
2513 char *requested =
2514 smartlist_join_strings(requested_fingerprints," ",0,NULL);
2515 log_warn(LD_DIR,
2516 "We received a network status with a fingerprint (%s) that we "
2517 "never requested. (We asked for: %s.) Dropping.",
2518 fp, requested);
2519 tor_free(requested);
2520 return 0;
2525 if (!trusted_dir) {
2526 if (!skewed && get_options()->DirPort) {
2527 /* We got a non-trusted networkstatus, and we're a directory cache.
2528 * This means that we asked an authority, and it told us about another
2529 * authority we didn't recognize. */
2530 log_info(LD_DIR,
2531 "We do not recognize authority (%s) but we are willing "
2532 "to cache it", fp);
2533 add_networkstatus_to_cache(s, source, ns);
2534 networkstatus_free(ns);
2536 return 0;
2539 found = 0;
2540 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
2541 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
2543 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
2544 if (!memcmp(old_ns->networkstatus_digest,
2545 ns->networkstatus_digest, DIGEST_LEN)) {
2546 /* Same one we had before. */
2547 networkstatus_free(ns);
2548 tor_assert(trusted_dir);
2549 log_info(LD_DIR,
2550 "Not replacing network-status from %s (published %s); "
2551 "we already have it.",
2552 trusted_dir->description, published);
2553 if (old_ns->received_on < arrived_at) {
2554 if (source != NS_FROM_CACHE) {
2555 char *fn;
2556 fn = networkstatus_get_cache_filename(old_ns->identity_digest);
2557 /* We use mtime to tell when it arrived, so update that. */
2558 touch_file(fn);
2559 tor_free(fn);
2561 old_ns->received_on = arrived_at;
2563 ++trusted_dir->n_networkstatus_failures;
2564 return 0;
2565 } else if (old_ns->published_on >= ns->published_on) {
2566 char old_published[ISO_TIME_LEN+1];
2567 format_iso_time(old_published, old_ns->published_on);
2568 tor_assert(trusted_dir);
2569 log_info(LD_DIR,
2570 "Not replacing network-status from %s (published %s);"
2571 " we have a newer one (published %s) for this authority.",
2572 trusted_dir->description, published,
2573 old_published);
2574 networkstatus_free(ns);
2575 ++trusted_dir->n_networkstatus_failures;
2576 return 0;
2577 } else {
2578 networkstatus_free(old_ns);
2579 smartlist_set(networkstatus_list, i, ns);
2580 found = 1;
2581 break;
2586 if (source != NS_FROM_CACHE && trusted_dir)
2587 trusted_dir->n_networkstatus_failures = 0;
2589 if (!found)
2590 smartlist_add(networkstatus_list, ns);
2592 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
2594 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
2595 rs->need_to_mirror = 1;
2598 log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
2599 source == NS_FROM_CACHE?"cached from":
2600 ((source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) ?
2601 "downloaded from":"generated for"),
2602 trusted_dir->description, published);
2603 networkstatus_list_has_changed = 1;
2604 router_dir_info_changed();
2606 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
2608 if (!skewed)
2609 add_networkstatus_to_cache(s, source, ns);
2611 networkstatus_list_update_recent(now);
2613 return 0;
2616 /** How old do we allow a network-status to get before removing it
2617 * completely? */
2618 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
2619 /** Remove all very-old network_status_t objects from memory and from the
2620 * disk cache. */
2621 void
2622 networkstatus_list_clean(time_t now)
2624 int i;
2625 if (!networkstatus_list)
2626 return;
2628 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
2629 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2630 char *fname = NULL;
2631 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
2632 continue;
2633 /* Okay, this one is too old. Remove it from the list, and delete it
2634 * from the cache. */
2635 smartlist_del(networkstatus_list, i--);
2636 fname = networkstatus_get_cache_filename(ns->identity_digest);
2637 if (file_status(fname) == FN_FILE) {
2638 log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
2639 unlink(fname);
2641 tor_free(fname);
2642 if (get_options()->DirPort) {
2643 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
2645 networkstatus_free(ns);
2646 router_dir_info_changed();
2649 /* And now go through the directory cache for any cached untrusted
2650 * networkstatuses and other network info. */
2651 dirserv_clear_old_networkstatuses(now - MAX_NETWORKSTATUS_AGE);
2652 dirserv_clear_old_v1_info(now);
2655 /** Helper for bsearching a list of routerstatus_t pointers.*/
2656 static int
2657 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
2659 const char *key = _key;
2660 const routerstatus_t *rs = *_member;
2661 return memcmp(key, rs->identity_digest, DIGEST_LEN);
2664 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2665 * NULL if none was found. */
2666 static routerstatus_t *
2667 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
2669 return smartlist_bsearch(ns->entries, digest,
2670 _compare_digest_to_routerstatus_entry);
2673 /** Return the consensus view of the status of the router whose digest is
2674 * <b>digest</b>, or NULL if we don't know about any such router. */
2675 local_routerstatus_t *
2676 router_get_combined_status_by_digest(const char *digest)
2678 if (!routerstatus_list)
2679 return NULL;
2680 return smartlist_bsearch(routerstatus_list, digest,
2681 _compare_digest_to_routerstatus_entry);
2684 /** Return a newly allocated list of the local_routerstatus_t for all routers
2685 * where we believe that the digest of their current descriptor is some digest
2686 * listed in <b>digests</b>. */
2687 smartlist_t *
2688 router_get_combined_status_by_descriptor_digests(smartlist_t *digests)
2690 digestmap_t *map;
2691 smartlist_t *result;
2693 if (!routerstatus_list)
2694 return NULL;
2696 map = digestmap_new();
2697 result = smartlist_create();
2698 SMARTLIST_FOREACH(digests, const char *, d, digestmap_set(map, d, (void*)1));
2700 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs, {
2701 if (digestmap_get(map, lrs->status.descriptor_digest))
2702 smartlist_add(result, lrs);
2705 digestmap_free(map, NULL);
2706 return result;
2709 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
2710 * the corresponding local_routerstatus_t, or NULL if none exists. Warn the
2711 * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
2712 * nickname, but the Named flag isn't set for that router. */
2713 static local_routerstatus_t *
2714 router_get_combined_status_by_nickname(const char *nickname,
2715 int warn_if_unnamed)
2717 char digest[DIGEST_LEN];
2718 local_routerstatus_t *best=NULL;
2719 smartlist_t *matches=NULL;
2721 if (!routerstatus_list || !nickname)
2722 return NULL;
2724 if (nickname[0] == '$') {
2725 if (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))<0)
2726 return NULL;
2727 return router_get_combined_status_by_digest(digest);
2728 } else if (strlen(nickname) == HEX_DIGEST_LEN &&
2729 (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))==0)) {
2730 return router_get_combined_status_by_digest(digest);
2733 matches = smartlist_create();
2734 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
2736 if (!strcasecmp(lrs->status.nickname, nickname)) {
2737 if (lrs->status.is_named) {
2738 smartlist_free(matches);
2739 return lrs;
2740 } else {
2741 smartlist_add(matches, lrs);
2742 best = lrs;
2747 if (smartlist_len(matches)>1 && warn_if_unnamed) {
2748 int any_unwarned=0;
2749 SMARTLIST_FOREACH(matches, local_routerstatus_t *, lrs,
2751 if (! lrs->name_lookup_warned) {
2752 lrs->name_lookup_warned=1;
2753 any_unwarned=1;
2756 if (any_unwarned) {
2757 log_warn(LD_CONFIG,"There are multiple matches for the nickname \"%s\","
2758 " but none is listed as named by the directory authorites. "
2759 "Choosing one arbitrarily.", nickname);
2761 } else if (warn_if_unnamed && best && !best->name_lookup_warned) {
2762 char fp[HEX_DIGEST_LEN+1];
2763 base16_encode(fp, sizeof(fp),
2764 best->status.identity_digest, DIGEST_LEN);
2765 log_warn(LD_CONFIG,
2766 "When looking up a status, you specified a server \"%s\" by name, "
2767 "but the directory authorities do not have any key registered for "
2768 "this nickname -- so it could be used by any server, "
2769 "not just the one you meant. "
2770 "To make sure you get the same server in the future, refer to "
2771 "it by key, as \"$%s\".", nickname, fp);
2772 best->name_lookup_warned = 1;
2774 smartlist_free(matches);
2775 return best;
2778 /** Find a routerstatus_t that corresponds to <b>hexdigest</b>, if
2779 * any. Prefer ones that belong to authorities. */
2780 routerstatus_t *
2781 routerstatus_get_by_hexdigest(const char *hexdigest)
2783 char digest[DIGEST_LEN];
2784 local_routerstatus_t *rs;
2785 trusted_dir_server_t *ds;
2787 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2788 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
2789 return NULL;
2790 if ((ds = router_get_trusteddirserver_by_digest(digest)))
2791 return &(ds->fake_status.status);
2792 if ((rs = router_get_combined_status_by_digest(digest)))
2793 return &(rs->status);
2794 return NULL;
2797 /** Return true iff any networkstatus includes a descriptor whose digest
2798 * is that of <b>desc</b>. */
2799 static int
2800 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
2802 routerstatus_t *rs;
2803 if (!networkstatus_list)
2804 return 0;
2806 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2808 if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
2809 continue;
2810 if (!memcmp(rs->descriptor_digest,
2811 desc->signed_descriptor_digest, DIGEST_LEN))
2812 return 1;
2814 return 0;
2817 /** How frequently do directory authorities re-download fresh networkstatus
2818 * documents? */
2819 #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
2821 /** How frequently do non-authority directory caches re-download fresh
2822 * networkstatus documents? */
2823 #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
2825 /** We are a directory server, and so cache network_status documents.
2826 * Initiate downloads as needed to update them. For authorities, this means
2827 * asking each trusted directory for its network-status. For caches, this
2828 * means asking a random authority for all network-statuses.
2830 static void
2831 update_networkstatus_cache_downloads(time_t now)
2833 int authority = authdir_mode(get_options());
2834 int interval =
2835 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
2837 if (last_networkstatus_download_attempted + interval >= now)
2838 return;
2839 if (!trusted_dir_servers)
2840 return;
2842 last_networkstatus_download_attempted = now;
2844 if (authority) {
2845 /* An authority launches a separate connection for everybody. */
2846 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2848 char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
2849 if (!ds->is_v2_authority)
2850 continue;
2851 if (router_digest_is_me(ds->digest))
2852 continue;
2853 if (connection_get_by_type_addr_port_purpose(
2854 CONN_TYPE_DIR, ds->addr, ds->dir_port,
2855 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
2856 /* We are already fetching this one. */
2857 continue;
2859 strlcpy(resource, "fp/", sizeof(resource));
2860 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
2861 strlcat(resource, ".z", sizeof(resource));
2862 directory_initiate_command_routerstatus(
2863 &ds->fake_status.status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
2864 0, /* Not private */
2865 resource,
2866 NULL, 0 /* No payload. */);
2868 } else {
2869 /* A non-authority cache launches one connection to a random authority. */
2870 /* (Check whether we're currently fetching network-status objects.) */
2871 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
2872 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2873 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
2877 /** How long (in seconds) does a client wait after getting a network status
2878 * before downloading the next in sequence? */
2879 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2880 /** How many times do we allow a networkstatus download to fail before we
2881 * assume that the authority isn't publishing? */
2882 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2883 /** We are not a directory cache or authority. Update our network-status list
2884 * by launching a new directory fetch for enough network-status documents "as
2885 * necessary". See function comments for implementation details.
2887 static void
2888 update_networkstatus_client_downloads(time_t now)
2890 int n_live = 0, n_dirservers, n_running_dirservers, needed = 0;
2891 int fetch_latest = 0;
2892 int most_recent_idx = -1;
2893 trusted_dir_server_t *most_recent = NULL;
2894 time_t most_recent_received = 0;
2895 char *resource, *cp;
2896 size_t resource_len;
2897 smartlist_t *missing;
2899 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
2900 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2901 return;
2903 /* This is a little tricky. We want to download enough network-status
2904 * objects so that we have all of them under
2905 * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
2906 * *one* if the most recent one's publication time is under
2907 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2909 if (!get_n_v2_authorities())
2910 return;
2911 n_dirservers = n_running_dirservers = 0;
2912 missing = smartlist_create();
2913 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2915 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
2916 if (!ds->is_v2_authority)
2917 continue;
2918 ++n_dirservers;
2919 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
2920 continue;
2921 ++n_running_dirservers;
2922 if (ns && ns->published_on > now-NETWORKSTATUS_MAX_AGE)
2923 ++n_live;
2924 else
2925 smartlist_add(missing, ds->digest);
2926 if (ns && (!most_recent || ns->received_on > most_recent_received)) {
2927 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
2928 most_recent = ds;
2929 most_recent_received = ns->received_on;
2933 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2934 if (!smartlist_len(missing) &&
2935 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL) {
2936 log_info(LD_DIR, "Our most recent network-status document (from %s) "
2937 "is %d seconds old; downloading another.",
2938 most_recent?most_recent->description:"nobody",
2939 (int)(now-most_recent_received));
2940 fetch_latest = 1;
2941 needed = 1;
2942 } else if (smartlist_len(missing)) {
2943 log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
2944 " network-status documents. Downloading %d.",
2945 n_running_dirservers, n_dirservers, n_live,
2946 smartlist_len(missing));
2947 needed = smartlist_len(missing);
2948 } else {
2949 smartlist_free(missing);
2950 return;
2953 /* If no networkstatus was found, choose a dirserver at random as "most
2954 * recent". */
2955 if (most_recent_idx<0)
2956 most_recent_idx = crypto_rand_int(smartlist_len(trusted_dir_servers));
2958 if (fetch_latest) {
2959 int i;
2960 int n_failed = 0;
2961 for (i = most_recent_idx + 1; 1; ++i) {
2962 trusted_dir_server_t *ds;
2963 if (i >= smartlist_len(trusted_dir_servers))
2964 i = 0;
2965 ds = smartlist_get(trusted_dir_servers, i);
2966 if (! ds->is_v2_authority)
2967 continue;
2968 if (n_failed >= n_dirservers) {
2969 log_info(LD_DIR, "All authorities have failed. Not trying any.");
2970 smartlist_free(missing);
2971 return;
2973 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
2974 ++n_failed;
2975 continue;
2977 smartlist_add(missing, ds->digest);
2978 break;
2982 /* Build a request string for all the resources we want. */
2983 resource_len = smartlist_len(missing) * (HEX_DIGEST_LEN+1) + 6;
2984 resource = tor_malloc(resource_len);
2985 memcpy(resource, "fp/", 3);
2986 cp = resource+3;
2987 smartlist_sort_digests(missing);
2988 needed = smartlist_len(missing);
2989 SMARTLIST_FOREACH(missing, const char *, d,
2991 base16_encode(cp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
2992 cp += HEX_DIGEST_LEN;
2993 --needed;
2994 if (needed)
2995 *cp++ = '+';
2997 memcpy(cp, ".z", 3);
2998 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
2999 tor_free(resource);
3000 smartlist_free(missing);
3003 /** Launch requests for networkstatus documents as appropriate. */
3004 void
3005 update_networkstatus_downloads(time_t now)
3007 or_options_t *options = get_options();
3008 if (options->DirPort)
3009 update_networkstatus_cache_downloads(now);
3010 else
3011 update_networkstatus_client_downloads(now);
3014 /** Return 1 if all running sufficiently-stable routers will reject
3015 * addr:port, return 0 if any might accept it. */
3017 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3018 int need_uptime)
3020 addr_policy_result_t r;
3021 if (!routerlist) return 1;
3023 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
3025 if (router->is_running &&
3026 !router_is_unreliable(router, need_uptime, 0, 0)) {
3027 r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
3028 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
3029 return 0; /* this one could be ok. good enough. */
3032 return 1; /* all will reject. */
3035 /** Return true iff <b>router</b> does not permit exit streams.
3038 router_exit_policy_rejects_all(routerinfo_t *router)
3040 return compare_addr_to_addr_policy(0, 0, router->exit_policy)
3041 == ADDR_POLICY_REJECTED;
3044 /** Add to the list of authorized directory servers one at
3045 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3046 * <b>address</b> is NULL, add ourself. */
3047 void
3048 add_trusted_dir_server(const char *nickname, const char *address,
3049 uint16_t dir_port, uint16_t or_port,
3050 const char *digest, int is_v1_authority,
3051 int is_v2_authority, int is_hidserv_authority)
3053 trusted_dir_server_t *ent;
3054 uint32_t a;
3055 char *hostname = NULL;
3056 size_t dlen;
3057 if (!trusted_dir_servers)
3058 trusted_dir_servers = smartlist_create();
3060 if (!address) { /* The address is us; we should guess. */
3061 if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
3062 log_warn(LD_CONFIG,
3063 "Couldn't find a suitable address when adding ourself as a "
3064 "trusted directory server.");
3065 return;
3067 } else {
3068 if (tor_lookup_hostname(address, &a)) {
3069 log_warn(LD_CONFIG,
3070 "Unable to lookup address for directory server at '%s'",
3071 address);
3072 return;
3074 hostname = tor_strdup(address);
3075 a = ntohl(a);
3078 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
3079 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
3080 ent->address = hostname;
3081 ent->addr = a;
3082 ent->dir_port = dir_port;
3083 ent->or_port = or_port;
3084 ent->is_running = 1;
3085 ent->is_v1_authority = is_v1_authority;
3086 ent->is_v2_authority = is_v2_authority;
3087 ent->is_hidserv_authority = is_hidserv_authority;
3088 memcpy(ent->digest, digest, DIGEST_LEN);
3090 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
3091 ent->description = tor_malloc(dlen);
3092 if (nickname)
3093 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
3094 nickname, hostname, (int)dir_port);
3095 else
3096 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
3097 hostname, (int)dir_port);
3099 ent->fake_status.status.addr = ent->addr;
3100 memcpy(ent->fake_status.status.identity_digest, digest, DIGEST_LEN);
3101 if (nickname)
3102 strlcpy(ent->fake_status.status.nickname, nickname,
3103 sizeof(ent->fake_status.status.nickname));
3104 else
3105 ent->fake_status.status.nickname[0] = '\0';
3106 ent->fake_status.status.dir_port = ent->dir_port;
3107 ent->fake_status.status.or_port = ent->or_port;
3109 smartlist_add(trusted_dir_servers, ent);
3110 router_dir_info_changed();
3113 /** Free storage held in <b>ds</b> */
3114 static void
3115 trusted_dir_server_free(trusted_dir_server_t *ds)
3117 tor_free(ds->nickname);
3118 tor_free(ds->description);
3119 tor_free(ds->address);
3120 tor_free(ds);
3123 /** Remove all members from the list of trusted dir servers. */
3124 void
3125 clear_trusted_dir_servers(void)
3127 if (trusted_dir_servers) {
3128 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
3129 trusted_dir_server_free(ent));
3130 smartlist_clear(trusted_dir_servers);
3131 } else {
3132 trusted_dir_servers = smartlist_create();
3134 router_dir_info_changed();
3137 /** Return 1 if any trusted dir server supports v1 directories,
3138 * else return 0. */
3140 any_trusted_dir_is_v1_authority(void)
3142 if (trusted_dir_servers)
3143 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
3144 if (ent->is_v1_authority) return 1);
3145 return 0;
3148 /** Return the network status with a given identity digest. */
3149 networkstatus_t *
3150 networkstatus_get_by_digest(const char *digest)
3152 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3154 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
3155 return ns;
3157 return NULL;
3160 /** We believe networkstatuses more recent than this when they tell us that
3161 * our server is broken, invalid, obsolete, etc. */
3162 #define SELF_OPINION_INTERVAL (90*60)
3164 /** Result of checking whether a version is recommended. */
3165 typedef struct combined_version_status_t {
3166 /** How many networkstatuses claim to know about versions? */
3167 int n_versioning;
3168 /** What do the majority of networkstatuses believe about this version? */
3169 version_status_t consensus;
3170 /** How many networkstatuses constitute the majority? */
3171 int n_concurring;
3172 } combined_version_status_t;
3174 /** Return a string naming the versions of Tor recommended by
3175 * more than half the versioning networkstatuses. */
3176 static char *
3177 compute_recommended_versions(time_t now, int client,
3178 const char *my_version,
3179 combined_version_status_t *status_out)
3181 int n_seen;
3182 char *current;
3183 smartlist_t *combined, *recommended;
3184 int n_versioning, n_recommending;
3185 char *result;
3186 /** holds the compromise status taken among all non-recommending
3187 * authorities */
3188 version_status_t consensus = VS_RECOMMENDED;
3189 (void) now; /* right now, we consider *all* statuses, regardless of age. */
3191 tor_assert(my_version);
3192 tor_assert(status_out);
3194 memset(status_out, 0, sizeof(combined_version_status_t));
3196 if (!networkstatus_list)
3197 return tor_strdup("<none>");
3199 combined = smartlist_create();
3200 n_versioning = n_recommending = 0;
3201 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3203 const char *vers;
3204 smartlist_t *versions;
3205 version_status_t status;
3206 if (! ns->recommends_versions)
3207 continue;
3208 n_versioning++;
3209 vers = client ? ns->client_versions : ns->server_versions;
3210 if (!vers)
3211 continue;
3212 versions = smartlist_create();
3213 smartlist_split_string(versions, vers, ",",
3214 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3215 sort_version_list(versions, 1);
3216 smartlist_add_all(combined, versions);
3217 smartlist_free(versions);
3219 /* now, check _our_ version */
3220 status = tor_version_is_obsolete(my_version, vers);
3221 if (status == VS_RECOMMENDED)
3222 n_recommending++;
3223 consensus = version_status_join(status, consensus);
3226 sort_version_list(combined, 0);
3228 current = NULL;
3229 n_seen = 0;
3230 recommended = smartlist_create();
3231 SMARTLIST_FOREACH(combined, char *, cp,
3233 if (current && !strcmp(cp, current)) {
3234 ++n_seen;
3235 } else {
3236 if (n_seen > n_versioning/2 && current)
3237 smartlist_add(recommended, current);
3238 n_seen = 0;
3239 current = cp;
3242 if (n_seen > n_versioning/2 && current)
3243 smartlist_add(recommended, current);
3245 result = smartlist_join_strings(recommended, ", ", 0, NULL);
3247 SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
3248 smartlist_free(combined);
3249 smartlist_free(recommended);
3251 status_out->n_versioning = n_versioning;
3252 if (n_recommending > n_versioning/2) {
3253 status_out->consensus = VS_RECOMMENDED;
3254 status_out->n_concurring = n_recommending;
3255 } else {
3256 status_out->consensus = consensus;
3257 status_out->n_concurring = n_versioning - n_recommending;
3260 return result;
3263 /** How many times do we have to fail at getting a networkstatus we can't find
3264 * before we're willing to believe it's okay to set up router statuses? */
3265 #define N_NS_ATTEMPTS_TO_SET_ROUTERS 4
3266 /** How many times do we have to fail at getting a networkstatus we can't find
3267 * before we're willing to believe it's okay to check our version? */
3268 #define N_NS_ATTEMPTS_TO_CHECK_VERSION 4
3270 /** If the network-status list has changed since the last time we called this
3271 * function, update the status of every routerinfo from the network-status
3272 * list.
3274 void
3275 routers_update_all_from_networkstatus(void)
3277 routerinfo_t *me;
3278 time_t now;
3279 if (!routerlist || !networkstatus_list ||
3280 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
3281 return;
3283 router_dir_info_changed();
3285 now = time(NULL);
3286 if (networkstatus_list_has_changed)
3287 routerstatus_list_update_from_networkstatus(now);
3289 routers_update_status_from_networkstatus(routerlist->routers, 0);
3291 me = router_get_my_routerinfo();
3292 if (me && !have_warned_about_invalid_status &&
3293 have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_SET_ROUTERS)) {
3294 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0, n_naming = 0;
3295 routerstatus_t *rs;
3296 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3298 if (ns->received_on + SELF_OPINION_INTERVAL < now)
3299 continue;
3300 ++n_recent;
3301 if (ns->binds_names)
3302 ++n_naming;
3303 if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
3304 continue;
3305 ++n_listing;
3306 if (rs->is_valid)
3307 ++n_valid;
3308 if (rs->is_named)
3309 ++n_named;
3312 if (n_listing) {
3313 if (n_valid <= n_listing/2) {
3314 log_info(LD_GENERAL,
3315 "%d/%d recent statements from directory authorities list us "
3316 "as unapproved. Are you misconfigured?",
3317 n_listing-n_valid, n_listing);
3318 have_warned_about_invalid_status = 1;
3319 } else if (n_naming && !n_named) {
3320 log_info(LD_GENERAL, "0/%d name-binding directory authorities "
3321 "recognize your nickname. Please consider sending your "
3322 "nickname and identity fingerprint to the tor-ops.",
3323 n_naming);
3324 have_warned_about_invalid_status = 1;
3329 entry_guards_compute_status();
3331 if (!have_warned_about_old_version &&
3332 have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_CHECK_VERSION)) {
3333 combined_version_status_t st;
3334 int is_server = server_mode(get_options());
3335 char *recommended;
3337 recommended = compute_recommended_versions(now, !is_server, VERSION, &st);
3339 if (st.n_versioning) {
3340 if (st.consensus == VS_RECOMMENDED) {
3341 log_info(LD_GENERAL, "%d/%d statements from version-listing "
3342 "directory authorities say my version is ok.",
3343 st.n_concurring, st.n_versioning);
3344 } else if (st.consensus == VS_NEW || st.consensus == VS_NEW_IN_SERIES) {
3345 if (!have_warned_about_new_version) {
3346 log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
3347 "recommended version%s, according to %d/%d version-listing "
3348 "network statuses. Versions recommended by more than %d "
3349 "authorit%s are: %s",
3350 VERSION,
3351 st.consensus == VS_NEW_IN_SERIES ? " in its series" : "",
3352 st.n_concurring, st.n_versioning, st.n_versioning/2,
3353 st.n_versioning/2 > 1 ? "ies" : "y", recommended);
3354 have_warned_about_new_version = 1;
3355 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
3356 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3357 VERSION, "NEW", recommended);
3359 } else {
3360 log_warn(LD_GENERAL, "Please upgrade! "
3361 "This version of Tor (%s) is %s, according to %d/%d version-"
3362 "listing network statuses. Versions recommended by "
3363 "at least %d authorit%s are: %s",
3364 VERSION,
3365 st.consensus == VS_OLD ? "obsolete" : "not recommended",
3366 st.n_concurring, st.n_versioning, st.n_versioning/2,
3367 st.n_versioning/2 > 1 ? "ies" : "y", recommended);
3368 have_warned_about_old_version = 1;
3369 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
3370 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3371 VERSION, st.consensus == VS_OLD ? "OLD" : "UNRECOMMENDED",
3372 recommended);
3375 tor_free(recommended);
3378 routerstatus_list_has_changed = 0;
3381 /** Allow any network-status newer than this to influence our view of who's
3382 * running. */
3383 #define DEFAULT_RUNNING_INTERVAL (60*60)
3384 /** If possible, always allow at least this many network-statuses to influence
3385 * our view of who's running. */
3386 #define MIN_TO_INFLUENCE_RUNNING 3
3388 /** Change the is_recent field of each member of networkstatus_list so that
3389 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
3390 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
3391 * others are recent. Set networkstatus_list_has_changed if anything happened.
3393 void
3394 networkstatus_list_update_recent(time_t now)
3396 int n_statuses, n_recent, changed, i;
3397 char published[ISO_TIME_LEN+1];
3399 if (!networkstatus_list)
3400 return;
3402 n_statuses = smartlist_len(networkstatus_list);
3403 n_recent = 0;
3404 changed = 0;
3405 for (i=n_statuses-1; i >= 0; --i) {
3406 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
3407 trusted_dir_server_t *ds =
3408 router_get_trusteddirserver_by_digest(ns->identity_digest);
3409 const char *src = ds?ds->description:ns->source_address;
3410 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
3411 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
3412 if (!ns->is_recent) {
3413 format_iso_time(published, ns->published_on);
3414 log_info(LD_DIR,
3415 "Networkstatus from %s (published %s) is now \"recent\"",
3416 src, published);
3417 changed = 1;
3419 ns->is_recent = 1;
3420 ++n_recent;
3421 } else {
3422 if (ns->is_recent) {
3423 format_iso_time(published, ns->published_on);
3424 log_info(LD_DIR,
3425 "Networkstatus from %s (published %s) is "
3426 "no longer \"recent\"",
3427 src, published);
3428 changed = 1;
3429 ns->is_recent = 0;
3433 if (changed) {
3434 networkstatus_list_has_changed = 1;
3435 router_dir_info_changed();
3439 /** Helper for routerstatus_list_update_from_networkstatus: remember how many
3440 * authorities recommend a given descriptor digest. */
3441 typedef struct {
3442 routerstatus_t *rs;
3443 int count;
3444 } desc_digest_count_t;
3446 /** Update our view of router status (as stored in routerstatus_list) from the
3447 * current set of network status documents (as stored in networkstatus_list).
3448 * Do nothing unless the network status list has changed since the last time
3449 * this function was called.
3451 static void
3452 routerstatus_list_update_from_networkstatus(time_t now)
3454 or_options_t *options = get_options();
3455 int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
3456 int n_listing_bad_exits = 0, n_listing_bad_directories = 0;
3457 int i, j, warned;
3458 int *index, *size;
3459 networkstatus_t **networkstatus;
3460 smartlist_t *result, *changed_list;
3461 strmap_t *name_map;
3462 char conflict[DIGEST_LEN]; /* Sentinel value */
3463 desc_digest_count_t *digest_counts = NULL;
3465 /* compute which network statuses will have a vote now */
3466 networkstatus_list_update_recent(now);
3467 router_dir_info_changed();
3469 if (!networkstatus_list_has_changed)
3470 return;
3471 if (!networkstatus_list)
3472 networkstatus_list = smartlist_create();
3473 if (!routerstatus_list)
3474 routerstatus_list = smartlist_create();
3475 if (!trusted_dir_servers)
3476 trusted_dir_servers = smartlist_create();
3477 if (!warned_conflicts)
3478 warned_conflicts = smartlist_create();
3480 n_statuses = smartlist_len(networkstatus_list);
3481 n_trusted = get_n_v2_authorities();
3483 if (n_statuses <= n_trusted/2) {
3484 /* Not enough statuses to adjust status. */
3485 log_info(LD_DIR,
3486 "Not enough statuses to update router status list. (%d/%d)",
3487 n_statuses, n_trusted);
3488 return;
3491 log_info(LD_DIR, "Rebuilding router status list.");
3493 index = tor_malloc(sizeof(int)*n_statuses);
3494 size = tor_malloc(sizeof(int)*n_statuses);
3495 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
3496 for (i = 0; i < n_statuses; ++i) {
3497 index[i] = 0;
3498 networkstatus[i] = smartlist_get(networkstatus_list, i);
3499 size[i] = smartlist_len(networkstatus[i]->entries);
3500 if (networkstatus[i]->binds_names)
3501 ++n_naming;
3502 if (networkstatus[i]->is_recent)
3503 ++n_recent;
3504 if (networkstatus[i]->lists_bad_exits)
3505 ++n_listing_bad_exits;
3506 if (networkstatus[i]->lists_bad_directories)
3507 ++n_listing_bad_directories;
3510 /** Iterate over all entries in all networkstatuses, and build
3511 * name_map as a map from lc nickname to identity digest. If there
3512 * is a conflict on that nickname, map the lc nickname to conflict.
3514 name_map = strmap_new();
3515 /* Clear the global map... */
3516 if (named_server_map)
3517 strmap_free(named_server_map, _tor_free);
3518 named_server_map = strmap_new();
3519 memset(conflict, 0xff, sizeof(conflict));
3520 for (i = 0; i < n_statuses; ++i) {
3521 if (!networkstatus[i]->binds_names)
3522 continue;
3523 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
3525 const char *other_digest;
3526 if (!rs->is_named)
3527 continue;
3528 other_digest = strmap_get_lc(name_map, rs->nickname);
3529 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
3530 if (!other_digest) {
3531 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
3532 strmap_set_lc(named_server_map, rs->nickname,
3533 tor_memdup(rs->identity_digest, DIGEST_LEN));
3534 if (warned)
3535 smartlist_string_remove(warned_conflicts, rs->nickname);
3536 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
3537 other_digest != conflict) {
3538 if (!warned) {
3539 char *d;
3540 int should_warn = options->DirPort && options->AuthoritativeDir;
3541 char fp1[HEX_DIGEST_LEN+1];
3542 char fp2[HEX_DIGEST_LEN+1];
3543 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
3544 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
3545 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
3546 "Naming authorities disagree about which key goes with %s. "
3547 "($%s vs $%s)",
3548 rs->nickname, fp1, fp2);
3549 strmap_set_lc(name_map, rs->nickname, conflict);
3550 d = strmap_remove_lc(named_server_map, rs->nickname);
3551 tor_free(d);
3552 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
3554 } else {
3555 if (warned)
3556 smartlist_string_remove(warned_conflicts, rs->nickname);
3561 result = smartlist_create();
3562 changed_list = smartlist_create();
3563 digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
3565 /* Iterate through all of the sorted routerstatus lists in lockstep.
3566 * Invariants:
3567 * - For 0 <= i < n_statuses: index[i] is an index into
3568 * networkstatus[i]->entries, which has size[i] elements.
3569 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
3570 * j < index[i1]: networkstatus[i1]->entries[j]->identity_digest <
3571 * networkstatus[i2]->entries[index[i2]]->identity_digest.
3573 * (That is, the indices are always advanced past lower digest before
3574 * higher.)
3576 while (1) {
3577 int n_running=0, n_named=0, n_valid=0, n_listing=0;
3578 int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0, n_bad_exit=0;
3579 int n_bad_directory=0;
3580 int n_version_known=0, n_supports_begindir=0;
3581 int n_desc_digests=0, highest_count=0;
3582 const char *the_name = NULL;
3583 local_routerstatus_t *rs_out, *rs_old;
3584 routerstatus_t *rs, *most_recent;
3585 networkstatus_t *ns;
3586 const char *lowest = NULL;
3588 /* Find out which of the digests appears first. */
3589 for (i = 0; i < n_statuses; ++i) {
3590 if (index[i] < size[i]) {
3591 rs = smartlist_get(networkstatus[i]->entries, index[i]);
3592 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
3593 lowest = rs->identity_digest;
3596 if (!lowest) {
3597 /* We're out of routers. Great! */
3598 break;
3600 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
3601 * match "lowest" are next in order. Iterate over them, incrementing those
3602 * index[i] as we go. */
3603 for (i = 0; i < n_statuses; ++i) {
3604 if (index[i] >= size[i])
3605 continue;
3606 ns = networkstatus[i];
3607 rs = smartlist_get(ns->entries, index[i]);
3608 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
3609 continue;
3610 /* At this point, we know that we're looking at a routersatus with
3611 * identity "lowest".
3613 ++index[i];
3614 ++n_listing;
3615 /* Should we name this router? Only if all the names from naming
3616 * authorities match. */
3617 if (rs->is_named && ns->binds_names) {
3618 if (!the_name)
3619 the_name = rs->nickname;
3620 if (!strcasecmp(rs->nickname, the_name)) {
3621 ++n_named;
3622 } else if (strcmp(the_name,"**mismatch**")) {
3623 char hd[HEX_DIGEST_LEN+1];
3624 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
3625 if (! smartlist_string_isin(warned_conflicts, hd)) {
3626 log_warn(LD_DIR,
3627 "Naming authorities disagree about nicknames for $%s "
3628 "(\"%s\" vs \"%s\")",
3629 hd, the_name, rs->nickname);
3630 smartlist_add(warned_conflicts, tor_strdup(hd));
3632 the_name = "**mismatch**";
3635 /* Keep a running count of how often which descriptor digests
3636 * appear. */
3637 for (j = 0; j < n_desc_digests; ++j) {
3638 if (!memcmp(rs->descriptor_digest,
3639 digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
3640 if (++digest_counts[j].count > highest_count)
3641 highest_count = digest_counts[j].count;
3642 goto found;
3645 digest_counts[n_desc_digests].rs = rs;
3646 digest_counts[n_desc_digests].count = 1;
3647 if (!highest_count)
3648 highest_count = 1;
3649 ++n_desc_digests;
3650 found:
3651 /* Now tally up the easily-tallied flags. */
3652 if (rs->is_valid)
3653 ++n_valid;
3654 if (rs->is_running && ns->is_recent)
3655 ++n_running;
3656 if (rs->is_exit)
3657 ++n_exit;
3658 if (rs->is_fast)
3659 ++n_fast;
3660 if (rs->is_possible_guard)
3661 ++n_guard;
3662 if (rs->is_stable)
3663 ++n_stable;
3664 if (rs->is_v2_dir)
3665 ++n_v2_dir;
3666 if (rs->is_bad_exit)
3667 ++n_bad_exit;
3668 if (rs->is_bad_directory)
3669 ++n_bad_directory;
3670 if (rs->version_known)
3671 ++n_version_known;
3672 if (rs->version_supports_begindir)
3673 ++n_supports_begindir;
3675 /* Go over the descriptor digests and figure out which descriptor we
3676 * want. */
3677 most_recent = NULL;
3678 for (i = 0; i < n_desc_digests; ++i) {
3679 /* If any digest appears twice or more, ignore those that don't.*/
3680 if (highest_count >= 2 && digest_counts[i].count < 2)
3681 continue;
3682 if (!most_recent ||
3683 digest_counts[i].rs->published_on > most_recent->published_on)
3684 most_recent = digest_counts[i].rs;
3686 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
3687 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
3688 /* Copy status info about this router, if we had any before. */
3689 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
3690 if (!memcmp(rs_out->status.descriptor_digest,
3691 most_recent->descriptor_digest, DIGEST_LEN)) {
3692 rs_out->n_download_failures = rs_old->n_download_failures;
3693 rs_out->next_attempt_at = rs_old->next_attempt_at;
3695 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
3696 rs_out->last_dir_503_at = rs_old->last_dir_503_at;
3698 smartlist_add(result, rs_out);
3699 log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
3700 "named by %d/%d, validated by %d/%d, and %d/%d recent "
3701 "directories think it's running.",
3702 rs_out->status.nickname,
3703 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
3704 n_running, n_recent);
3705 rs_out->status.is_named = 0;
3706 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
3707 const char *d = strmap_get_lc(name_map, the_name);
3708 if (d && d != conflict)
3709 rs_out->status.is_named = 1;
3710 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
3711 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
3713 if (rs_out->status.is_named)
3714 strlcpy(rs_out->status.nickname, the_name,
3715 sizeof(rs_out->status.nickname));
3716 rs_out->status.is_valid = n_valid > n_statuses/2;
3717 rs_out->status.is_running = n_running > n_recent/2;
3718 rs_out->status.is_exit = n_exit > n_statuses/2;
3719 rs_out->status.is_fast = n_fast > n_statuses/2;
3720 rs_out->status.is_possible_guard = n_guard > n_statuses/2;
3721 rs_out->status.is_stable = n_stable > n_statuses/2;
3722 rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
3723 rs_out->status.is_bad_exit = n_bad_exit > n_listing_bad_exits/2;
3724 rs_out->status.is_bad_directory =
3725 n_bad_directory > n_listing_bad_directories/2;
3726 rs_out->status.version_known = n_version_known > 0;
3727 rs_out->status.version_supports_begindir =
3728 n_supports_begindir > n_version_known/2;
3729 if (!rs_old || memcmp(rs_old, rs_out, sizeof(local_routerstatus_t)))
3730 smartlist_add(changed_list, rs_out);
3732 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3733 local_routerstatus_free(rs));
3735 smartlist_free(routerstatus_list);
3736 routerstatus_list = result;
3738 tor_free(networkstatus);
3739 tor_free(index);
3740 tor_free(size);
3741 tor_free(digest_counts);
3742 strmap_free(name_map, NULL);
3744 networkstatus_list_has_changed = 0;
3745 routerstatus_list_has_changed = 1;
3747 control_event_networkstatus_changed(changed_list);
3748 smartlist_free(changed_list);
3751 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
3752 * is_named, is_valid, and is_running fields according to our current
3753 * networkstatus_t documents. */
3754 void
3755 routers_update_status_from_networkstatus(smartlist_t *routers,
3756 int reset_failures)
3758 trusted_dir_server_t *ds;
3759 local_routerstatus_t *rs;
3760 or_options_t *options = get_options();
3761 int authdir = options->AuthoritativeDir;
3762 int namingdir = options->AuthoritativeDir &&
3763 options->NamingAuthoritativeDir;
3765 if (!routerstatus_list)
3766 return;
3768 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
3770 const char *digest = router->cache_info.identity_digest;
3771 rs = router_get_combined_status_by_digest(digest);
3772 ds = router_get_trusteddirserver_by_digest(digest);
3774 if (!rs)
3775 continue;
3777 if (!namingdir)
3778 router->is_named = rs->status.is_named;
3780 if (!authdir) {
3781 /* If we're not an authdir, believe others. */
3782 router->is_valid = rs->status.is_valid;
3783 router->is_running = rs->status.is_running;
3784 router->is_fast = rs->status.is_fast;
3785 router->is_stable = rs->status.is_stable;
3786 router->is_possible_guard = rs->status.is_possible_guard;
3787 router->is_exit = rs->status.is_exit;
3788 router->is_bad_exit = rs->status.is_bad_exit;
3790 if (router->is_running && ds) {
3791 ds->n_networkstatus_failures = 0;
3793 if (reset_failures) {
3794 rs->n_download_failures = 0;
3795 rs->next_attempt_at = 0;
3798 router_dir_info_changed();
3801 /** For every router descriptor we are currently downloading by descriptor
3802 * digest, set result[d] to 1. */
3803 static void
3804 list_pending_descriptor_downloads(digestmap_t *result)
3806 const char *prefix = "d/";
3807 size_t p_len = strlen(prefix);
3808 int i, n_conns;
3809 connection_t **carray;
3810 smartlist_t *tmp = smartlist_create();
3812 tor_assert(result);
3813 get_connection_array(&carray, &n_conns);
3815 for (i = 0; i < n_conns; ++i) {
3816 connection_t *conn = carray[i];
3817 if (conn->type == CONN_TYPE_DIR &&
3818 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
3819 !conn->marked_for_close) {
3820 const char *resource = TO_DIR_CONN(conn)->requested_resource;
3821 if (!strcmpstart(resource, prefix))
3822 dir_split_resource_into_fingerprints(resource + p_len,
3823 tmp, NULL, 1, 0);
3826 SMARTLIST_FOREACH(tmp, char *, d,
3828 digestmap_set(result, d, (void*)1);
3829 tor_free(d);
3831 smartlist_free(tmp);
3834 /** Launch downloads for all the descriptors whose digests are listed
3835 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3836 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3837 * download from an appropriate random directory server.
3839 static void
3840 initiate_descriptor_downloads(routerstatus_t *source,
3841 smartlist_t *digests,
3842 int lo, int hi)
3844 int i, n = hi-lo;
3845 char *resource, *cp;
3846 size_t r_len;
3847 if (n <= 0)
3848 return;
3849 if (lo < 0)
3850 lo = 0;
3851 if (hi > smartlist_len(digests))
3852 hi = smartlist_len(digests);
3854 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
3855 cp = resource = tor_malloc(r_len);
3856 memcpy(cp, "d/", 2);
3857 cp += 2;
3858 for (i = lo; i < hi; ++i) {
3859 base16_encode(cp, r_len-(cp-resource),
3860 smartlist_get(digests,i), DIGEST_LEN);
3861 cp += HEX_DIGEST_LEN;
3862 *cp++ = '+';
3864 memcpy(cp-1, ".z", 3);
3866 if (source) {
3867 /* We know which authority we want. */
3868 directory_initiate_command_routerstatus(source,
3869 DIR_PURPOSE_FETCH_SERVERDESC,
3870 0, /* not private */
3871 resource, NULL, 0);
3872 } else {
3873 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
3874 resource,
3877 tor_free(resource);
3880 /** Clients don't download any descriptor this recent, since it will probably
3881 * not have propageted to enough caches. */
3882 #define ESTIMATED_PROPAGATION_TIME (10*60)
3884 /** Return 0 if this routerstatus is obsolete, too new, isn't
3885 * running, or otherwise not a descriptor that we would make any
3886 * use of even if we had it. Else return 1. */
3887 static INLINE int
3888 client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
3890 if (!rs->is_running && !options->FetchUselessDescriptors) {
3891 /* If we had this router descriptor, we wouldn't even bother using it.
3892 * But, if we want to have a complete list, fetch it anyway. */
3893 return 0;
3895 if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
3896 /* Most caches probably don't have this descriptor yet. */
3897 return 0;
3899 return 1;
3902 /** Return new list of ID fingerprints for routers that we (as a client) would
3903 * like to download.
3905 static smartlist_t *
3906 router_list_client_downloadable(void)
3908 int n_downloadable = 0;
3909 smartlist_t *downloadable = smartlist_create();
3910 digestmap_t *downloading;
3911 time_t now = time(NULL);
3912 /* these are just used for logging */
3913 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_wouldnt_use = 0;
3914 or_options_t *options = get_options();
3916 if (!routerstatus_list)
3917 return downloadable;
3919 downloading = digestmap_new();
3920 list_pending_descriptor_downloads(downloading);
3922 routerstatus_list_update_from_networkstatus(now);
3923 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3925 routerinfo_t *ri;
3926 if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
3927 /* We have the 'best' descriptor for this router. */
3928 ++n_uptodate;
3929 } else if (!client_would_use_router(&rs->status, now, options)) {
3930 /* We wouldn't want this descriptor even if we got it. */
3931 ++n_wouldnt_use;
3932 } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
3933 /* We're downloading this one now. */
3934 ++n_in_progress;
3935 } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
3936 ri->cache_info.published_on > rs->status.published_on) {
3937 /* Oddly, we have a descriptor more recent than the 'best' one, but it
3938 was once best. So that's okay. */
3939 ++n_uptodate;
3940 } else if (rs->next_attempt_at > now) {
3941 /* We failed too recently to try again. */
3942 ++n_not_ready;
3943 } else {
3944 /* Okay, time to try it. */
3945 smartlist_add(downloadable, rs->status.descriptor_digest);
3946 ++n_downloadable;
3950 #if 0
3951 log_info(LD_DIR,
3952 "%d router descriptors are downloadable. "
3953 "%d are in progress. %d are up-to-date. "
3954 "%d are non-useful. %d failed too recently to retry.",
3955 n_downloadable, n_in_progress, n_uptodate,
3956 n_wouldnt_use, n_not_ready);
3957 #endif
3959 digestmap_free(downloading, NULL);
3960 return downloadable;
3963 /** Initiate new router downloads as needed, using the strategy for
3964 * non-directory-servers.
3966 * We don't launch any downloads if there are fewer than MAX_DL_TO_DELAY
3967 * descriptors to get and less than MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
3968 * seconds have passed.
3970 * Otherwise, we ask for all descriptors that we think are different from what
3971 * we have, and that we don't currently have an in-progress download attempt
3972 * for. */
3973 static void
3974 update_router_descriptor_client_downloads(time_t now)
3976 /** Max amount of hashes to download per request.
3977 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3978 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3979 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3980 * So use 96 because it's a nice number.
3982 #define MAX_DL_PER_REQUEST 96
3983 /** Don't split our requests so finely that we are requesting fewer than
3984 * this number per server. */
3985 #define MIN_DL_PER_REQUEST 4
3986 /** To prevent a single screwy cache from confusing us by selective reply,
3987 * try to split our requests into at least this this many requests. */
3988 #define MIN_REQUESTS 3
3989 /** If we want fewer than this many descriptors, wait until we
3990 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3991 * passed. */
3992 #define MAX_DL_TO_DELAY 16
3993 /** When directory clients have only a few servers to request, they batch
3994 * them until they have more, or until this amount of time has passed. */
3995 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3996 smartlist_t *downloadable = NULL;
3997 int should_delay, n_downloadable;
3998 or_options_t *options = get_options();
4000 if (options->DirPort) {
4001 log_warn(LD_BUG,
4002 "Called router_descriptor_client_downloads() on a dir mirror?");
4005 if (rep_hist_circbuilding_dormant(now)) {
4006 log_info(LD_CIRC, "Skipping descriptor downloads: we haven't needed "
4007 "any circuits lately.");
4008 return;
4011 if (networkstatus_list &&
4012 smartlist_len(networkstatus_list) <= get_n_v2_authorities()/2) {
4013 log_info(LD_DIR,
4014 "Not enough networkstatus documents to launch requests.");
4015 return;
4018 downloadable = router_list_client_downloadable();
4019 n_downloadable = smartlist_len(downloadable);
4020 if (n_downloadable >= MAX_DL_TO_DELAY) {
4021 log_debug(LD_DIR,
4022 "There are enough downloadable routerdescs to launch requests.");
4023 should_delay = 0;
4024 } else if (n_downloadable == 0) {
4025 // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
4026 should_delay = 1;
4027 } else {
4028 should_delay = (last_routerdesc_download_attempted +
4029 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
4030 if (!should_delay) {
4031 if (last_routerdesc_download_attempted) {
4032 log_info(LD_DIR,
4033 "There are not many downloadable routerdescs, but we've "
4034 "been waiting long enough (%d seconds). Downloading.",
4035 (int)(now-last_routerdesc_download_attempted));
4036 } else {
4037 log_info(LD_DIR,
4038 "There are not many downloadable routerdescs, but we haven't "
4039 "tried downloading descriptors recently. Downloading.");
4044 if (! should_delay) {
4045 int i, n_per_request;
4046 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
4047 if (n_per_request > MAX_DL_PER_REQUEST)
4048 n_per_request = MAX_DL_PER_REQUEST;
4049 if (n_per_request < MIN_DL_PER_REQUEST)
4050 n_per_request = MIN_DL_PER_REQUEST;
4052 log_info(LD_DIR,
4053 "Launching %d request%s for %d router%s, %d at a time",
4054 (n_downloadable+n_per_request-1)/n_per_request,
4055 n_downloadable>n_per_request?"s":"",
4056 n_downloadable, n_downloadable>1?"s":"", n_per_request);
4057 smartlist_sort_digests(downloadable);
4058 for (i=0; i < n_downloadable; i += n_per_request) {
4059 initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
4061 last_routerdesc_download_attempted = now;
4063 smartlist_free(downloadable);
4066 /** Launch downloads for router status as needed, using the strategy used by
4067 * authorities and caches: download every descriptor we don't have but would
4068 * serve, from a random authority that lists it. */
4069 static void
4070 update_router_descriptor_cache_downloads(time_t now)
4072 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
4073 smartlist_t **download_from; /* ... and, what will we dl from it? */
4074 digestmap_t *map; /* Which descs are in progress, or assigned? */
4075 int i, j, n;
4076 int n_download;
4077 or_options_t *options = get_options();
4078 (void) now;
4080 if (!options->DirPort) {
4081 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
4082 "on a non-dir-mirror?");
4085 if (!networkstatus_list || !smartlist_len(networkstatus_list))
4086 return;
4088 map = digestmap_new();
4089 n = smartlist_len(networkstatus_list);
4091 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
4092 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
4094 /* Set map[d]=1 for the digest of every descriptor that we are currently
4095 * downloading. */
4096 list_pending_descriptor_downloads(map);
4098 /* For the digest of every descriptor that we don't have, and that we aren't
4099 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4100 * about that descriptor, and we haven't already failed to get that
4101 * descriptor from the corresponding authority.
4103 n_download = 0;
4104 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
4106 trusted_dir_server_t *ds;
4107 smartlist_t *dl;
4108 dl = downloadable[ns_sl_idx] = smartlist_create();
4109 download_from[ns_sl_idx] = smartlist_create();
4110 if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
4111 /* Don't download if the networkstatus is almost ancient. */
4112 /* Actually, I suspect what's happening here is that we ask
4113 * for the descriptor when we have a given networkstatus,
4114 * and then we get a newer networkstatus, and then we receive
4115 * the descriptor. Having a networkstatus actually expire is
4116 * probably a rare event, and we'll probably be happiest if
4117 * we take this clause out. -RD */
4118 continue;
4121 /* Don't try dirservers that we think are down -- we might have
4122 * just tried them and just marked them as down. */
4123 ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
4124 if (ds && !ds->is_running)
4125 continue;
4127 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
4129 if (!rs->need_to_mirror)
4130 continue;
4131 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4132 log_warn(LD_BUG,
4133 "Bug: We have a router descriptor, but need_to_mirror=1.");
4134 rs->need_to_mirror = 0;
4135 continue;
4137 if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
4138 rs->need_to_mirror = 0;
4139 continue;
4141 if (digestmap_get(map, rs->descriptor_digest)) {
4142 /* We're downloading it already. */
4143 continue;
4144 } else {
4145 /* We could download it from this guy. */
4146 smartlist_add(dl, rs->descriptor_digest);
4147 ++n_download;
4152 /* At random, assign descriptors to authorities such that:
4153 * - if d is a member of some downloadable[x], d is a member of some
4154 * download_from[y]. (Everything we want to download, we try to download
4155 * from somebody.)
4156 * - If d is a member of download_from[y], d is a member of downloadable[y].
4157 * (We only try to download descriptors from authorities who claim to have
4158 * them.)
4159 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4160 * (We don't try to download anything from two authorities concurrently.)
4162 while (n_download) {
4163 int which_ns = crypto_rand_int(n);
4164 smartlist_t *dl = downloadable[which_ns];
4165 int idx;
4166 char *d;
4167 if (!smartlist_len(dl))
4168 continue;
4169 idx = crypto_rand_int(smartlist_len(dl));
4170 d = smartlist_get(dl, idx);
4171 if (! digestmap_get(map, d)) {
4172 smartlist_add(download_from[which_ns], d);
4173 digestmap_set(map, d, (void*) 1);
4175 smartlist_del(dl, idx);
4176 --n_download;
4179 /* Now, we can actually launch our requests. */
4180 for (i=0; i<n; ++i) {
4181 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
4182 trusted_dir_server_t *ds =
4183 router_get_trusteddirserver_by_digest(ns->identity_digest);
4184 smartlist_t *dl = download_from[i];
4185 if (!ds) {
4186 log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
4187 continue;
4189 if (! smartlist_len(dl))
4190 continue;
4191 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
4192 smartlist_len(dl), ds->nickname);
4193 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
4194 initiate_descriptor_downloads(&(ds->fake_status.status), dl, j,
4195 j+MAX_DL_PER_REQUEST);
4199 for (i=0; i<n; ++i) {
4200 smartlist_free(download_from[i]);
4201 smartlist_free(downloadable[i]);
4203 tor_free(download_from);
4204 tor_free(downloadable);
4205 digestmap_free(map,NULL);
4208 /** Launch downloads for router status as needed. */
4209 void
4210 update_router_descriptor_downloads(time_t now)
4212 or_options_t *options = get_options();
4213 if (options->DirPort) {
4214 update_router_descriptor_cache_downloads(now);
4215 } else {
4216 update_router_descriptor_client_downloads(now);
4220 /** Return the number of routerstatus_t in <b>entries</b> that we'd actually
4221 * use. */
4222 static int
4223 routerstatus_count_usable_entries(smartlist_t *entries)
4225 int count = 0;
4226 time_t now = time(NULL);
4227 or_options_t *options = get_options();
4228 SMARTLIST_FOREACH(entries, routerstatus_t *, rs,
4229 if (client_would_use_router(rs, now, options)) count++);
4230 return count;
4233 /** True iff, the last time we checked whether we had enough directory info
4234 * to build circuits, the answer was "yes". */
4235 static int have_min_dir_info = 0;
4236 /** True iff enough has changed since the last time we checked whether we had
4237 * enough directory info to build circuits that our old answer can no longer
4238 * be trusted. */
4239 static int need_to_update_have_min_dir_info = 1;
4241 /** Return true iff we have enough networkstatus and router information to
4242 * start building circuits. Right now, this means "more than half the
4243 * networkstatus documents, and at least 1/4 of expected routers." */
4244 //XXX should consider whether we have enough exiting nodes here.
4246 router_have_minimum_dir_info(void)
4248 if (PREDICT(need_to_update_have_min_dir_info, 0)) {
4249 update_router_have_minimum_dir_info();
4250 need_to_update_have_min_dir_info = 0;
4252 return have_min_dir_info;
4255 /** Called when our internal view of the directory has changed. This can be
4256 * when the authorities change, networkstatuses change, the list of routerdescs
4257 * changes, or number of running routers changes.
4259 static void
4260 router_dir_info_changed(void)
4262 need_to_update_have_min_dir_info = 1;
4265 /** Change the value of have_min_dir_info, setting it true iff we have enough
4266 * network and router information to build circuits. Clear the value of
4267 * need_to_update_have_min_dir_info. */
4268 static void
4269 update_router_have_minimum_dir_info(void)
4271 int tot = 0, num_running = 0;
4272 int n_ns, n_authorities, res, avg;
4273 time_t now = time(NULL);
4274 if (!networkstatus_list || !routerlist) {
4275 res = 0;
4276 goto done;
4278 routerlist_remove_old_routers();
4279 networkstatus_list_clean(now);
4281 n_authorities = get_n_v2_authorities();
4282 n_ns = smartlist_len(networkstatus_list);
4283 if (n_ns<=n_authorities/2) {
4284 log_info(LD_DIR,
4285 "We have %d of %d network statuses, and we want "
4286 "more than %d.", n_ns, n_authorities, n_authorities/2);
4287 res = 0;
4288 goto done;
4290 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
4291 tot += routerstatus_count_usable_entries(ns->entries));
4292 avg = tot / n_ns;
4293 if (!routerstatus_list)
4294 routerstatus_list = smartlist_create();
4295 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
4297 if (rs->status.is_running)
4298 num_running++;
4300 res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
4301 done:
4302 if (res && !have_min_dir_info) {
4303 log(LOG_NOTICE, LD_DIR,
4304 "We now have enough directory information to build circuits.");
4305 control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
4307 if (!res && have_min_dir_info) {
4308 log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
4309 "enough to build circuits.%s",
4310 num_running > 2 ? "" : " (Not enough servers seem reachable -- "
4311 "is your network connection down?)");
4312 control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
4314 have_min_dir_info = res;
4317 /** Return true iff we have downloaded, or attempted to download at least
4318 * n_failures times, a network status for each authority. */
4319 static int
4320 have_tried_downloading_all_statuses(int n_failures)
4322 if (!trusted_dir_servers)
4323 return 0;
4325 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
4327 if (!ds->is_v2_authority)
4328 continue;
4329 /* If we don't have the status, and we haven't failed to get the status,
4330 * we haven't tried to get the status. */
4331 if (!networkstatus_get_by_digest(ds->digest) &&
4332 ds->n_networkstatus_failures <= n_failures)
4333 return 0;
4336 return 1;
4339 /** Reset the descriptor download failure count on all routers, so that we
4340 * can retry any long-failed routers immediately.
4342 void
4343 router_reset_descriptor_download_failures(void)
4345 if (!routerstatus_list)
4346 return;
4347 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
4349 rs->n_download_failures = 0;
4350 rs->next_attempt_at = 0;
4352 tor_assert(networkstatus_list);
4353 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
4354 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
4356 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
4357 rs->need_to_mirror = 1;
4358 }));
4359 last_routerdesc_download_attempted = 0;
4362 /** Any changes in a router descriptor's publication time larger than this are
4363 * automatically non-cosmetic. */
4364 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4366 /** We allow uptime to vary from how much it ought to be by this much. */
4367 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4369 /** Return true iff the only differences between r1 and r2 are such that
4370 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4373 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
4375 time_t r1pub, r2pub;
4376 int time_difference;
4377 tor_assert(r1 && r2);
4379 /* r1 should be the one that was published first. */
4380 if (r1->cache_info.published_on > r2->cache_info.published_on) {
4381 routerinfo_t *ri_tmp = r2;
4382 r2 = r1;
4383 r1 = ri_tmp;
4386 /* If any key fields differ, they're different. */
4387 if (strcasecmp(r1->address, r2->address) ||
4388 strcasecmp(r1->nickname, r2->nickname) ||
4389 r1->or_port != r2->or_port ||
4390 r1->dir_port != r2->dir_port ||
4391 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
4392 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
4393 strcasecmp(r1->platform, r2->platform) ||
4394 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
4395 (!r1->contact_info && r2->contact_info) ||
4396 (r1->contact_info && r2->contact_info &&
4397 strcasecmp(r1->contact_info, r2->contact_info)) ||
4398 r1->is_hibernating != r2->is_hibernating ||
4399 r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
4400 cmp_addr_policies(r1->exit_policy, r2->exit_policy))
4401 return 0;
4402 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
4403 return 0;
4404 if (r1->declared_family && r2->declared_family) {
4405 int i, n;
4406 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
4407 return 0;
4408 n = smartlist_len(r1->declared_family);
4409 for (i=0; i < n; ++i) {
4410 if (strcasecmp(smartlist_get(r1->declared_family, i),
4411 smartlist_get(r2->declared_family, i)))
4412 return 0;
4416 /* Did bandwidth change a lot? */
4417 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
4418 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
4419 return 0;
4421 /* Did more than 12 hours pass? */
4422 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4423 < r2->cache_info.published_on)
4424 return 0;
4426 /* Did uptime fail to increase by approximately the amount we would think,
4427 * give or take some slop? */
4428 r1pub = r1->cache_info.published_on;
4429 r2pub = r2->cache_info.published_on;
4430 time_difference = abs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
4431 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
4432 time_difference > r1->uptime * .05 &&
4433 time_difference > r2->uptime * .05)
4434 return 0;
4436 /* Otherwise, the difference is cosmetic. */
4437 return 1;
4440 /** Generate networkstatus lines for a single routerstatus_t object, and
4441 * return the result in a newly allocated string. Used only by controller
4442 * interface (for now.) */
4443 /* XXXX This should eventually merge into generate_v2_networkstatus() */
4444 char *
4445 networkstatus_getinfo_helper_single(routerstatus_t *rs)
4447 char buf[192];
4448 int r;
4449 struct in_addr in;
4451 int f_authority;
4452 char published[ISO_TIME_LEN+1];
4453 char ipaddr[INET_NTOA_BUF_LEN];
4454 char identity64[BASE64_DIGEST_LEN+1];
4455 char digest64[BASE64_DIGEST_LEN+1];
4457 format_iso_time(published, rs->published_on);
4458 digest_to_base64(identity64, rs->identity_digest);
4459 digest_to_base64(digest64, rs->descriptor_digest);
4460 in.s_addr = htonl(rs->addr);
4461 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
4463 f_authority = router_digest_is_trusted_dir(rs->identity_digest);
4465 r = tor_snprintf(buf, sizeof(buf),
4466 "r %s %s %s %s %s %d %d\n"
4467 "s%s%s%s%s%s%s%s%s%s%s\n",
4468 rs->nickname,
4469 identity64,
4470 digest64,
4471 published,
4472 ipaddr,
4473 (int)rs->or_port,
4474 (int)rs->dir_port,
4476 f_authority?" Authority":"",
4477 rs->is_bad_exit?" BadExit":"",
4478 rs->is_exit?" Exit":"",
4479 rs->is_fast?" Fast":"",
4480 rs->is_possible_guard?" Guard":"",
4481 rs->is_named?" Named":"",
4482 rs->is_stable?" Stable":"",
4483 rs->is_running?" Running":"",
4484 rs->is_valid?" Valid":"",
4485 rs->is_v2_dir?" V2Dir":"");
4486 if (r<0)
4487 log_warn(LD_BUG, "Not enough space in buffer.");
4489 return tor_strdup(buf);
4492 /** If <b>question</b> is a string beginning with "ns/" in a format the
4493 * control interface expects for a GETINFO question, set *<b>answer</b> to a
4494 * newly-allocated string containing networkstatus lines for the appropriate
4495 * ORs. Return 0 on success, -1 on unrecognized question format. */
4497 getinfo_helper_networkstatus(control_connection_t *conn,
4498 const char *question, char **answer)
4500 local_routerstatus_t *status;
4501 (void) conn;
4503 if (!routerstatus_list) {
4504 *answer = tor_strdup("");
4505 return 0;
4508 if (!strcmp(question, "ns/all")) {
4509 smartlist_t *statuses = smartlist_create();
4510 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
4512 routerstatus_t *rs = &(lrs->status);
4513 smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
4515 *answer = smartlist_join_strings(statuses, "", 0, NULL);
4516 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
4517 smartlist_free(statuses);
4518 return 0;
4519 } else if (!strcmpstart(question, "ns/id/")) {
4520 char d[DIGEST_LEN];
4522 if (base16_decode(d, DIGEST_LEN, question+6, strlen(question+6)))
4523 return -1;
4524 status = router_get_combined_status_by_digest(d);
4525 } else if (!strcmpstart(question, "ns/name/")) {
4526 status = router_get_combined_status_by_nickname(question+8, 0);
4527 } else {
4528 return -1;
4531 if (status) {
4532 *answer = networkstatus_getinfo_helper_single(&status->status);
4534 return 0;
4537 /** Assert that the internal representation of <b>rl</b> is
4538 * self-consistent. */
4539 static void
4540 routerlist_assert_ok(routerlist_t *rl)
4542 digestmap_iter_t *iter;
4543 routerinfo_t *r2;
4544 signed_descriptor_t *sd2;
4545 if (!rl)
4546 return;
4547 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
4549 r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
4550 tor_assert(r == r2);
4551 sd2 = digestmap_get(rl->desc_digest_map,
4552 r->cache_info.signed_descriptor_digest);
4553 tor_assert(&(r->cache_info) == sd2);
4554 tor_assert(r->routerlist_index == r_sl_idx);
4556 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
4558 r2 = digestmap_get(rl->identity_map, sd->identity_digest);
4559 tor_assert(sd != &(r2->cache_info));
4560 sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
4561 tor_assert(sd == sd2);
4563 iter = digestmap_iter_init(rl->identity_map);
4564 while (!digestmap_iter_done(iter)) {
4565 const char *d;
4566 void *_r;
4567 routerinfo_t *r;
4568 digestmap_iter_get(iter, &d, &_r);
4569 r = _r;
4570 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
4571 iter = digestmap_iter_next(rl->identity_map, iter);
4573 iter = digestmap_iter_init(rl->desc_digest_map);
4574 while (!digestmap_iter_done(iter)) {
4575 const char *d;
4576 void *_sd;
4577 signed_descriptor_t *sd;
4578 digestmap_iter_get(iter, &d, &_sd);
4579 sd = _sd;
4580 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
4581 iter = digestmap_iter_next(rl->desc_digest_map, iter);
4585 /** Allocate and return a new string representing the contact info
4586 * and platform string for <b>router</b>,
4587 * surrounded by quotes and using standard C escapes.
4589 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4590 * thread. Also, each call invalidates the last-returned value, so don't
4591 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4593 const char *
4594 esc_router_info(routerinfo_t *router)
4596 static char *info;
4597 char *esc_contact, *esc_platform;
4598 size_t len;
4599 if (info)
4600 tor_free(info);
4602 esc_contact = esc_for_log(router->contact_info);
4603 esc_platform = esc_for_log(router->platform);
4605 len = strlen(esc_contact)+strlen(esc_platform)+32;
4606 info = tor_malloc(len);
4607 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
4608 esc_platform);
4609 tor_free(esc_contact);
4610 tor_free(esc_platform);
4612 return info;