Infrastructure to test BEGIN_DIR cells.
[tor.git] / src / or / router.c
blobbc38f107cdb0b767f0a6e9c8e3896f18c72023ac
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 constructing rotated onion key");
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 onion 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 key file \"%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 constructing key");
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. Return 0 on success,
236 * or -1 if Tor should die.
239 init_keys(void)
241 char keydir[512];
242 char keydir2[512];
243 char fingerprint[FINGERPRINT_LEN+1];
244 /*nickname<space>fp\n\0 */
245 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
246 const char *mydesc, *datadir;
247 crypto_pk_env_t *prkey;
248 char digest[20];
249 or_options_t *options = get_options();
251 if (!key_lock)
252 key_lock = tor_mutex_new();
254 /* OP's don't need persistent keys; just make up an identity and
255 * initialize the TLS context. */
256 if (!server_mode(options)) {
257 if (!(prkey = crypto_new_pk_env()))
258 return -1;
259 if (crypto_pk_generate_key(prkey))
260 return -1;
261 set_identity_key(prkey);
262 /* Create a TLS context; default the client nickname to "client". */
263 if (tor_tls_context_new(get_identity_key(),
264 options->Nickname ? options->Nickname : "client",
265 MAX_SSL_KEY_LIFETIME) < 0) {
266 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
267 return -1;
269 return 0;
271 /* Make sure DataDirectory exists, and is private. */
272 datadir = options->DataDirectory;
273 if (check_private_dir(datadir, CPD_CREATE)) {
274 return -1;
276 /* Check the key directory. */
277 tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
278 if (check_private_dir(keydir, CPD_CREATE)) {
279 return -1;
282 /* 1. Read identity key. Make it if none is found. */
283 tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
284 tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
285 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir2);
286 prkey = init_key_from_file_name_changed(keydir,keydir2);
287 if (!prkey) return -1;
288 set_identity_key(prkey);
289 /* 2. Read onion key. Make it if none is found. */
290 tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
291 tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
292 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir2);
293 prkey = init_key_from_file_name_changed(keydir,keydir2);
294 if (!prkey) return -1;
295 set_onion_key(prkey);
296 tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
297 if (file_status(keydir) == FN_FILE) {
298 prkey = init_key_from_file(keydir);
299 if (prkey)
300 lastonionkey = prkey;
303 /* 3. Initialize link key and TLS context. */
304 if (tor_tls_context_new(get_identity_key(), options->Nickname,
305 MAX_SSL_KEY_LIFETIME) < 0) {
306 log_err(LD_GENERAL,"Error initializing TLS context");
307 return -1;
309 /* 4. Build our router descriptor. */
310 /* Must be called after keys are initialized. */
311 mydesc = router_get_my_descriptor();
312 if (authdir_mode(options)) {
313 const char *m;
314 /* We need to add our own fingerprint so it gets recognized. */
315 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
316 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
317 return -1;
319 if (!mydesc) {
320 log_err(LD_GENERAL,"Error initializing descriptor.");
321 return -1;
323 if (dirserv_add_descriptor(mydesc, &m) < 0) {
324 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
325 m?m:"<unknown error>");
326 return -1;
330 /* 5. Dump fingerprint to 'fingerprint' */
331 tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
332 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
333 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
334 log_err(LD_GENERAL,"Error computing fingerprint");
335 return -1;
337 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
338 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
339 "%s %s\n",options->Nickname, fingerprint) < 0) {
340 log_err(LD_GENERAL,"Error writing fingerprint line");
341 return -1;
343 if (write_str_to_file(keydir, fingerprint_line, 0)) {
344 log_err(LD_FS, "Error writing fingerprint line to file");
345 return -1;
348 log(LOG_NOTICE, LD_GENERAL,
349 "Your Tor server's identity key fingerprint is '%s %s'",
350 options->Nickname, fingerprint);
351 if (!authdir_mode(options))
352 return 0;
353 /* 6. [authdirserver only] load approved-routers file */
354 if (dirserv_load_fingerprint_file() < 0) {
355 log_err(LD_GENERAL,"Error loading fingerprints");
356 return -1;
358 /* 6b. [authdirserver only] add own key to approved directories. */
359 crypto_pk_get_digest(get_identity_key(), digest);
360 if (!router_digest_is_trusted_dir(digest)) {
361 add_trusted_dir_server(options->Nickname, NULL,
362 (uint16_t)options->DirPort, digest,
363 options->V1AuthoritativeDir, /* v1 authority */
364 1, /* v2 authority */
365 options->HSAuthoritativeDir /*hidserv authority*/);
367 return 0; /* success */
370 /* Keep track of whether we should upload our server descriptor,
371 * and what type of server we are.
374 /** Whether we can reach our ORPort from the outside. */
375 static int can_reach_or_port = 0;
376 /** Whether we can reach our DirPort from the outside. */
377 static int can_reach_dir_port = 0;
379 /** Return 1 if ORPort is known reachable; else return 0. */
381 check_whether_orport_reachable(void)
383 or_options_t *options = get_options();
384 return options->AssumeReachable ||
385 can_reach_or_port;
388 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
390 check_whether_dirport_reachable(void)
392 or_options_t *options = get_options();
393 return !options->DirPort ||
394 options->AssumeReachable ||
395 we_are_hibernating() ||
396 can_reach_dir_port;
399 /** Look at a variety of factors, and return 0 if we don't want to
400 * advertise the fact that we have a DirPort open. Else return the
401 * DirPort we want to advertise. */
402 static int
403 decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
405 if (!router->dir_port) /* short circuit the rest of the function */
406 return 0;
407 if (authdir_mode(options)) /* always publish */
408 return router->dir_port;
409 if (we_are_hibernating())
410 return 0;
411 if (!check_whether_dirport_reachable())
412 return 0;
413 if (router->bandwidthcapacity >= router->bandwidthrate) {
414 /* check if we might potentially hibernate. */
415 if (options->AccountingMax != 0)
416 return 0;
417 /* also check if we're advertising a small amount, and have
418 a "boring" DirPort. */
419 if (router->bandwidthrate < 50000 && router->dir_port > 1024)
420 return 0;
423 /* Sounds like a great idea. Let's publish it. */
424 return router->dir_port;
427 /** Some time has passed, or we just got new directory information.
428 * See if we currently believe our ORPort or DirPort to be
429 * unreachable. If so, launch a new test for it.
431 * For ORPort, we simply try making a circuit that ends at ourselves.
432 * Success is noticed in onionskin_answer().
434 * For DirPort, we make a connection via Tor to our DirPort and ask
435 * for our own server descriptor.
436 * Success is noticed in connection_dir_client_reached_eof().
438 void
439 consider_testing_reachability(int test_or, int test_dir)
441 routerinfo_t *me = router_get_my_routerinfo();
442 int orport_reachable = check_whether_orport_reachable();
443 if (!me)
444 return;
446 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
447 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
448 !orport_reachable ? "reachability" : "bandwidth",
449 me->address, me->or_port);
450 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
453 if (test_dir && !check_whether_dirport_reachable() &&
454 !connection_get_by_type_addr_port_purpose(
455 CONN_TYPE_DIR, me->addr, me->dir_port,
456 DIR_PURPOSE_FETCH_SERVERDESC)) {
457 /* ask myself, via tor, for my server descriptor. */
458 directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
459 1, "authority", NULL, 0);
463 /** Annotate that we found our ORPort reachable. */
464 void
465 router_orport_found_reachable(void)
467 if (!can_reach_or_port) {
468 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
469 "the outside. Excellent.%s",
470 get_options()->PublishServerDescriptor ?
471 " Publishing server descriptor." : "");
472 can_reach_or_port = 1;
473 mark_my_descriptor_dirty();
477 /** Annotate that we found our DirPort reachable. */
478 void
479 router_dirport_found_reachable(void)
481 if (!can_reach_dir_port) {
482 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
483 "from the outside. Excellent.");
484 can_reach_dir_port = 1;
485 mark_my_descriptor_dirty();
489 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
491 /** Our router has just moved to a new IP. Reset stats. */
492 void
493 server_has_changed_ip(void)
495 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
496 reset_bandwidth_test();
497 stats_n_seconds_working = 0;
498 can_reach_or_port = 0;
499 can_reach_dir_port = 0;
500 mark_my_descriptor_dirty();
503 /** We have enough testing circuits open. Send a bunch of "drop"
504 * cells down each of them, to exercise our bandwidth. */
505 void
506 router_perform_bandwidth_test(int num_circs, time_t now)
508 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
509 int max_cells = num_cells < CIRCWINDOW_START ?
510 num_cells : CIRCWINDOW_START;
511 int cells_per_circuit = max_cells / num_circs;
512 origin_circuit_t *circ = NULL;
514 log_notice(LD_OR,"Performing bandwidth self-test.");
515 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
516 CIRCUIT_PURPOSE_TESTING))) {
517 /* dump cells_per_circuit drop cells onto this circ */
518 int i = cells_per_circuit;
519 if (circ->_base.state != CIRCUIT_STATE_OPEN)
520 continue;
521 circ->_base.timestamp_dirty = now;
522 while (i-- > 0) {
523 if (connection_edge_send_command(NULL, TO_CIRCUIT(circ),
524 RELAY_COMMAND_DROP,
525 NULL, 0, circ->cpath->prev)<0) {
526 return; /* stop if error */
532 /** Return true iff we believe ourselves to be an authoritative
533 * directory server.
536 authdir_mode(or_options_t *options)
538 return options->AuthoritativeDir != 0;
540 /** Return true iff we try to stay connected to all ORs at once.
543 clique_mode(or_options_t *options)
545 return authdir_mode(options);
548 /** Return true iff we are trying to be a server.
551 server_mode(or_options_t *options)
553 if (options->ClientOnly) return 0;
554 return (options->ORPort != 0 || options->ORListenAddress);
557 /** Remember if we've advertised ourselves to the dirservers. */
558 static int server_is_advertised=0;
560 /** Return true iff we have published our descriptor lately.
563 advertised_server_mode(void)
565 return server_is_advertised;
569 * Called with a boolean: set whether we have recently published our
570 * descriptor.
572 static void
573 set_server_advertised(int s)
575 server_is_advertised = s;
578 /** Return true iff we are trying to be a socks proxy. */
580 proxy_mode(or_options_t *options)
582 return (options->SocksPort != 0 || options->SocksListenAddress);
585 /** Decide if we're a publishable server. We are a publishable server if:
586 * - We don't have the ClientOnly option set
587 * and
588 * - We have the PublishServerDescriptor option set
589 * and
590 * - We have ORPort set
591 * and
592 * - We believe we are reachable from the outside; or
593 * - We have the AuthoritativeDirectory option set.
595 static int
596 decide_if_publishable_server(void)
598 or_options_t *options = get_options();
600 if (options->ClientOnly)
601 return 0;
602 if (!options->PublishServerDescriptor)
603 return 0;
604 if (!server_mode(options))
605 return 0;
606 if (options->AuthoritativeDir)
607 return 1;
609 return check_whether_orport_reachable();
612 /** Initiate server descriptor upload as reasonable (if server is publishable,
613 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
615 * We need to rebuild the descriptor if it's dirty even if we're not
616 * uploading, because our reachability testing *uses* our descriptor to
617 * determine what IP address and ports to test.
619 void
620 consider_publishable_server(int force)
622 int rebuilt;
624 if (!server_mode(get_options()))
625 return;
627 rebuilt = router_rebuild_descriptor(0);
628 if (decide_if_publishable_server()) {
629 set_server_advertised(1);
630 if (rebuilt == 0)
631 router_upload_dir_desc_to_dirservers(force);
632 } else {
633 set_server_advertised(0);
638 * Clique maintenance -- to be phased out.
641 /** Return true iff this OR should try to keep connections open to all
642 * other ORs. */
644 router_is_clique_mode(routerinfo_t *router)
646 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
647 return 1;
648 return 0;
652 * OR descriptor generation.
655 /** My routerinfo. */
656 static routerinfo_t *desc_routerinfo = NULL;
657 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
658 * now. */
659 static time_t desc_clean_since = 0;
660 /** Boolean: do we need to regenerate the above? */
661 static int desc_needs_upload = 0;
663 /** OR only: If <b>force</b> is true, or we haven't uploaded this
664 * descriptor successfully yet, try to upload our signed descriptor to
665 * all the directory servers we know about.
667 void
668 router_upload_dir_desc_to_dirservers(int force)
670 const char *s;
672 s = router_get_my_descriptor();
673 if (!s) {
674 log_info(LD_GENERAL, "No descriptor; skipping upload");
675 return;
677 if (!get_options()->PublishServerDescriptor)
678 return;
679 if (!force && !desc_needs_upload)
680 return;
681 desc_needs_upload = 0;
682 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
685 /** OR only: Check whether my exit policy says to allow connection to
686 * conn. Return 0 if we accept; non-0 if we reject.
689 router_compare_to_my_exit_policy(edge_connection_t *conn)
691 tor_assert(desc_routerinfo);
693 /* make sure it's resolved to something. this way we can't get a
694 'maybe' below. */
695 if (!conn->_base.addr)
696 return -1;
698 return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
699 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
702 /** Return true iff I'm a server and <b>digest</b> is equal to
703 * my identity digest. */
705 router_digest_is_me(const char *digest)
707 routerinfo_t *me = router_get_my_routerinfo();
708 if (!me || memcmp(me->cache_info.identity_digest, digest, DIGEST_LEN))
709 return 0;
710 return 1;
713 /** A wrapper around router_digest_is_me(). */
715 router_is_me(routerinfo_t *router)
717 return router_digest_is_me(router->cache_info.identity_digest);
720 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
722 router_fingerprint_is_me(const char *fp)
724 char digest[DIGEST_LEN];
725 if (strlen(fp) == HEX_DIGEST_LEN &&
726 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
727 return router_digest_is_me(digest);
729 return 0;
732 /** Return a routerinfo for this OR, rebuilding a fresh one if
733 * necessary. Return NULL on error, or if called on an OP. */
734 routerinfo_t *
735 router_get_my_routerinfo(void)
737 if (!server_mode(get_options()))
738 return NULL;
739 if (router_rebuild_descriptor(0))
740 return NULL;
741 return desc_routerinfo;
744 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
745 * one if necessary. Return NULL on error.
747 const char *
748 router_get_my_descriptor(void)
750 const char *body;
751 if (!router_get_my_routerinfo())
752 return NULL;
753 /* Make sure this is nul-terminated. */
754 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
755 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
756 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
757 log_debug(LD_GENERAL,"my desc is '%s'", body);
758 return body;
761 /*DOCDOC*/
762 static smartlist_t *warned_nonexistent_family = NULL;
764 static int router_guess_address_from_dir_headers(uint32_t *guess);
766 /** Return our current best guess at our address, either because
767 * it's configured in torrc, or because we've learned it from
768 * dirserver headers. */
770 router_pick_published_address(or_options_t *options, uint32_t *addr)
772 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
773 log_info(LD_CONFIG, "Could not determine our address locally. "
774 "Checking if directory headers provide any hints.");
775 if (router_guess_address_from_dir_headers(addr) < 0) {
776 log_info(LD_CONFIG, "No hints from directory headers either. "
777 "Will try again later.");
778 return -1;
781 return 0;
784 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
785 * a fresh routerinfo and signed server descriptor for this OR.
786 * Return 0 on success, -1 on temporary error.
789 router_rebuild_descriptor(int force)
791 routerinfo_t *ri;
792 uint32_t addr;
793 char platform[256];
794 int hibernating = we_are_hibernating();
795 or_options_t *options = get_options();
797 if (desc_clean_since && !force)
798 return 0;
800 if (router_pick_published_address(options, &addr) < 0) {
801 /* Stop trying to rebuild our descriptor every second. We'll
802 * learn that it's time to try again when server_has_changed_ip()
803 * marks it dirty. */
804 desc_clean_since = time(NULL);
805 return -1;
808 ri = tor_malloc_zero(sizeof(routerinfo_t));
809 ri->routerlist_index = -1;
810 ri->address = tor_dup_addr(addr);
811 ri->nickname = tor_strdup(options->Nickname);
812 ri->addr = addr;
813 ri->or_port = options->ORPort;
814 ri->dir_port = options->DirPort;
815 ri->cache_info.published_on = time(NULL);
816 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
817 * main thread */
818 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
819 if (crypto_pk_get_digest(ri->identity_pkey,
820 ri->cache_info.identity_digest)<0) {
821 routerinfo_free(ri);
822 return -1;
824 get_platform_str(platform, sizeof(platform));
825 ri->platform = tor_strdup(platform);
826 ri->bandwidthrate = (int)options->BandwidthRate;
827 ri->bandwidthburst = (int)options->BandwidthBurst;
828 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
830 if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
831 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
833 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
834 options->ExitPolicyRejectPrivate);
836 if (desc_routerinfo) { /* inherit values */
837 ri->is_valid = desc_routerinfo->is_valid;
838 ri->is_running = desc_routerinfo->is_running;
839 ri->is_named = desc_routerinfo->is_named;
841 if (authdir_mode(options))
842 ri->is_valid = ri->is_named = 1; /* believe in yourself */
843 if (options->MyFamily) {
844 smartlist_t *family;
845 if (!warned_nonexistent_family)
846 warned_nonexistent_family = smartlist_create();
847 family = smartlist_create();
848 ri->declared_family = smartlist_create();
849 smartlist_split_string(family, options->MyFamily, ",",
850 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
851 SMARTLIST_FOREACH(family, char *, name,
853 routerinfo_t *member;
854 if (!strcasecmp(name, options->Nickname))
855 member = ri;
856 else
857 member = router_get_by_nickname(name, 1);
858 if (!member) {
859 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
860 !is_legal_hexdigest(name)) {
861 log_warn(LD_CONFIG,
862 "I have no descriptor for the router named \"%s\" "
863 "in my declared family; I'll use the nickname as is, but "
864 "this may confuse clients.", name);
865 smartlist_add(warned_nonexistent_family, tor_strdup(name));
867 smartlist_add(ri->declared_family, name);
868 name = NULL;
869 } else {
870 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
871 fp[0] = '$';
872 base16_encode(fp+1,HEX_DIGEST_LEN+1,
873 member->cache_info.identity_digest, DIGEST_LEN);
874 smartlist_add(ri->declared_family, fp);
875 if (smartlist_string_isin(warned_nonexistent_family, name))
876 smartlist_string_remove(warned_nonexistent_family, name);
878 tor_free(name);
881 /* remove duplicates from the list */
882 smartlist_sort_strings(ri->declared_family);
883 smartlist_uniq_strings(ri->declared_family);
885 smartlist_free(family);
887 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
888 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
889 ri, get_identity_key())<0) {
890 log_warn(LD_BUG, "Couldn't allocate string for descriptor.");
891 return -1;
893 ri->cache_info.signed_descriptor_len =
894 strlen(ri->cache_info.signed_descriptor_body);
895 crypto_digest(ri->cache_info.signed_descriptor_digest,
896 ri->cache_info.signed_descriptor_body,
897 ri->cache_info.signed_descriptor_len);
899 if (desc_routerinfo)
900 routerinfo_free(desc_routerinfo);
901 desc_routerinfo = ri;
903 desc_clean_since = time(NULL);
904 desc_needs_upload = 1;
905 control_event_my_descriptor_changed();
906 return 0;
909 /** Mark descriptor out of date if it's older than <b>when</b> */
910 void
911 mark_my_descriptor_dirty_if_older_than(time_t when)
913 if (desc_clean_since < when)
914 mark_my_descriptor_dirty();
917 /** Call when the current descriptor is out of date. */
918 void
919 mark_my_descriptor_dirty(void)
921 desc_clean_since = 0;
924 /** How frequently will we republish our descriptor because of large (factor
925 * of 2) shifts in estimated bandwidth? */
926 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
928 /** Check whether bandwidth has changed a lot since the last time we announced
929 * bandwidth. If so, mark our descriptor dirty. */
930 void
931 check_descriptor_bandwidth_changed(time_t now)
933 static time_t last_changed = 0;
934 uint64_t prev, cur;
935 if (!desc_routerinfo)
936 return;
938 prev = desc_routerinfo->bandwidthcapacity;
939 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
940 if ((prev != cur && (!prev || !cur)) ||
941 cur > prev*2 ||
942 cur < prev/2) {
943 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
944 log_info(LD_GENERAL,
945 "Measured bandwidth has changed; rebuilding descriptor.");
946 mark_my_descriptor_dirty();
947 last_changed = now;
952 static void
953 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
955 char addrbuf_prev[INET_NTOA_BUF_LEN];
956 char addrbuf_cur[INET_NTOA_BUF_LEN];
957 struct in_addr in_prev;
958 struct in_addr in_cur;
960 in_prev.s_addr = htonl(prev);
961 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
963 in_cur.s_addr = htonl(cur);
964 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
966 if (prev)
967 log_fn(severity, LD_GENERAL,
968 "Our IP Address has changed from %s to %s; "
969 "rebuilding descriptor.",
970 addrbuf_prev, addrbuf_cur);
971 else
972 log_notice(LD_GENERAL,
973 "Guessed our IP address as %s.",
974 addrbuf_cur);
977 /** Check whether our own address as defined by the Address configuration
978 * has changed. This is for routers that get their address from a service
979 * like dyndns. If our address has changed, mark our descriptor dirty. */
980 void
981 check_descriptor_ipaddress_changed(time_t now)
983 uint32_t prev, cur;
984 or_options_t *options = get_options();
985 (void) now;
987 if (!desc_routerinfo)
988 return;
990 prev = desc_routerinfo->addr;
991 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
992 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
993 return;
996 if (prev != cur) {
997 log_addr_has_changed(LOG_INFO, prev, cur);
998 mark_my_descriptor_dirty();
999 /* the above call is probably redundant, since resolve_my_address()
1000 * probably already noticed and marked it dirty. */
1004 static uint32_t last_guessed_ip = 0;
1006 /** A directory authority told us our IP address is <b>suggestion</b>.
1007 * If this address is different from the one we think we are now, and
1008 * if our computer doesn't actually know its IP address, then switch. */
1009 void
1010 router_new_address_suggestion(const char *suggestion)
1012 uint32_t addr, cur = 0;
1013 struct in_addr in;
1014 or_options_t *options = get_options();
1016 /* first, learn what the IP address actually is */
1017 if (!tor_inet_aton(suggestion, &in)) {
1018 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1019 escaped(suggestion));
1020 return;
1022 addr = ntohl(in.s_addr);
1024 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1026 if (!server_mode(options)) {
1027 last_guessed_ip = addr; /* store it in case we need it later */
1028 return;
1031 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1032 /* We're all set -- we already know our address. Great. */
1033 last_guessed_ip = cur; /* store it in case we need it later */
1034 return;
1037 if (last_guessed_ip != addr) {
1038 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
1039 server_has_changed_ip();
1040 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1044 /** We failed to resolve our address locally, but we'd like to build
1045 * a descriptor and publish / test reachability. If we have a guess
1046 * about our address based on directory headers, answer it and return
1047 * 0; else return -1. */
1048 static int
1049 router_guess_address_from_dir_headers(uint32_t *guess)
1051 if (last_guessed_ip) {
1052 *guess = last_guessed_ip;
1053 return 0;
1055 return -1;
1058 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1059 * string describing the version of Tor and the operating system we're
1060 * currently running on.
1062 void
1063 get_platform_str(char *platform, size_t len)
1065 tor_snprintf(platform, len, "Tor %s on %s",
1066 VERSION, get_uname());
1067 return;
1070 /* XXX need to audit this thing and count fenceposts. maybe
1071 * refactor so we don't have to keep asking if we're
1072 * near the end of maxlen?
1074 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1076 /** OR only: Given a routerinfo for this router, and an identity key to sign
1077 * with, encode the routerinfo as a signed server descriptor and write the
1078 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1079 * failure, and the number of bytes used on success.
1082 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1083 crypto_pk_env_t *ident_key)
1085 char *onion_pkey; /* Onion key, PEM-encoded. */
1086 char *identity_pkey; /* Identity key, PEM-encoded. */
1087 char digest[DIGEST_LEN];
1088 char published[ISO_TIME_LEN+1];
1089 char fingerprint[FINGERPRINT_LEN+1];
1090 struct in_addr in;
1091 char addrbuf[INET_NTOA_BUF_LEN];
1092 size_t onion_pkeylen, identity_pkeylen;
1093 size_t written;
1094 int result=0;
1095 addr_policy_t *tmpe;
1096 char *bandwidth_usage;
1097 char *family_line;
1098 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1099 char *s_dup;
1100 const char *cp;
1101 routerinfo_t *ri_tmp;
1102 #endif
1103 or_options_t *options = get_options();
1105 /* Make sure the identity key matches the one in the routerinfo. */
1106 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1107 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1108 "match router's public key!");
1109 return -1;
1112 /* record our fingerprint, so we can include it in the descriptor */
1113 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1114 log_err(LD_BUG,"Error computing fingerprint");
1115 return -1;
1118 /* PEM-encode the onion key */
1119 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1120 &onion_pkey,&onion_pkeylen)<0) {
1121 log_warn(LD_BUG,"write onion_pkey to string failed!");
1122 return -1;
1125 /* PEM-encode the identity key key */
1126 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1127 &identity_pkey,&identity_pkeylen)<0) {
1128 log_warn(LD_BUG,"write identity_pkey to string failed!");
1129 tor_free(onion_pkey);
1130 return -1;
1133 /* Encode the publication time. */
1134 format_iso_time(published, router->cache_info.published_on);
1136 /* How busy have we been? */
1137 bandwidth_usage = rep_hist_get_bandwidth_lines();
1139 if (router->declared_family && smartlist_len(router->declared_family)) {
1140 size_t n;
1141 char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
1142 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1143 family_line = tor_malloc(n);
1144 tor_snprintf(family_line, n, "family %s\n", s);
1145 tor_free(s);
1146 } else {
1147 family_line = tor_strdup("");
1150 /* Generate the easy portion of the router descriptor. */
1151 result = tor_snprintf(s, maxlen,
1152 "router %s %s %d 0 %d\n"
1153 "platform %s\n"
1154 "published %s\n"
1155 "opt fingerprint %s\n"
1156 "uptime %ld\n"
1157 "bandwidth %d %d %d\n"
1158 "onion-key\n%s"
1159 "signing-key\n%s"
1160 #ifdef USE_EVENTDNS
1161 "opt eventdns 1\n"
1162 #else
1163 "opt eventdns 0\n"
1164 #endif
1165 "%s%s%s",
1166 router->nickname,
1167 router->address,
1168 router->or_port,
1169 decide_to_advertise_dirport(options, router),
1170 router->platform,
1171 published,
1172 fingerprint,
1173 stats_n_seconds_working,
1174 (int) router->bandwidthrate,
1175 (int) router->bandwidthburst,
1176 (int) router->bandwidthcapacity,
1177 onion_pkey, identity_pkey,
1178 family_line, bandwidth_usage,
1179 we_are_hibernating() ? "opt hibernating 1\n" : "");
1180 tor_free(family_line);
1181 tor_free(onion_pkey);
1182 tor_free(identity_pkey);
1183 tor_free(bandwidth_usage);
1185 if (result < 0)
1186 return -1;
1187 /* From now on, we use 'written' to remember the current length of 's'. */
1188 written = result;
1190 if (options->ContactInfo && strlen(options->ContactInfo)) {
1191 result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
1192 options->ContactInfo);
1193 if (result<0)
1194 return -1;
1195 written += result;
1198 /* Write the exit policy to the end of 's'. */
1199 for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
1200 /* Write: "accept 1.2.3.4" */
1201 in.s_addr = htonl(tmpe->addr);
1202 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
1203 result = tor_snprintf(s+written, maxlen-written, "%s %s",
1204 tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
1205 tmpe->msk == 0 ? "*" : addrbuf);
1206 if (result < 0)
1207 return -1;
1208 written += result;
1209 if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
1210 int n_bits = addr_mask_get_bits(tmpe->msk);
1211 if (n_bits >= 0) {
1212 if (tor_snprintf(s+written, maxlen-written, "/%d", n_bits)<0)
1213 return -1;
1214 } else {
1215 /* Write "/255.255.0.0" */
1216 in.s_addr = htonl(tmpe->msk);
1217 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
1218 if (tor_snprintf(s+written, maxlen-written, "/%s", addrbuf)<0)
1219 return -1;
1221 written += strlen(s+written);
1223 if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
1224 /* There is no port set; write ":*" */
1225 if (written+4 > maxlen)
1226 return -1;
1227 strlcat(s+written, ":*\n", maxlen-written);
1228 written += 3;
1229 } else if (tmpe->prt_min == tmpe->prt_max) {
1230 /* There is only one port; write ":80". */
1231 result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
1232 if (result<0)
1233 return -1;
1234 written += result;
1235 } else {
1236 /* There is a range of ports; write ":79-80". */
1237 result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n",
1238 tmpe->prt_min, tmpe->prt_max);
1239 if (result<0)
1240 return -1;
1241 written += result;
1243 } /* end for */
1245 if (written+256 > maxlen) /* Not enough room for signature. */
1246 return -1;
1248 /* Sign the directory */
1249 strlcat(s+written, "router-signature\n", maxlen-written);
1250 written += strlen(s+written);
1251 s[written] = '\0';
1252 if (router_get_router_hash(s, digest) < 0)
1253 return -1;
1255 note_crypto_pk_op(SIGN_RTR);
1256 if (router_append_dirobj_signature(s+written,maxlen-written,
1257 digest,ident_key)<0) {
1258 log_warn(LD_BUG, "Couldn't sign router descriptor");
1259 return -1;
1261 written += strlen(s+written);
1263 if (written+2 > maxlen)
1264 return -1;
1265 /* include a last '\n' */
1266 s[written] = '\n';
1267 s[written+1] = 0;
1269 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1270 cp = s_dup = tor_strdup(s);
1271 ri_tmp = router_parse_entry_from_string(cp, NULL, 1);
1272 if (!ri_tmp) {
1273 log_err(LD_BUG,
1274 "We just generated a router descriptor we can't parse: <<%s>>",
1276 return -1;
1278 tor_free(s_dup);
1279 routerinfo_free(ri_tmp);
1280 #endif
1282 return written+1;
1285 /** Return true iff <b>s</b> is a legally valid server nickname. */
1287 is_legal_nickname(const char *s)
1289 size_t len;
1290 tor_assert(s);
1291 len = strlen(s);
1292 return len > 0 && len <= MAX_NICKNAME_LEN &&
1293 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1296 /** Return true iff <b>s</b> is a legally valid server nickname or
1297 * hex-encoded identity-key digest. */
1299 is_legal_nickname_or_hexdigest(const char *s)
1301 if (*s!='$')
1302 return is_legal_nickname(s);
1303 else
1304 return is_legal_hexdigest(s);
1307 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1308 * digest. */
1310 is_legal_hexdigest(const char *s)
1312 size_t len;
1313 tor_assert(s);
1314 if (s[0] == '$') s++;
1315 len = strlen(s);
1316 if (len > HEX_DIGEST_LEN) {
1317 if (s[HEX_DIGEST_LEN] == '=' ||
1318 s[HEX_DIGEST_LEN] == '~') {
1319 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1320 return 0;
1321 } else {
1322 return 0;
1325 return (len >= HEX_DIGEST_LEN &&
1326 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1329 /** DOCDOC buf must have MAX_VERBOSE_NICKNAME_LEN+1 bytes. */
1330 void
1331 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1333 buf[0] = '$';
1334 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1335 DIGEST_LEN);
1336 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1337 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1340 /** Forget that we have issued any router-related warnings, so that we'll
1341 * warn again if we see the same errors. */
1342 void
1343 router_reset_warnings(void)
1345 if (warned_nonexistent_family) {
1346 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1347 smartlist_clear(warned_nonexistent_family);
1351 /** Release all static resources held in router.c */
1352 void
1353 router_free_all(void)
1355 if (onionkey)
1356 crypto_free_pk_env(onionkey);
1357 if (lastonionkey)
1358 crypto_free_pk_env(lastonionkey);
1359 if (identitykey)
1360 crypto_free_pk_env(identitykey);
1361 if (key_lock)
1362 tor_mutex_free(key_lock);
1363 if (desc_routerinfo)
1364 routerinfo_free(desc_routerinfo);
1365 if (warned_nonexistent_family) {
1366 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1367 smartlist_free(warned_nonexistent_family);