Add some "to-be-safe" escaped() wrappers to log statements in rend*.c, though I am...
[tor.git] / src / or / router.c
blobe15cc73e2cd1320681c3a670f7ddf0d74f4bd8bf
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char router_c_id[] =
7 "$Id$";
9 #include "or.h"
11 /**
12 * \file router.c
13 * \brief OR functionality, including key maintenance, generating
14 * and uploading server descriptors, retrying OR connections.
15 **/
17 extern long stats_n_seconds_working;
19 /* Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
21 /************************************************************/
23 /*****
24 * Key management: ORs only.
25 *****/
27 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
29 static tor_mutex_t *key_lock=NULL;
30 static time_t onionkey_set_at=0; /* When was onionkey last changed? */
31 static crypto_pk_env_t *onionkey=NULL;
32 static crypto_pk_env_t *lastonionkey=NULL;
33 static crypto_pk_env_t *identitykey=NULL;
35 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
36 * to update onionkey correctly, call rotate_onion_key().
38 void
39 set_onion_key(crypto_pk_env_t *k)
41 tor_mutex_acquire(key_lock);
42 onionkey = k;
43 onionkey_set_at = time(NULL);
44 tor_mutex_release(key_lock);
45 mark_my_descriptor_dirty();
48 /** Return the current onion key. Requires that the onion key has been
49 * loaded or generated. */
50 crypto_pk_env_t *
51 get_onion_key(void)
53 tor_assert(onionkey);
54 return onionkey;
57 /** Store a copy of the current onion key into *<b>key</b>, and a copy
58 * of the most recent onion key into *<b>last</b>.
60 void
61 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
63 tor_assert(key);
64 tor_assert(last);
65 tor_mutex_acquire(key_lock);
66 tor_assert(onionkey);
67 *key = crypto_pk_dup_key(onionkey);
68 if (lastonionkey)
69 *last = crypto_pk_dup_key(lastonionkey);
70 else
71 *last = NULL;
72 tor_mutex_release(key_lock);
75 /** Return the time when the onion key was last set. This is either the time
76 * when the process launched, or the time of the most recent key rotation since
77 * the process launched.
79 time_t
80 get_onion_key_set_at(void)
82 return onionkey_set_at;
85 /** Set the current identity key to k.
87 void
88 set_identity_key(crypto_pk_env_t *k)
90 if (identitykey)
91 crypto_free_pk_env(identitykey);
92 identitykey = k;
95 /** Returns the current identity key; requires that the identity key has been
96 * set.
98 crypto_pk_env_t *
99 get_identity_key(void)
101 tor_assert(identitykey);
102 return identitykey;
105 /** Return true iff the identity key has been set. */
107 identity_key_is_set(void)
109 return identitykey != NULL;
112 /** Replace the previous onion key with the current onion key, and generate
113 * a new previous onion key. Immediately after calling this function,
114 * the OR should:
115 * - schedule all previous cpuworkers to shut down _after_ processing
116 * pending work. (This will cause fresh cpuworkers to be generated.)
117 * - generate and upload a fresh routerinfo.
119 void
120 rotate_onion_key(void)
122 char fname[512];
123 char fname_prev[512];
124 crypto_pk_env_t *prkey;
125 tor_snprintf(fname,sizeof(fname),
126 "%s/keys/secret_onion_key",get_options()->DataDirectory);
127 tor_snprintf(fname_prev,sizeof(fname_prev),
128 "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
129 if (!(prkey = crypto_new_pk_env())) {
130 log_err(LD_GENERAL,"Error creating crypto environment.");
131 goto error;
133 if (crypto_pk_generate_key(prkey)) {
134 log_err(LD_BUG,"Error generating onion key");
135 goto error;
137 if (file_status(fname) == FN_FILE) {
138 if (replace_file(fname, fname_prev))
139 goto error;
141 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
142 log_err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
143 goto error;
145 log_info(LD_GENERAL, "Rotating onion key");
146 tor_mutex_acquire(key_lock);
147 if (lastonionkey)
148 crypto_free_pk_env(lastonionkey);
149 lastonionkey = onionkey;
150 onionkey = prkey;
151 onionkey_set_at = time(NULL);
152 tor_mutex_release(key_lock);
153 mark_my_descriptor_dirty();
154 return;
155 error:
156 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
159 /* Read an RSA secret key key from a file that was once named fname_old,
160 * but is now named fname_new. Rename the file from old to new as needed.
162 static crypto_pk_env_t *
163 init_key_from_file_name_changed(const char *fname_old,
164 const char *fname_new)
166 if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
167 /* The new filename is there, or both are, or neither is. */
168 return init_key_from_file(fname_new);
170 /* The old filename exists, and the new one doesn't. Rename and load. */
171 if (rename(fname_old, fname_new) < 0) {
172 log_warn(LD_FS, "Couldn't rename \"%s\" to \"%s\": %s",
173 fname_old, fname_new, strerror(errno));
174 return NULL;
176 return init_key_from_file(fname_new);
179 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
180 * create a new RSA key and save it in <b>fname</b>. Return the read/created
181 * key, or NULL on error.
183 crypto_pk_env_t *
184 init_key_from_file(const char *fname)
186 crypto_pk_env_t *prkey = NULL;
187 FILE *file = NULL;
189 if (!(prkey = crypto_new_pk_env())) {
190 log_err(LD_GENERAL,"Error creating crypto environment.");
191 goto error;
194 switch (file_status(fname)) {
195 case FN_DIR:
196 case FN_ERROR:
197 log_err(LD_FS,"Can't read key from \"%s\"", fname);
198 goto error;
199 case FN_NOENT:
200 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
201 fname);
202 if (crypto_pk_generate_key(prkey)) {
203 log_err(LD_GENERAL,"Error generating onion key");
204 goto error;
206 if (crypto_pk_check_key(prkey) <= 0) {
207 log_err(LD_GENERAL,"Generated key seems invalid");
208 goto error;
210 log_info(LD_GENERAL, "Generated key seems valid");
211 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
212 log_err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
213 goto error;
215 return prkey;
216 case FN_FILE:
217 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
218 log_err(LD_GENERAL,"Error loading private key.");
219 goto error;
221 return prkey;
222 default:
223 tor_assert(0);
226 error:
227 if (prkey)
228 crypto_free_pk_env(prkey);
229 if (file)
230 fclose(file);
231 return NULL;
234 /** Initialize all OR private keys, and the TLS context, as necessary.
235 * On OPs, this only initializes the tls context.
238 init_keys(void)
240 /* XXX009 Two problems with how this is called:
241 * 1. It should be idempotent for servers, so we can call init_keys
242 * as much as we need to.
244 char keydir[512];
245 char keydir2[512];
246 char fingerprint[FINGERPRINT_LEN+1];
247 /*nickname fp\n\0 */
248 char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
249 char *cp;
250 const char *mydesc, *datadir;
251 crypto_pk_env_t *prkey;
252 char digest[20];
253 or_options_t *options = get_options();
255 if (!key_lock)
256 key_lock = tor_mutex_new();
258 /* OP's don't need persistent keys; just make up an identity and
259 * initialize the TLS context. */
260 if (!server_mode(options)) {
261 if (!(prkey = crypto_new_pk_env()))
262 return -1;
263 if (crypto_pk_generate_key(prkey))
264 return -1;
265 set_identity_key(prkey);
266 /* Create a TLS context; default the client nickname to "client". */
267 if (tor_tls_context_new(get_identity_key(), 1,
268 options->Nickname ? options->Nickname : "client",
269 MAX_SSL_KEY_LIFETIME) < 0) {
270 log_err(LD_GENERAL,"Error creating TLS context for OP.");
271 return -1;
273 return 0;
275 /* Make sure DataDirectory exists, and is private. */
276 datadir = options->DataDirectory;
277 if (check_private_dir(datadir, CPD_CREATE)) {
278 return -1;
280 /* Check the key directory. */
281 tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
282 if (check_private_dir(keydir, CPD_CREATE)) {
283 return -1;
285 cp = keydir + strlen(keydir); /* End of string. */
287 /* 1. Read identity key. Make it if none is found. */
288 tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
289 tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
290 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir2);
291 prkey = init_key_from_file_name_changed(keydir,keydir2);
292 if (!prkey) return -1;
293 set_identity_key(prkey);
294 /* 2. Read onion key. Make it if none is found. */
295 tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
296 tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
297 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir2);
298 prkey = init_key_from_file_name_changed(keydir,keydir2);
299 if (!prkey) return -1;
300 set_onion_key(prkey);
301 tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
302 if (file_status(keydir) == FN_FILE) {
303 prkey = init_key_from_file(keydir);
304 if (prkey)
305 lastonionkey = prkey;
308 /* 3. Initialize link key and TLS context. */
309 if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
310 MAX_SSL_KEY_LIFETIME) < 0) {
311 log_err(LD_GENERAL,"Error initializing TLS context");
312 return -1;
314 /* 4. Dump router descriptor to 'router.desc' */
315 /* Must be called after keys are initialized. */
316 mydesc = router_get_my_descriptor();
317 if (!mydesc) {
318 log_err(LD_GENERAL,"Error initializing descriptor.");
319 return -1;
321 if (authdir_mode(options)) {
322 const char *m;
323 /* We need to add our own fingerprint so it gets recognized. */
324 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
325 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
326 return -1;
328 if (dirserv_add_descriptor(mydesc, &m) < 0) {
329 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
330 m?m:"<unknown error>");
331 return -1;
335 tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
336 log_info(LD_GENERAL,"Dumping descriptor to \"%s\"...",keydir);
337 if (write_str_to_file(keydir, mydesc,0)) {
338 return -1;
340 /* 5. Dump fingerprint to 'fingerprint' */
341 tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
342 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
343 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
344 log_err(LD_GENERAL,"Error computing fingerprint");
345 return -1;
347 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
348 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
349 "%s %s\n",options->Nickname, fingerprint) < 0) {
350 log_err(LD_GENERAL,"Error writing fingerprint line");
351 return -1;
353 if (write_str_to_file(keydir, fingerprint_line, 0)) {
354 log_err(LD_FS, "Error writing fingerprint line to file");
355 return -1;
357 if (!authdir_mode(options))
358 return 0;
359 /* 6. [authdirserver only] load approved-routers file */
360 tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
361 log_info(LD_DIRSERV,"Loading approved fingerprints from \"%s\"...",keydir);
362 if (dirserv_parse_fingerprint_file(keydir) < 0) {
363 log_err(LD_GENERAL,"Error loading fingerprints");
364 return -1;
366 /* 6b. [authdirserver only] add own key to approved directories. */
367 crypto_pk_get_digest(get_identity_key(), digest);
368 if (!router_digest_is_trusted_dir(digest)) {
369 add_trusted_dir_server(options->Nickname, NULL,
370 (uint16_t)options->DirPort, digest,
371 options->V1AuthoritativeDir);
373 /* success */
374 return 0;
377 /* Keep track of whether we should upload our server descriptor,
378 * and what type of server we are.
381 /** Whether we can reach our ORPort from the outside. */
382 static int can_reach_or_port = 0;
383 /** Whether we can reach our DirPort from the outside. */
384 static int can_reach_dir_port = 0;
386 /** Return 1 if or port is known reachable; else return 0. */
388 check_whether_orport_reachable(void)
390 or_options_t *options = get_options();
391 return clique_mode(options) ||
392 options->AssumeReachable ||
393 can_reach_or_port;
396 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
398 check_whether_dirport_reachable(void)
400 or_options_t *options = get_options();
401 return !options->DirPort ||
402 options->AssumeReachable ||
403 we_are_hibernating() ||
404 can_reach_dir_port;
407 /** Look at a variety of factors, and return 0 if we don't want to
408 * advertise the fact that we have a DirPort open. Else return the
409 * DirPort we want to advertise. */
410 static int
411 decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
413 if (!router->dir_port) /* short circuit the rest of the function */
414 return 0;
415 if (authdir_mode(options)) /* always publish */
416 return router->dir_port;
417 if (we_are_hibernating())
418 return 0;
419 if (!check_whether_dirport_reachable())
420 return 0;
421 if (router->bandwidthcapacity >= router->bandwidthrate) {
422 /* check if we might potentially hibernate. */
423 if (options->AccountingMax != 0)
424 return 0;
425 /* also check if we're advertising a small amount, and have
426 a "boring" DirPort. */
427 if (router->bandwidthrate < 50000 && router->dir_port > 1024)
428 return 0;
431 /* Sounds like a great idea. Let's publish it. */
432 return router->dir_port;
435 /** Some time has passed, or we just got new directory information.
436 * See if we currently believe our ORPort or DirPort to be
437 * unreachable. If so, launch a new test for it.
439 * For ORPort, we simply try making a circuit that ends at ourselves.
440 * Success is noticed in onionskin_answer().
442 * For DirPort, we make a connection via Tor to our DirPort and ask
443 * for our own server descriptor.
444 * Success is noticed in connection_dir_client_reached_eof().
446 void
447 consider_testing_reachability(void)
449 routerinfo_t *me = router_get_my_routerinfo();
450 if (!me) {
451 log_warn(LD_BUG,
452 "Bug: router_get_my_routerinfo() did not find my routerinfo?");
453 return;
456 if (!check_whether_orport_reachable()) {
457 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
460 if (!check_whether_dirport_reachable()) {
461 /* ask myself, via tor, for my server descriptor. */
462 directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
463 1, "authority", NULL, 0);
467 /** Annotate that we found our ORPort reachable. */
468 void
469 router_orport_found_reachable(void)
471 if (!can_reach_or_port) {
472 if (!clique_mode(get_options()))
473 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
474 "the outside. Excellent.%s",
475 get_options()->PublishServerDescriptor ?
476 " Publishing server descriptor." : "");
477 can_reach_or_port = 1;
478 mark_my_descriptor_dirty();
479 consider_publishable_server(time(NULL), 1);
483 /** Annotate that we found our DirPort reachable. */
484 void
485 router_dirport_found_reachable(void)
487 if (!can_reach_dir_port) {
488 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
489 "from the outside. Excellent.");
490 can_reach_dir_port = 1;
494 /** Our router has just moved to a new IP. Reset stats. */
495 void
496 server_has_changed_ip(void)
498 stats_n_seconds_working = 0;
499 can_reach_or_port = 0;
500 can_reach_dir_port = 0;
501 mark_my_descriptor_dirty();
504 /** Return true iff we believe ourselves to be an authoritative
505 * directory server.
508 authdir_mode(or_options_t *options)
510 return options->AuthoritativeDir != 0;
512 /** Return true iff we try to stay connected to all ORs at once.
515 clique_mode(or_options_t *options)
517 return authdir_mode(options);
520 /** Return true iff we are trying to be a server.
523 server_mode(or_options_t *options)
525 if (options->ClientOnly) return 0;
526 return (options->ORPort != 0 || options->ORListenAddress);
529 /** Remember if we've advertised ourselves to the dirservers. */
530 static int server_is_advertised=0;
532 /** Return true iff we have published our descriptor lately.
535 advertised_server_mode(void)
537 return server_is_advertised;
541 * Called with a boolean: set whether we have recently published our
542 * descriptor.
544 static void
545 set_server_advertised(int s)
547 server_is_advertised = s;
550 /** Return true iff we are trying to be a socks proxy. */
552 proxy_mode(or_options_t *options)
554 return (options->SocksPort != 0 || options->SocksListenAddress);
557 /** Decide if we're a publishable server. We are a publishable server if:
558 * - We don't have the ClientOnly option set
559 * and
560 * - We have the PublishServerDescriptor option set
561 * and
562 * - We have ORPort set
563 * and
564 * - We believe we are reachable from the outside; or
565 * - We have the AuthoritativeDirectory option set.
567 static int
568 decide_if_publishable_server(time_t now)
570 or_options_t *options = get_options();
572 if (options->ClientOnly)
573 return 0;
574 if (!options->PublishServerDescriptor)
575 return 0;
576 if (!server_mode(options))
577 return 0;
578 if (options->AuthoritativeDir)
579 return 1;
581 return check_whether_orport_reachable();
584 /** Initiate server descriptor upload as reasonable (if server is publishable,
585 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
587 * We need to rebuild the descriptor if it's dirty even if we're not
588 * uploading, because our reachability testing *uses* our descriptor to
589 * determine what IP address and ports to test.
591 void
592 consider_publishable_server(time_t now, int force)
594 int rebuilt;
596 if (!server_mode(get_options()))
597 return;
599 rebuilt = router_rebuild_descriptor(0);
600 if (decide_if_publishable_server(now)) {
601 set_server_advertised(1);
602 if (rebuilt == 0)
603 router_upload_dir_desc_to_dirservers(force);
604 } else {
605 set_server_advertised(0);
610 * Clique maintenance
613 /** OR only: if in clique mode, try to open connections to all of the
614 * other ORs we know about. Otherwise, open connections to those we
615 * think are in clique mode.
617 * If <b>testing_reachability</b> is 0, try to open the connections
618 * but only if we don't already have one. If it's 1, then we're an
619 * auth dir server, and we should try to connect regardless of
620 * whether we already have a connection open -- but if <b>try_all</b>
621 * is 0, we want to load balance such that we only try a few connections
622 * per call.
624 * The load balancing is such that if we get called once every ten
625 * seconds, we will cycle through all the tests in 1280 seconds (a
626 * bit over 20 minutes).
628 void
629 router_retry_connections(int testing_reachability, int try_all)
631 time_t now = time(NULL);
632 routerlist_t *rl = router_get_routerlist();
633 or_options_t *options = get_options();
634 static char ctr = 0;
636 tor_assert(server_mode(options));
638 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
639 const char *id_digest = router->cache_info.identity_digest;
640 if (router_is_me(router))
641 continue;
642 if (!clique_mode(options) && !router_is_clique_mode(router))
643 continue;
644 if ((testing_reachability &&
645 (try_all || (((uint8_t)id_digest[0]) % 128) == ctr)) ||
646 (!testing_reachability &&
647 !connection_or_get_by_identity_digest(id_digest))) {
648 log_debug(LD_OR,"%sconnecting to %s at %s:%u.",
649 clique_mode(options) ? "(forced) " : "",
650 router->nickname, router->address, router->or_port);
651 /* Remember when we started trying to determine reachability */
652 if (!router->testing_since)
653 router->testing_since = now;
654 connection_or_connect(router->addr, router->or_port,
655 id_digest);
658 if (testing_reachability && !try_all) /* increment ctr */
659 ctr = (ctr + 1) % 128;
662 /** Return true iff this OR should try to keep connections open to all
663 * other ORs. */
665 router_is_clique_mode(routerinfo_t *router)
667 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
668 return 1;
669 return 0;
673 * OR descriptor generation.
676 /** My routerinfo. */
677 static routerinfo_t *desc_routerinfo = NULL;
678 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
679 * now. */
680 static time_t desc_clean_since = 0;
681 /** Boolean: do we need to regenerate the above? */
682 static int desc_needs_upload = 0;
684 /** OR only: If <b>force</b> is true, or we haven't uploaded this
685 * descriptor successfully yet, try to upload our signed descriptor to
686 * all the directory servers we know about.
688 void
689 router_upload_dir_desc_to_dirservers(int force)
691 const char *s;
693 s = router_get_my_descriptor();
694 if (!s) {
695 log_warn(LD_GENERAL, "No descriptor; skipping upload");
696 return;
698 if (!get_options()->PublishServerDescriptor)
699 return;
700 if (!force && !desc_needs_upload)
701 return;
702 desc_needs_upload = 0;
703 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
706 /** OR only: Check whether my exit policy says to allow connection to
707 * conn. Return 0 if we accept; non-0 if we reject.
710 router_compare_to_my_exit_policy(connection_t *conn)
712 tor_assert(desc_routerinfo);
714 /* make sure it's resolved to something. this way we can't get a
715 'maybe' below. */
716 if (!conn->addr)
717 return -1;
719 return router_compare_addr_to_addr_policy(conn->addr, conn->port,
720 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
723 /** Return true iff I'm a server and <b>digest</b> is equal to
724 * my identity digest. */
726 router_digest_is_me(const char *digest)
728 routerinfo_t *me = router_get_my_routerinfo();
729 if (!me || memcmp(me->cache_info.identity_digest, digest, DIGEST_LEN))
730 return 0;
731 return 1;
734 /** A wrapper around router_digest_is_me(). */
736 router_is_me(routerinfo_t *router)
738 return router_digest_is_me(router->cache_info.identity_digest);
741 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
743 router_fingerprint_is_me(const char *fp)
745 char digest[DIGEST_LEN];
746 if (strlen(fp) == HEX_DIGEST_LEN &&
747 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
748 return router_digest_is_me(digest);
750 return 0;
753 /** Return a routerinfo for this OR, rebuilding a fresh one if
754 * necessary. Return NULL on error, or if called on an OP. */
755 routerinfo_t *
756 router_get_my_routerinfo(void)
758 if (!server_mode(get_options()))
759 return NULL;
761 if (!desc_routerinfo) {
762 if (router_rebuild_descriptor(1))
763 return NULL;
765 return desc_routerinfo;
768 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
769 * one if necessary. Return NULL on error.
771 const char *
772 router_get_my_descriptor(void)
774 const char *body;
775 if (!desc_routerinfo) {
776 if (router_rebuild_descriptor(1))
777 return NULL;
779 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
780 log_debug(LD_GENERAL,"my desc is '%s'", body);
781 return body;
784 /*DOCDOC*/
785 static smartlist_t *warned_nonexistent_family = NULL;
787 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
788 * a fresh routerinfo and signed server descriptor for this OR.
789 * Return 0 on success, -1 on error.
792 router_rebuild_descriptor(int force)
794 routerinfo_t *ri;
795 uint32_t addr;
796 char platform[256];
797 int hibernating = we_are_hibernating();
798 or_options_t *options = get_options();
800 if (desc_clean_since && !force)
801 return 0;
803 if (resolve_my_address(options, &addr, NULL) < 0) {
804 log_warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
805 return -1;
808 ri = tor_malloc_zero(sizeof(routerinfo_t));
809 ri->address = tor_dup_addr(addr);
810 ri->nickname = tor_strdup(options->Nickname);
811 ri->addr = addr;
812 ri->or_port = options->ORPort;
813 ri->dir_port = options->DirPort;
814 ri->cache_info.published_on = time(NULL);
815 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
816 * main thread */
817 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
818 if (crypto_pk_get_digest(ri->identity_pkey,
819 ri->cache_info.identity_digest)<0) {
820 routerinfo_free(ri);
821 return -1;
823 get_platform_str(platform, sizeof(platform));
824 ri->platform = tor_strdup(platform);
825 ri->bandwidthrate = (int)options->BandwidthRate;
826 ri->bandwidthburst = (int)options->BandwidthBurst;
827 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
829 if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
830 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
832 config_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
833 options->ExitPolicyRejectPrivate);
835 if (desc_routerinfo) { /* inherit values */
836 ri->is_verified = desc_routerinfo->is_verified;
837 ri->is_running = desc_routerinfo->is_running;
838 ri->is_named = desc_routerinfo->is_named;
840 if (authdir_mode(options))
841 ri->is_verified = ri->is_named = 1; /* believe in yourself */
842 if (options->MyFamily) {
843 smartlist_t *family;
844 if (!warned_nonexistent_family)
845 warned_nonexistent_family = smartlist_create();
846 family = smartlist_create();
847 ri->declared_family = smartlist_create();
848 smartlist_split_string(family, options->MyFamily, ",",
849 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
850 SMARTLIST_FOREACH(family, char *, name,
852 routerinfo_t *member;
853 if (!strcasecmp(name, options->Nickname))
854 member = ri;
855 else
856 member = router_get_by_nickname(name, 1);
857 if (!member) {
858 if (!smartlist_string_isin(warned_nonexistent_family, name)) {
859 log_warn(LD_CONFIG,
860 "I have no descriptor for the router named \"%s\" "
861 "in my declared family; I'll use the nickname as is, but "
862 "this may confuse clients.", name);
863 smartlist_add(warned_nonexistent_family, tor_strdup(name));
865 smartlist_add(ri->declared_family, name);
866 name = NULL;
867 } else {
868 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
869 fp[0] = '$';
870 base16_encode(fp+1,HEX_DIGEST_LEN+1,
871 member->cache_info.identity_digest, DIGEST_LEN);
872 smartlist_add(ri->declared_family, fp);
873 if (smartlist_string_isin(warned_nonexistent_family, name))
874 smartlist_string_remove(warned_nonexistent_family, name);
876 tor_free(name);
878 smartlist_free(family);
880 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
881 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
882 ri, get_identity_key())<0) {
883 log_warn(LD_BUG, "Couldn't allocate string for descriptor.");
884 return -1;
886 ri->cache_info.signed_descriptor_len =
887 strlen(ri->cache_info.signed_descriptor_body);
888 crypto_digest(ri->cache_info.signed_descriptor_digest,
889 ri->cache_info.signed_descriptor_body,
890 ri->cache_info.signed_descriptor_len);
892 if (desc_routerinfo)
893 routerinfo_free(desc_routerinfo);
894 desc_routerinfo = ri;
896 desc_clean_since = time(NULL);
897 desc_needs_upload = 1;
898 return 0;
901 /** Mark descriptor out of date if it's older than <b>when</b> */
902 void
903 mark_my_descriptor_dirty_if_older_than(time_t when)
905 if (desc_clean_since < when)
906 mark_my_descriptor_dirty();
909 /** Call when the current descriptor is out of date. */
910 void
911 mark_my_descriptor_dirty(void)
913 desc_clean_since = 0;
916 #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
917 /** Check whether bandwidth has changed a lot since the last time we announced
918 * bandwidth. If so, mark our descriptor dirty. */
919 void
920 check_descriptor_bandwidth_changed(time_t now)
922 static time_t last_changed = 0;
923 uint64_t prev, cur;
924 if (!desc_routerinfo)
925 return;
927 prev = desc_routerinfo->bandwidthcapacity;
928 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
929 if ((prev != cur && (!prev || !cur)) ||
930 cur > prev*2 ||
931 cur < prev/2) {
932 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
933 log_info(LD_GENERAL,
934 "Measured bandwidth has changed; rebuilding descriptor.");
935 mark_my_descriptor_dirty();
936 last_changed = now;
941 /** Check whether our own address as defined by the Address configuration
942 * has changed. This is for routers that get their address from a service
943 * like dyndns. If our address has changed, mark our descriptor dirty. */
944 void
945 check_descriptor_ipaddress_changed(time_t now)
947 uint32_t prev, cur;
948 or_options_t *options = get_options();
950 if (!desc_routerinfo)
951 return;
953 prev = desc_routerinfo->addr;
954 if (resolve_my_address(options, &cur, NULL) < 0) {
955 log_warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
956 return;
959 if (prev != cur) {
960 char addrbuf_prev[INET_NTOA_BUF_LEN];
961 char addrbuf_cur[INET_NTOA_BUF_LEN];
962 struct in_addr in_prev;
963 struct in_addr in_cur;
965 in_prev.s_addr = htonl(prev);
966 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
968 in_cur.s_addr = htonl(cur);
969 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
971 log_info(LD_GENERAL,
972 "Our IP Address has changed from %s to %s; "
973 "rebuilding descriptor.",
974 addrbuf_prev, addrbuf_cur);
975 mark_my_descriptor_dirty();
979 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
980 * string describing the version of Tor and the operating system we're
981 * currently running on.
983 void
984 get_platform_str(char *platform, size_t len)
986 tor_snprintf(platform, len, "Tor %s on %s",
987 VERSION, get_uname());
988 return;
991 /* XXX need to audit this thing and count fenceposts. maybe
992 * refactor so we don't have to keep asking if we're
993 * near the end of maxlen?
995 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
997 /** OR only: Given a routerinfo for this router, and an identity key to sign
998 * with, encode the routerinfo as a signed server descriptor and write the
999 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1000 * failure, and the number of bytes used on success.
1003 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1004 crypto_pk_env_t *ident_key)
1006 char *onion_pkey; /* Onion key, PEM-encoded. */
1007 char *identity_pkey; /* Identity key, PEM-encoded. */
1008 char digest[DIGEST_LEN];
1009 char published[ISO_TIME_LEN+1];
1010 char fingerprint[FINGERPRINT_LEN+1];
1011 struct in_addr in;
1012 char addrbuf[INET_NTOA_BUF_LEN];
1013 size_t onion_pkeylen, identity_pkeylen;
1014 size_t written;
1015 int result=0;
1016 addr_policy_t *tmpe;
1017 char *bandwidth_usage;
1018 char *family_line;
1019 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1020 char *s_tmp, *s_dup;
1021 const char *cp;
1022 routerinfo_t *ri_tmp;
1023 #endif
1024 or_options_t *options = get_options();
1026 /* Make sure the identity key matches the one in the routerinfo. */
1027 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1028 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1029 "match router's public key!");
1030 return -1;
1033 /* record our fingerprint, so we can include it in the descriptor */
1034 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1035 log_err(LD_BUG,"Error computing fingerprint");
1036 return -1;
1039 /* PEM-encode the onion key */
1040 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1041 &onion_pkey,&onion_pkeylen)<0) {
1042 log_warn(LD_BUG,"write onion_pkey to string failed!");
1043 return -1;
1046 /* PEM-encode the identity key key */
1047 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1048 &identity_pkey,&identity_pkeylen)<0) {
1049 log_warn(LD_BUG,"write identity_pkey to string failed!");
1050 tor_free(onion_pkey);
1051 return -1;
1054 /* Encode the publication time. */
1055 format_iso_time(published, router->cache_info.published_on);
1057 /* How busy have we been? */
1058 bandwidth_usage = rep_hist_get_bandwidth_lines();
1060 if (router->declared_family && smartlist_len(router->declared_family)) {
1061 size_t n;
1062 char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
1063 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1064 family_line = tor_malloc(n);
1065 tor_snprintf(family_line, n, "family %s\n", s);
1066 tor_free(s);
1067 } else {
1068 family_line = tor_strdup("");
1071 /* Generate the easy portion of the router descriptor. */
1072 result = tor_snprintf(s, maxlen,
1073 "router %s %s %d 0 %d\n"
1074 "platform %s\n"
1075 "published %s\n"
1076 "opt fingerprint %s\n"
1077 "uptime %ld\n"
1078 "bandwidth %d %d %d\n"
1079 "onion-key\n%s"
1080 "signing-key\n%s%s%s%s",
1081 router->nickname,
1082 router->address,
1083 router->or_port,
1084 decide_to_advertise_dirport(options, router),
1085 router->platform,
1086 published,
1087 fingerprint,
1088 stats_n_seconds_working,
1089 (int) router->bandwidthrate,
1090 (int) router->bandwidthburst,
1091 (int) router->bandwidthcapacity,
1092 onion_pkey, identity_pkey,
1093 family_line, bandwidth_usage,
1094 we_are_hibernating() ? "opt hibernating 1\n" : "");
1095 tor_free(family_line);
1096 tor_free(onion_pkey);
1097 tor_free(identity_pkey);
1098 tor_free(bandwidth_usage);
1100 if (result < 0)
1101 return -1;
1102 /* From now on, we use 'written' to remember the current length of 's'. */
1103 written = result;
1105 if (options->ContactInfo && strlen(options->ContactInfo)) {
1106 result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
1107 options->ContactInfo);
1108 if (result<0)
1109 return -1;
1110 written += result;
1113 /* Write the exit policy to the end of 's'. */
1114 for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
1115 /* Write: "accept 1.2.3.4" */
1116 in.s_addr = htonl(tmpe->addr);
1117 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
1118 result = tor_snprintf(s+written, maxlen-written, "%s %s",
1119 tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
1120 tmpe->msk == 0 ? "*" : addrbuf);
1121 if (result < 0)
1122 return -1;
1123 written += result;
1124 if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
1125 int n_bits = addr_mask_get_bits(tmpe->msk);
1126 if (n_bits >= 0) {
1127 if (tor_snprintf(s+written, maxlen-written, "/%d", n_bits)<0)
1128 return -1;
1129 } else {
1130 /* Write "/255.255.0.0" */
1131 in.s_addr = htonl(tmpe->msk);
1132 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
1133 if (tor_snprintf(s+written, maxlen-written, "/%s", addrbuf)<0)
1134 return -1;
1136 written += strlen(s+written);
1138 if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
1139 /* There is no port set; write ":*" */
1140 if (written+4 > maxlen)
1141 return -1;
1142 strlcat(s+written, ":*\n", maxlen-written);
1143 written += 3;
1144 } else if (tmpe->prt_min == tmpe->prt_max) {
1145 /* There is only one port; write ":80". */
1146 result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
1147 if (result<0)
1148 return -1;
1149 written += result;
1150 } else {
1151 /* There is a range of ports; write ":79-80". */
1152 result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n",
1153 tmpe->prt_min, tmpe->prt_max);
1154 if (result<0)
1155 return -1;
1156 written += result;
1158 if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
1159 /* This was a catch-all rule, so future rules are irrelevant. */
1160 break;
1161 } /* end for */
1162 if (written+256 > maxlen) /* Not enough room for signature. */
1163 return -1;
1165 /* Sign the directory */
1166 strlcat(s+written, "router-signature\n", maxlen-written);
1167 written += strlen(s+written);
1168 s[written] = '\0';
1169 if (router_get_router_hash(s, digest) < 0)
1170 return -1;
1172 if (router_append_dirobj_signature(s+written,maxlen-written,
1173 digest,ident_key)<0) {
1174 log_warn(LD_BUG, "Couldn't sign router descriptor");
1175 return -1;
1177 written += strlen(s+written);
1179 if (written+2 > maxlen)
1180 return -1;
1181 /* include a last '\n' */
1182 s[written] = '\n';
1183 s[written+1] = 0;
1185 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1186 cp = s_tmp = s_dup = tor_strdup(s);
1187 ri_tmp = router_parse_entry_from_string(cp, NULL);
1188 if (!ri_tmp) {
1189 log_err(LD_BUG,
1190 "We just generated a router descriptor we can't parse: <<%s>>",
1192 return -1;
1194 tor_free(s_dup);
1195 routerinfo_free(ri_tmp);
1196 #endif
1198 return written+1;
1201 /** Return true iff <b>s</b> is a legally valid server nickname. */
1203 is_legal_nickname(const char *s)
1205 size_t len;
1206 tor_assert(s);
1207 len = strlen(s);
1208 return len > 0 && len <= MAX_NICKNAME_LEN &&
1209 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1212 /** Return true iff <b>s</b> is a legally valid server nickname or
1213 * hex-encoded identity-key digest. */
1215 is_legal_nickname_or_hexdigest(const char *s)
1217 size_t len;
1218 tor_assert(s);
1219 if (*s!='$')
1220 return is_legal_nickname(s);
1222 len = strlen(s);
1223 return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
1226 /** Forget that we have issued any router-related warnings, so that we'll
1227 * warn again if we see the same errors. */
1228 void
1229 router_reset_warnings(void)
1231 if (warned_nonexistent_family) {
1232 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1233 smartlist_clear(warned_nonexistent_family);
1237 /** Release all static resources held in router.c */
1238 void
1239 router_free_all(void)
1241 if (onionkey)
1242 crypto_free_pk_env(onionkey);
1243 if (lastonionkey)
1244 crypto_free_pk_env(lastonionkey);
1245 if (identitykey)
1246 crypto_free_pk_env(identitykey);
1247 if (key_lock)
1248 tor_mutex_free(key_lock);
1249 if (desc_routerinfo)
1250 routerinfo_free(desc_routerinfo);
1251 if (warned_nonexistent_family) {
1252 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1253 smartlist_free(warned_nonexistent_family);