r11824@Kushana: nickm | 2007-01-03 17:15:28 -0500
[tor.git] / src / or / router.c
blobb9b5151b9167906af00208ec9623ceb14e85dc72
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;
34 static char identitykey_digest[DIGEST_LEN];
36 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
37 * to update onionkey correctly, call rotate_onion_key().
39 static void
40 set_onion_key(crypto_pk_env_t *k)
42 tor_mutex_acquire(key_lock);
43 onionkey = k;
44 onionkey_set_at = time(NULL);
45 tor_mutex_release(key_lock);
46 mark_my_descriptor_dirty();
49 /** Return the current onion key. Requires that the onion key has been
50 * loaded or generated. */
51 crypto_pk_env_t *
52 get_onion_key(void)
54 tor_assert(onionkey);
55 return onionkey;
58 /** Store a copy of the current onion key into *<b>key</b>, and a copy
59 * of the most recent onion key into *<b>last</b>.
61 void
62 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
64 tor_assert(key);
65 tor_assert(last);
66 tor_mutex_acquire(key_lock);
67 tor_assert(onionkey);
68 *key = crypto_pk_dup_key(onionkey);
69 if (lastonionkey)
70 *last = crypto_pk_dup_key(lastonionkey);
71 else
72 *last = NULL;
73 tor_mutex_release(key_lock);
76 /** Return the time when the onion key was last set. This is either the time
77 * when the process launched, or the time of the most recent key rotation since
78 * the process launched.
80 time_t
81 get_onion_key_set_at(void)
83 return onionkey_set_at;
86 /** Set the current identity key to k.
88 void
89 set_identity_key(crypto_pk_env_t *k)
91 if (identitykey)
92 crypto_free_pk_env(identitykey);
93 identitykey = k;
94 crypto_pk_get_digest(identitykey, identitykey_digest);
97 /** Returns the current identity key; requires that the identity key has been
98 * set.
100 crypto_pk_env_t *
101 get_identity_key(void)
103 tor_assert(identitykey);
104 return identitykey;
107 /** Return true iff the identity key has been set. */
109 identity_key_is_set(void)
111 return identitykey != NULL;
114 /** Replace the previous onion key with the current onion key, and generate
115 * a new previous onion key. Immediately after calling this function,
116 * the OR should:
117 * - schedule all previous cpuworkers to shut down _after_ processing
118 * pending work. (This will cause fresh cpuworkers to be generated.)
119 * - generate and upload a fresh routerinfo.
121 void
122 rotate_onion_key(void)
124 char fname[512];
125 char fname_prev[512];
126 crypto_pk_env_t *prkey;
127 or_state_t *state = get_or_state();
128 time_t now;
129 tor_snprintf(fname,sizeof(fname),
130 "%s/keys/secret_onion_key",get_options()->DataDirectory);
131 tor_snprintf(fname_prev,sizeof(fname_prev),
132 "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
133 if (!(prkey = crypto_new_pk_env())) {
134 log_err(LD_GENERAL,"Error constructing rotated onion key");
135 goto error;
137 if (crypto_pk_generate_key(prkey)) {
138 log_err(LD_BUG,"Error generating onion key");
139 goto error;
141 if (file_status(fname) == FN_FILE) {
142 if (replace_file(fname, fname_prev))
143 goto error;
145 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
146 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
147 goto error;
149 log_info(LD_GENERAL, "Rotating onion key");
150 tor_mutex_acquire(key_lock);
151 if (lastonionkey)
152 crypto_free_pk_env(lastonionkey);
153 lastonionkey = onionkey;
154 onionkey = prkey;
155 now = time(NULL);
156 state->LastRotatedOnionKey = onionkey_set_at = now;
157 tor_mutex_release(key_lock);
158 mark_my_descriptor_dirty();
159 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
160 return;
161 error:
162 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
165 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
166 * create a new RSA key and save it in <b>fname</b>. Return the read/created
167 * key, or NULL on error.
169 crypto_pk_env_t *
170 init_key_from_file(const char *fname)
172 crypto_pk_env_t *prkey = NULL;
173 FILE *file = NULL;
175 if (!(prkey = crypto_new_pk_env())) {
176 log_err(LD_GENERAL,"Error constructing key");
177 goto error;
180 switch (file_status(fname)) {
181 case FN_DIR:
182 case FN_ERROR:
183 log_err(LD_FS,"Can't read key from \"%s\"", fname);
184 goto error;
185 case FN_NOENT:
186 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
187 fname);
188 if (crypto_pk_generate_key(prkey)) {
189 log_err(LD_GENERAL,"Error generating onion key");
190 goto error;
192 if (crypto_pk_check_key(prkey) <= 0) {
193 log_err(LD_GENERAL,"Generated key seems invalid");
194 goto error;
196 log_info(LD_GENERAL, "Generated key seems valid");
197 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
198 log_err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
199 goto error;
201 return prkey;
202 case FN_FILE:
203 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
204 log_err(LD_GENERAL,"Error loading private key.");
205 goto error;
207 return prkey;
208 default:
209 tor_assert(0);
212 error:
213 if (prkey)
214 crypto_free_pk_env(prkey);
215 if (file)
216 fclose(file);
217 return NULL;
220 /** Initialize all OR private keys, and the TLS context, as necessary.
221 * On OPs, this only initializes the tls context. Return 0 on success,
222 * or -1 if Tor should die.
225 init_keys(void)
227 char keydir[512];
228 char fingerprint[FINGERPRINT_LEN+1];
229 /*nickname<space>fp\n\0 */
230 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
231 const char *mydesc, *datadir;
232 crypto_pk_env_t *prkey;
233 char digest[20];
234 char *cp;
235 or_options_t *options = get_options();
236 or_state_t *state = get_or_state();
238 if (!key_lock)
239 key_lock = tor_mutex_new();
241 /* OP's don't need persistent keys; just make up an identity and
242 * initialize the TLS context. */
243 if (!server_mode(options)) {
244 if (!(prkey = crypto_new_pk_env()))
245 return -1;
246 if (crypto_pk_generate_key(prkey))
247 return -1;
248 set_identity_key(prkey);
249 /* Create a TLS context; default the client nickname to "client". */
250 if (tor_tls_context_new(get_identity_key(),
251 options->Nickname ? options->Nickname : "client",
252 MAX_SSL_KEY_LIFETIME) < 0) {
253 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
254 return -1;
256 return 0;
258 /* Make sure DataDirectory exists, and is private. */
259 datadir = options->DataDirectory;
260 if (check_private_dir(datadir, CPD_CREATE)) {
261 return -1;
263 /* Check the key directory. */
264 tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
265 if (check_private_dir(keydir, CPD_CREATE)) {
266 return -1;
269 /* 1. Read identity key. Make it if none is found. */
270 tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_id_key",datadir);
271 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
272 prkey = init_key_from_file(keydir);
273 if (!prkey) return -1;
274 set_identity_key(prkey);
275 /* 2. Read onion key. Make it if none is found. */
276 tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key",datadir);
277 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
278 prkey = init_key_from_file(keydir);
279 if (!prkey) return -1;
280 set_onion_key(prkey);
281 if (state->LastRotatedOnionKey > 100) { /* allow for some parsing slop. */
282 onionkey_set_at = state->LastRotatedOnionKey;
283 } else {
284 /* We have no LastRotatedOnionKey set; either we just created the key
285 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
286 * start the clock ticking now so that we will eventually rotate it even
287 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
288 state->LastRotatedOnionKey = time(NULL);
289 or_state_mark_dirty(state, options->AvoidDiskWrites ? time(NULL)+3600 : 0);
292 tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
293 if (file_status(keydir) == FN_FILE) {
294 prkey = init_key_from_file(keydir);
295 if (prkey)
296 lastonionkey = prkey;
299 /* 3. Initialize link key and TLS context. */
300 if (tor_tls_context_new(get_identity_key(), options->Nickname,
301 MAX_SSL_KEY_LIFETIME) < 0) {
302 log_err(LD_GENERAL,"Error initializing TLS context");
303 return -1;
305 /* 4. Build our router descriptor. */
306 /* Must be called after keys are initialized. */
307 mydesc = router_get_my_descriptor();
308 if (authdir_mode(options)) {
309 const char *m;
310 /* We need to add our own fingerprint so it gets recognized. */
311 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
312 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
313 return -1;
315 if (!mydesc) {
316 log_err(LD_GENERAL,"Error initializing descriptor.");
317 return -1;
319 if (dirserv_add_descriptor(mydesc, &m) < 0) {
320 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
321 m?m:"<unknown error>");
322 return -1;
326 /* 5. Dump fingerprint to 'fingerprint' */
327 tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
328 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
329 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
330 log_err(LD_GENERAL,"Error computing fingerprint");
331 return -1;
333 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
334 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
335 "%s %s\n",options->Nickname, fingerprint) < 0) {
336 log_err(LD_GENERAL,"Error writing fingerprint line");
337 return -1;
339 /* Check whether we need to write the fingerprint file. */
340 cp = NULL;
341 if (file_status(keydir) == FN_FILE)
342 cp = read_file_to_str(keydir, 0, NULL);
343 if (!cp || strcmp(cp, fingerprint_line)) {
344 if (write_str_to_file(keydir, fingerprint_line, 0)) {
345 log_err(LD_FS, "Error writing fingerprint line to file");
346 return -1;
349 tor_free(cp);
351 log(LOG_NOTICE, LD_GENERAL,
352 "Your Tor server's identity key fingerprint is '%s %s'",
353 options->Nickname, fingerprint);
354 if (!authdir_mode(options))
355 return 0;
356 /* 6. [authdirserver only] load approved-routers file */
357 if (dirserv_load_fingerprint_file() < 0) {
358 log_err(LD_GENERAL,"Error loading fingerprints");
359 return -1;
361 /* 6b. [authdirserver only] add own key to approved directories. */
362 crypto_pk_get_digest(get_identity_key(), digest);
363 if (!router_digest_is_trusted_dir(digest)) {
364 add_trusted_dir_server(options->Nickname, NULL,
365 (uint16_t)options->DirPort,
366 (uint16_t)options->ORPort,
367 digest,
368 options->V1AuthoritativeDir, /* v1 authority */
369 1, /* v2 authority */
370 options->HSAuthoritativeDir /*hidserv authority*/);
372 return 0; /* success */
375 /* Keep track of whether we should upload our server descriptor,
376 * and what type of server we are.
379 /** Whether we can reach our ORPort from the outside. */
380 static int can_reach_or_port = 0;
381 /** Whether we can reach our DirPort from the outside. */
382 static int can_reach_dir_port = 0;
384 /** DOCDOC */
385 void
386 router_reset_reachability(void)
388 can_reach_or_port = can_reach_dir_port = 0;
391 /** Return 1 if ORPort is known reachable; else return 0. */
393 check_whether_orport_reachable(void)
395 or_options_t *options = get_options();
396 return options->AssumeReachable ||
397 can_reach_or_port;
400 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
402 check_whether_dirport_reachable(void)
404 or_options_t *options = get_options();
405 return !options->DirPort ||
406 options->AssumeReachable ||
407 we_are_hibernating() ||
408 can_reach_dir_port;
411 /** Look at a variety of factors, and return 0 if we don't want to
412 * advertise the fact that we have a DirPort open. Else return the
413 * DirPort we want to advertise. */
414 static int
415 decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
417 if (!router->dir_port) /* short circuit the rest of the function */
418 return 0;
419 if (authdir_mode(options)) /* always publish */
420 return router->dir_port;
421 if (we_are_hibernating())
422 return 0;
423 if (!check_whether_dirport_reachable())
424 return 0;
425 /* check if we might potentially hibernate. */
426 if (accounting_is_enabled(options))
427 return 0;
428 /* also check if we're advertising a small amount */
429 if (router->bandwidthrate <= 51200)
430 return 0;
432 /* Sounds like a great idea. Let's publish it. */
433 return router->dir_port;
436 /** Some time has passed, or we just got new directory information.
437 * See if we currently believe our ORPort or DirPort to be
438 * unreachable. If so, launch a new test for it.
440 * For ORPort, we simply try making a circuit that ends at ourselves.
441 * Success is noticed in onionskin_answer().
443 * For DirPort, we make a connection via Tor to our DirPort and ask
444 * for our own server descriptor.
445 * Success is noticed in connection_dir_client_reached_eof().
447 void
448 consider_testing_reachability(int test_or, int test_dir)
450 routerinfo_t *me = router_get_my_routerinfo();
451 int orport_reachable = check_whether_orport_reachable();
452 if (!me)
453 return;
455 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
456 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
457 !orport_reachable ? "reachability" : "bandwidth",
458 me->address, me->or_port);
459 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, 0, me, 0, 1, 1);
460 control_event_server_status(LOG_NOTICE,
461 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
462 me->address, me->or_port);
465 if (test_dir && !check_whether_dirport_reachable() &&
466 !connection_get_by_type_addr_port_purpose(
467 CONN_TYPE_DIR, me->addr, me->dir_port,
468 DIR_PURPOSE_FETCH_SERVERDESC)) {
469 /* ask myself, via tor, for my server descriptor. */
470 directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
471 1, "authority", NULL, 0);
472 control_event_server_status(LOG_NOTICE,
473 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
474 me->address, me->dir_port);
478 /** Annotate that we found our ORPort reachable. */
479 void
480 router_orport_found_reachable(void)
482 if (!can_reach_or_port) {
483 routerinfo_t *me = router_get_my_routerinfo();
484 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
485 "the outside. Excellent.%s",
486 get_options()->PublishServerDescriptor ?
487 " Publishing server descriptor." : "");
488 can_reach_or_port = 1;
489 mark_my_descriptor_dirty();
490 if (!me)
491 return;
492 control_event_server_status(LOG_NOTICE,
493 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
494 me->address, me->dir_port);
498 /** Annotate that we found our DirPort reachable. */
499 void
500 router_dirport_found_reachable(void)
502 if (!can_reach_dir_port) {
503 routerinfo_t *me = router_get_my_routerinfo();
504 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
505 "from the outside. Excellent.");
506 can_reach_dir_port = 1;
507 mark_my_descriptor_dirty();
508 if (!me)
509 return;
510 control_event_server_status(LOG_NOTICE,
511 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
512 me->address, me->dir_port);
516 /** We have enough testing circuits open. Send a bunch of "drop"
517 * cells down each of them, to exercise our bandwidth. */
518 void
519 router_perform_bandwidth_test(int num_circs, time_t now)
521 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
522 int max_cells = num_cells < CIRCWINDOW_START ?
523 num_cells : CIRCWINDOW_START;
524 int cells_per_circuit = max_cells / num_circs;
525 origin_circuit_t *circ = NULL;
527 log_notice(LD_OR,"Performing bandwidth self-test.");
528 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
529 CIRCUIT_PURPOSE_TESTING))) {
530 /* dump cells_per_circuit drop cells onto this circ */
531 int i = cells_per_circuit;
532 if (circ->_base.state != CIRCUIT_STATE_OPEN)
533 continue;
534 circ->_base.timestamp_dirty = now;
535 while (i-- > 0) {
536 if (connection_edge_send_command(NULL, TO_CIRCUIT(circ),
537 RELAY_COMMAND_DROP,
538 NULL, 0, circ->cpath->prev)<0) {
539 return; /* stop if error */
545 /** Return true iff we believe ourselves to be an authoritative
546 * directory server.
549 authdir_mode(or_options_t *options)
551 return options->AuthoritativeDir != 0;
553 /** Return true iff we try to stay connected to all ORs at once.
556 clique_mode(or_options_t *options)
558 return authdir_mode(options);
561 /** Return true iff we are trying to be a server.
564 server_mode(or_options_t *options)
566 if (options->ClientOnly) return 0;
567 return (options->ORPort != 0 || options->ORListenAddress);
570 /** Remember if we've advertised ourselves to the dirservers. */
571 static int server_is_advertised=0;
573 /** Return true iff we have published our descriptor lately.
576 advertised_server_mode(void)
578 return server_is_advertised;
582 * Called with a boolean: set whether we have recently published our
583 * descriptor.
585 static void
586 set_server_advertised(int s)
588 server_is_advertised = s;
591 /** Return true iff we are trying to be a socks proxy. */
593 proxy_mode(or_options_t *options)
595 return (options->SocksPort != 0 || options->SocksListenAddress);
598 /** Decide if we're a publishable server. We are a publishable server if:
599 * - We don't have the ClientOnly option set
600 * and
601 * - We have the PublishServerDescriptor option set
602 * and
603 * - We have ORPort set
604 * and
605 * - We believe we are reachable from the outside; or
606 * - We have the AuthoritativeDirectory option set.
608 static int
609 decide_if_publishable_server(void)
611 or_options_t *options = get_options();
613 if (options->ClientOnly)
614 return 0;
615 if (!options->PublishServerDescriptor)
616 return 0;
617 if (!server_mode(options))
618 return 0;
619 if (options->AuthoritativeDir)
620 return 1;
622 return check_whether_orport_reachable();
625 /** Initiate server descriptor upload as reasonable (if server is publishable,
626 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
628 * We need to rebuild the descriptor if it's dirty even if we're not
629 * uploading, because our reachability testing *uses* our descriptor to
630 * determine what IP address and ports to test.
632 void
633 consider_publishable_server(int force)
635 int rebuilt;
637 if (!server_mode(get_options()))
638 return;
640 rebuilt = router_rebuild_descriptor(0);
641 if (decide_if_publishable_server()) {
642 set_server_advertised(1);
643 if (rebuilt == 0)
644 router_upload_dir_desc_to_dirservers(force);
645 } else {
646 set_server_advertised(0);
651 * Clique maintenance -- to be phased out.
654 /** Return true iff this OR should try to keep connections open to all
655 * other ORs. */
657 router_is_clique_mode(routerinfo_t *router)
659 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
660 return 1;
661 return 0;
665 * OR descriptor generation.
668 /** My routerinfo. */
669 static routerinfo_t *desc_routerinfo = NULL;
670 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
671 * now. */
672 static time_t desc_clean_since = 0;
673 /** Boolean: do we need to regenerate the above? */
674 static int desc_needs_upload = 0;
676 /** OR only: If <b>force</b> is true, or we haven't uploaded this
677 * descriptor successfully yet, try to upload our signed descriptor to
678 * all the directory servers we know about.
680 void
681 router_upload_dir_desc_to_dirservers(int force)
683 const char *s;
685 s = router_get_my_descriptor();
686 if (!s) {
687 log_info(LD_GENERAL, "No descriptor; skipping upload");
688 return;
690 if (!get_options()->PublishServerDescriptor)
691 return;
692 if (!force && !desc_needs_upload)
693 return;
694 desc_needs_upload = 0;
695 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
698 /** OR only: Check whether my exit policy says to allow connection to
699 * conn. Return 0 if we accept; non-0 if we reject.
702 router_compare_to_my_exit_policy(edge_connection_t *conn)
704 tor_assert(desc_routerinfo);
706 /* make sure it's resolved to something. this way we can't get a
707 'maybe' below. */
708 if (!conn->_base.addr)
709 return -1;
711 return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
712 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
715 /** Return true iff I'm a server and <b>digest</b> is equal to
716 * my identity digest. */
718 router_digest_is_me(const char *digest)
720 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
723 /** A wrapper around router_digest_is_me(). */
725 router_is_me(routerinfo_t *router)
727 return router_digest_is_me(router->cache_info.identity_digest);
730 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
732 router_fingerprint_is_me(const char *fp)
734 char digest[DIGEST_LEN];
735 if (strlen(fp) == HEX_DIGEST_LEN &&
736 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
737 return router_digest_is_me(digest);
739 return 0;
742 /** Return a routerinfo for this OR, rebuilding a fresh one if
743 * necessary. Return NULL on error, or if called on an OP. */
744 routerinfo_t *
745 router_get_my_routerinfo(void)
747 if (!server_mode(get_options()))
748 return NULL;
749 if (router_rebuild_descriptor(0))
750 return NULL;
751 return desc_routerinfo;
754 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
755 * one if necessary. Return NULL on error.
757 const char *
758 router_get_my_descriptor(void)
760 const char *body;
761 if (!router_get_my_routerinfo())
762 return NULL;
763 /* Make sure this is nul-terminated. */
764 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
765 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
766 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
767 log_debug(LD_GENERAL,"my desc is '%s'", body);
768 return body;
771 /*DOCDOC*/
772 static smartlist_t *warned_nonexistent_family = NULL;
774 static int router_guess_address_from_dir_headers(uint32_t *guess);
776 /** Return our current best guess at our address, either because
777 * it's configured in torrc, or because we've learned it from
778 * dirserver headers. */
780 router_pick_published_address(or_options_t *options, uint32_t *addr)
782 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
783 log_info(LD_CONFIG, "Could not determine our address locally. "
784 "Checking if directory headers provide any hints.");
785 if (router_guess_address_from_dir_headers(addr) < 0) {
786 log_info(LD_CONFIG, "No hints from directory headers either. "
787 "Will try again later.");
788 return -1;
791 return 0;
794 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
795 * a fresh routerinfo and signed server descriptor for this OR.
796 * Return 0 on success, -1 on temporary error.
799 router_rebuild_descriptor(int force)
801 routerinfo_t *ri;
802 uint32_t addr;
803 char platform[256];
804 int hibernating = we_are_hibernating();
805 or_options_t *options = get_options();
807 if (desc_clean_since && !force)
808 return 0;
810 if (router_pick_published_address(options, &addr) < 0) {
811 /* Stop trying to rebuild our descriptor every second. We'll
812 * learn that it's time to try again when server_has_changed_ip()
813 * marks it dirty. */
814 desc_clean_since = time(NULL);
815 return -1;
818 ri = tor_malloc_zero(sizeof(routerinfo_t));
819 ri->routerlist_index = -1;
820 ri->address = tor_dup_addr(addr);
821 ri->nickname = tor_strdup(options->Nickname);
822 ri->addr = addr;
823 ri->or_port = options->ORPort;
824 ri->dir_port = options->DirPort;
825 ri->cache_info.published_on = time(NULL);
826 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
827 * main thread */
828 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
829 if (crypto_pk_get_digest(ri->identity_pkey,
830 ri->cache_info.identity_digest)<0) {
831 routerinfo_free(ri);
832 return -1;
834 get_platform_str(platform, sizeof(platform));
835 ri->platform = tor_strdup(platform);
836 ri->bandwidthrate = (int)options->BandwidthRate;
837 ri->bandwidthburst = (int)options->BandwidthBurst;
838 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
840 if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
841 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
843 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
844 options->ExitPolicyRejectPrivate);
846 if (desc_routerinfo) { /* inherit values */
847 ri->is_valid = desc_routerinfo->is_valid;
848 ri->is_running = desc_routerinfo->is_running;
849 ri->is_named = desc_routerinfo->is_named;
851 if (authdir_mode(options))
852 ri->is_valid = ri->is_named = 1; /* believe in yourself */
853 if (options->MyFamily) {
854 smartlist_t *family;
855 if (!warned_nonexistent_family)
856 warned_nonexistent_family = smartlist_create();
857 family = smartlist_create();
858 ri->declared_family = smartlist_create();
859 smartlist_split_string(family, options->MyFamily, ",",
860 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
861 SMARTLIST_FOREACH(family, char *, name,
863 routerinfo_t *member;
864 if (!strcasecmp(name, options->Nickname))
865 member = ri;
866 else
867 member = router_get_by_nickname(name, 1);
868 if (!member) {
869 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
870 !is_legal_hexdigest(name)) {
871 log_warn(LD_CONFIG,
872 "I have no descriptor for the router named \"%s\" "
873 "in my declared family; I'll use the nickname as is, but "
874 "this may confuse clients.", name);
875 smartlist_add(warned_nonexistent_family, tor_strdup(name));
877 smartlist_add(ri->declared_family, name);
878 name = NULL;
879 } else if (router_is_me(member)) {
880 /* Don't list ourself in our own family; that's redundant */
881 } else {
882 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
883 fp[0] = '$';
884 base16_encode(fp+1,HEX_DIGEST_LEN+1,
885 member->cache_info.identity_digest, DIGEST_LEN);
886 smartlist_add(ri->declared_family, fp);
887 if (smartlist_string_isin(warned_nonexistent_family, name))
888 smartlist_string_remove(warned_nonexistent_family, name);
890 tor_free(name);
893 /* remove duplicates from the list */
894 smartlist_sort_strings(ri->declared_family);
895 smartlist_uniq_strings(ri->declared_family);
897 smartlist_free(family);
899 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
900 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
901 ri, get_identity_key())<0) {
902 log_warn(LD_BUG, "Couldn't allocate string for descriptor.");
903 return -1;
905 ri->cache_info.signed_descriptor_len =
906 strlen(ri->cache_info.signed_descriptor_body);
907 crypto_digest(ri->cache_info.signed_descriptor_digest,
908 ri->cache_info.signed_descriptor_body,
909 ri->cache_info.signed_descriptor_len);
911 if (desc_routerinfo)
912 routerinfo_free(desc_routerinfo);
913 desc_routerinfo = ri;
915 desc_clean_since = time(NULL);
916 desc_needs_upload = 1;
917 control_event_my_descriptor_changed();
918 return 0;
921 /** Mark descriptor out of date if it's older than <b>when</b> */
922 void
923 mark_my_descriptor_dirty_if_older_than(time_t when)
925 if (desc_clean_since < when)
926 mark_my_descriptor_dirty();
929 /** Call when the current descriptor is out of date. */
930 void
931 mark_my_descriptor_dirty(void)
933 desc_clean_since = 0;
936 /** How frequently will we republish our descriptor because of large (factor
937 * of 2) shifts in estimated bandwidth? */
938 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
940 /** Check whether bandwidth has changed a lot since the last time we announced
941 * bandwidth. If so, mark our descriptor dirty. */
942 void
943 check_descriptor_bandwidth_changed(time_t now)
945 static time_t last_changed = 0;
946 uint64_t prev, cur;
947 if (!desc_routerinfo)
948 return;
950 prev = desc_routerinfo->bandwidthcapacity;
951 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
952 if ((prev != cur && (!prev || !cur)) ||
953 cur > prev*2 ||
954 cur < prev/2) {
955 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
956 log_info(LD_GENERAL,
957 "Measured bandwidth has changed; rebuilding descriptor.");
958 mark_my_descriptor_dirty();
959 last_changed = now;
964 static void
965 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
967 char addrbuf_prev[INET_NTOA_BUF_LEN];
968 char addrbuf_cur[INET_NTOA_BUF_LEN];
969 struct in_addr in_prev;
970 struct in_addr in_cur;
972 in_prev.s_addr = htonl(prev);
973 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
975 in_cur.s_addr = htonl(cur);
976 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
978 if (prev)
979 log_fn(severity, LD_GENERAL,
980 "Our IP Address has changed from %s to %s; "
981 "rebuilding descriptor.",
982 addrbuf_prev, addrbuf_cur);
983 else
984 log_notice(LD_GENERAL,
985 "Guessed our IP address as %s.",
986 addrbuf_cur);
989 /** Check whether our own address as defined by the Address configuration
990 * has changed. This is for routers that get their address from a service
991 * like dyndns. If our address has changed, mark our descriptor dirty. */
992 void
993 check_descriptor_ipaddress_changed(time_t now)
995 uint32_t prev, cur;
996 or_options_t *options = get_options();
997 (void) now;
999 if (!desc_routerinfo)
1000 return;
1002 prev = desc_routerinfo->addr;
1003 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1004 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1005 return;
1008 if (prev != cur) {
1009 log_addr_has_changed(LOG_INFO, prev, cur);
1010 ip_address_changed(0);
1014 static uint32_t last_guessed_ip = 0;
1016 /** A directory authority told us our IP address is <b>suggestion</b>.
1017 * If this address is different from the one we think we are now, and
1018 * if our computer doesn't actually know its IP address, then switch. */
1019 void
1020 router_new_address_suggestion(const char *suggestion)
1022 uint32_t addr, cur = 0;
1023 struct in_addr in;
1024 or_options_t *options = get_options();
1026 /* first, learn what the IP address actually is */
1027 if (!tor_inet_aton(suggestion, &in)) {
1028 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1029 escaped(suggestion));
1030 return;
1032 addr = ntohl(in.s_addr);
1034 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1036 if (!server_mode(options)) {
1037 last_guessed_ip = addr; /* store it in case we need it later */
1038 return;
1041 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1042 /* We're all set -- we already know our address. Great. */
1043 last_guessed_ip = cur; /* store it in case we need it later */
1044 return;
1046 if (is_internal_IP(addr, 0)) {
1047 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1048 return;
1051 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1052 * us an answer different from what we had the last time we managed to
1053 * resolve it. */
1054 if (last_guessed_ip != addr) {
1055 control_event_server_status(LOG_NOTICE,
1056 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1057 suggestion);
1058 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
1059 ip_address_changed(0);
1060 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1064 /** We failed to resolve our address locally, but we'd like to build
1065 * a descriptor and publish / test reachability. If we have a guess
1066 * about our address based on directory headers, answer it and return
1067 * 0; else return -1. */
1068 static int
1069 router_guess_address_from_dir_headers(uint32_t *guess)
1071 if (last_guessed_ip) {
1072 *guess = last_guessed_ip;
1073 return 0;
1075 return -1;
1078 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1079 * string describing the version of Tor and the operating system we're
1080 * currently running on.
1082 void
1083 get_platform_str(char *platform, size_t len)
1085 tor_snprintf(platform, len, "Tor %s on %s",
1086 VERSION, get_uname());
1087 return;
1090 /* XXX need to audit this thing and count fenceposts. maybe
1091 * refactor so we don't have to keep asking if we're
1092 * near the end of maxlen?
1094 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1096 /** OR only: Given a routerinfo for this router, and an identity key to sign
1097 * with, encode the routerinfo as a signed server descriptor and write the
1098 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1099 * failure, and the number of bytes used on success.
1102 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1103 crypto_pk_env_t *ident_key)
1105 char *onion_pkey; /* Onion key, PEM-encoded. */
1106 char *identity_pkey; /* Identity key, PEM-encoded. */
1107 char digest[DIGEST_LEN];
1108 char published[ISO_TIME_LEN+1];
1109 char fingerprint[FINGERPRINT_LEN+1];
1110 size_t onion_pkeylen, identity_pkeylen;
1111 size_t written;
1112 int result=0;
1113 addr_policy_t *tmpe;
1114 char *bandwidth_usage;
1115 char *family_line;
1116 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1117 char *s_dup;
1118 const char *cp;
1119 routerinfo_t *ri_tmp;
1120 #endif
1121 or_options_t *options = get_options();
1123 /* Make sure the identity key matches the one in the routerinfo. */
1124 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1125 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1126 "match router's public key!");
1127 return -1;
1130 /* record our fingerprint, so we can include it in the descriptor */
1131 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1132 log_err(LD_BUG,"Error computing fingerprint");
1133 return -1;
1136 /* PEM-encode the onion key */
1137 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1138 &onion_pkey,&onion_pkeylen)<0) {
1139 log_warn(LD_BUG,"write onion_pkey to string failed!");
1140 return -1;
1143 /* PEM-encode the identity key key */
1144 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1145 &identity_pkey,&identity_pkeylen)<0) {
1146 log_warn(LD_BUG,"write identity_pkey to string failed!");
1147 tor_free(onion_pkey);
1148 return -1;
1151 /* Encode the publication time. */
1152 format_iso_time(published, router->cache_info.published_on);
1154 /* How busy have we been? */
1155 bandwidth_usage = rep_hist_get_bandwidth_lines();
1157 if (router->declared_family && smartlist_len(router->declared_family)) {
1158 size_t n;
1159 char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
1160 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1161 family_line = tor_malloc(n);
1162 tor_snprintf(family_line, n, "family %s\n", s);
1163 tor_free(s);
1164 } else {
1165 family_line = tor_strdup("");
1168 /* Generate the easy portion of the router descriptor. */
1169 result = tor_snprintf(s, maxlen,
1170 "router %s %s %d 0 %d\n"
1171 "platform %s\n"
1172 "published %s\n"
1173 "opt fingerprint %s\n"
1174 "uptime %ld\n"
1175 "bandwidth %d %d %d\n"
1176 "onion-key\n%s"
1177 "signing-key\n%s"
1178 #ifndef USE_EVENTDNS
1179 "opt eventdns 0\n"
1180 #endif
1181 "%s%s%s",
1182 router->nickname,
1183 router->address,
1184 router->or_port,
1185 decide_to_advertise_dirport(options, router),
1186 router->platform,
1187 published,
1188 fingerprint,
1189 stats_n_seconds_working,
1190 (int) router->bandwidthrate,
1191 (int) router->bandwidthburst,
1192 (int) router->bandwidthcapacity,
1193 onion_pkey, identity_pkey,
1194 family_line, bandwidth_usage,
1195 we_are_hibernating() ? "opt hibernating 1\n" : "");
1196 tor_free(family_line);
1197 tor_free(onion_pkey);
1198 tor_free(identity_pkey);
1199 tor_free(bandwidth_usage);
1201 if (result < 0)
1202 return -1;
1203 /* From now on, we use 'written' to remember the current length of 's'. */
1204 written = result;
1206 if (options->ContactInfo && strlen(options->ContactInfo)) {
1207 result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
1208 options->ContactInfo);
1209 if (result<0)
1210 return -1;
1211 written += result;
1214 /* Write the exit policy to the end of 's'. */
1215 tmpe = router->exit_policy;
1216 if (dns_seems_to_be_broken()) {
1217 /* DNS is screwed up; don't claim to be an exit. */
1218 strlcat(s+written, "reject *:*\n", maxlen-written);
1219 written += strlen("reject *:*\n");
1220 tmpe = NULL;
1222 for ( ; tmpe; tmpe=tmpe->next) {
1223 result = policy_write_item(s+written, maxlen-written, tmpe);
1224 if (result < 0)
1225 return -1;
1226 tor_assert(result == (int)strlen(s+written));
1227 written += result;
1228 if (written+2 > maxlen)
1229 return -1;
1230 s[written++] = '\n';
1233 if (written+256 > maxlen) /* Not enough room for signature. */
1234 return -1;
1236 /* Sign the directory */
1237 strlcpy(s+written, "router-signature\n", maxlen-written);
1238 written += strlen(s+written);
1239 s[written] = '\0';
1240 if (router_get_router_hash(s, digest) < 0)
1241 return -1;
1243 note_crypto_pk_op(SIGN_RTR);
1244 if (router_append_dirobj_signature(s+written,maxlen-written,
1245 digest,ident_key)<0) {
1246 log_warn(LD_BUG, "Couldn't sign router descriptor");
1247 return -1;
1249 written += strlen(s+written);
1251 if (written+2 > maxlen)
1252 return -1;
1253 /* include a last '\n' */
1254 s[written] = '\n';
1255 s[written+1] = 0;
1257 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1258 cp = s_dup = tor_strdup(s);
1259 ri_tmp = router_parse_entry_from_string(cp, NULL, 1);
1260 if (!ri_tmp) {
1261 log_err(LD_BUG,
1262 "We just generated a router descriptor we can't parse: <<%s>>",
1264 return -1;
1266 tor_free(s_dup);
1267 routerinfo_free(ri_tmp);
1268 #endif
1270 return written+1;
1273 /** Return true iff <b>s</b> is a legally valid server nickname. */
1275 is_legal_nickname(const char *s)
1277 size_t len;
1278 tor_assert(s);
1279 len = strlen(s);
1280 return len > 0 && len <= MAX_NICKNAME_LEN &&
1281 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1284 /** Return true iff <b>s</b> is a legally valid server nickname or
1285 * hex-encoded identity-key digest. */
1287 is_legal_nickname_or_hexdigest(const char *s)
1289 if (*s!='$')
1290 return is_legal_nickname(s);
1291 else
1292 return is_legal_hexdigest(s);
1295 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1296 * digest. */
1298 is_legal_hexdigest(const char *s)
1300 size_t len;
1301 tor_assert(s);
1302 if (s[0] == '$') s++;
1303 len = strlen(s);
1304 if (len > HEX_DIGEST_LEN) {
1305 if (s[HEX_DIGEST_LEN] == '=' ||
1306 s[HEX_DIGEST_LEN] == '~') {
1307 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1308 return 0;
1309 } else {
1310 return 0;
1313 return (len >= HEX_DIGEST_LEN &&
1314 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1317 /** DOCDOC buf must have MAX_VERBOSE_NICKNAME_LEN+1 bytes. */
1318 void
1319 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1321 buf[0] = '$';
1322 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1323 DIGEST_LEN);
1324 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1325 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1328 /** Forget that we have issued any router-related warnings, so that we'll
1329 * warn again if we see the same errors. */
1330 void
1331 router_reset_warnings(void)
1333 if (warned_nonexistent_family) {
1334 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1335 smartlist_clear(warned_nonexistent_family);
1339 /** Release all static resources held in router.c */
1340 void
1341 router_free_all(void)
1343 if (onionkey)
1344 crypto_free_pk_env(onionkey);
1345 if (lastonionkey)
1346 crypto_free_pk_env(lastonionkey);
1347 if (identitykey)
1348 crypto_free_pk_env(identitykey);
1349 if (key_lock)
1350 tor_mutex_free(key_lock);
1351 if (desc_routerinfo)
1352 routerinfo_free(desc_routerinfo);
1353 if (warned_nonexistent_family) {
1354 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1355 smartlist_free(warned_nonexistent_family);