Convert circuituse, command, config, connection, relay, router, test to new logging...
[tor.git] / src / or / router.c
blob3531d9024f5bc980ea228adadbc8a6d46b4de034
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char router_c_id[] = "$Id$";
8 #define NEW_LOG_INTERFACE
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 /** Return the onion key that was current before the most recent onion
58 * key rotation. If no rotation has been performed since this process
59 * started, return NULL.
61 crypto_pk_env_t *
62 get_previous_onion_key(void)
64 return lastonionkey;
67 /** Store a copy of the current onion key into *<b>key</b>, and a copy
68 * of the most recent onion key into *<b>last</b>.
70 void
71 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
73 tor_assert(key);
74 tor_assert(last);
75 tor_mutex_acquire(key_lock);
76 *key = crypto_pk_dup_key(onionkey);
77 if (lastonionkey)
78 *last = crypto_pk_dup_key(lastonionkey);
79 else
80 *last = NULL;
81 tor_mutex_release(key_lock);
84 /** Return the time when the onion key was last set. This is either the time
85 * when the process launched, or the time of the most recent key rotation since
86 * the process launched.
88 time_t
89 get_onion_key_set_at(void)
91 return onionkey_set_at;
94 /** Set the current identity key to k.
96 void
97 set_identity_key(crypto_pk_env_t *k)
99 if (identitykey)
100 crypto_free_pk_env(identitykey);
101 identitykey = k;
104 /** Returns the current identity key; requires that the identity key has been
105 * set.
107 crypto_pk_env_t *
108 get_identity_key(void)
110 tor_assert(identitykey);
111 return identitykey;
114 /** Return true iff the identity key has been set. */
116 identity_key_is_set(void)
118 return identitykey != NULL;
121 /** Replace the previous onion key with the current onion key, and generate
122 * a new previous onion key. Immediately after calling this function,
123 * the OR should:
124 * - schedule all previous cpuworkers to shut down _after_ processing
125 * pending work. (This will cause fresh cpuworkers to be generated.)
126 * - generate and upload a fresh routerinfo.
128 void
129 rotate_onion_key(void)
131 char fname[512];
132 char fname_prev[512];
133 crypto_pk_env_t *prkey;
134 tor_snprintf(fname,sizeof(fname),
135 "%s/keys/secret_onion_key",get_options()->DataDirectory);
136 tor_snprintf(fname_prev,sizeof(fname_prev),
137 "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
138 if (!(prkey = crypto_new_pk_env())) {
139 err(LD_GENERAL,"Error creating crypto environment.");
140 goto error;
142 if (crypto_pk_generate_key(prkey)) {
143 err(LD_BUG,"Error generating onion key");
144 goto error;
146 if (file_status(fname) == FN_FILE) {
147 if (replace_file(fname, fname_prev))
148 goto error;
150 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
151 err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
152 goto error;
154 info(LD_GENERAL, "Rotating onion key");
155 tor_mutex_acquire(key_lock);
156 if (lastonionkey)
157 crypto_free_pk_env(lastonionkey);
158 lastonionkey = onionkey;
159 onionkey = prkey;
160 onionkey_set_at = time(NULL);
161 tor_mutex_release(key_lock);
162 mark_my_descriptor_dirty();
163 return;
164 error:
165 warn(LD_GENERAL, "Couldn't rotate onion key.");
168 /* Read an RSA secret key key from a file that was once named fname_old,
169 * but is now named fname_new. Rename the file from old to new as needed.
171 static crypto_pk_env_t *
172 init_key_from_file_name_changed(const char *fname_old,
173 const char *fname_new)
175 if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
176 /* The new filename is there, or both are, or neither is. */
177 return init_key_from_file(fname_new);
179 /* The old filename exists, and the new one doesn't. Rename and load. */
180 if (rename(fname_old, fname_new) < 0) {
181 log_fn(LOG_ERR, LD_FS, "Couldn't rename \"%s\" to \"%s\": %s",
182 fname_old, fname_new, strerror(errno));
183 return NULL;
185 return init_key_from_file(fname_new);
188 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
189 * create a new RSA key and save it in <b>fname</b>. Return the read/created
190 * key, or NULL on error.
192 crypto_pk_env_t *
193 init_key_from_file(const char *fname)
195 crypto_pk_env_t *prkey = NULL;
196 FILE *file = NULL;
198 if (!(prkey = crypto_new_pk_env())) {
199 err(LD_GENERAL,"Error creating crypto environment.");
200 goto error;
203 switch (file_status(fname)) {
204 case FN_DIR:
205 case FN_ERROR:
206 err(LD_FS,"Can't read key from \"%s\"", fname);
207 goto error;
208 case FN_NOENT:
209 info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.", fname);
210 if (crypto_pk_generate_key(prkey)) {
211 err(LD_GENERAL,"Error generating onion key");
212 goto error;
214 if (crypto_pk_check_key(prkey) <= 0) {
215 err(LD_GENERAL,"Generated key seems invalid");
216 goto error;
218 info(LD_GENERAL, "Generated key seems valid");
219 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
220 err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
221 goto error;
223 return prkey;
224 case FN_FILE:
225 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
226 err(LD_GENERAL,"Error loading private key.");
227 goto error;
229 return prkey;
230 default:
231 tor_assert(0);
234 error:
235 if (prkey)
236 crypto_free_pk_env(prkey);
237 if (file)
238 fclose(file);
239 return NULL;
242 /** Initialize all OR private keys, and the TLS context, as necessary.
243 * On OPs, this only initializes the tls context.
246 init_keys(void)
248 /* XXX009 Two problems with how this is called:
249 * 1. It should be idempotent for servers, so we can call init_keys
250 * as much as we need to.
252 char keydir[512];
253 char keydir2[512];
254 char fingerprint[FINGERPRINT_LEN+1];
255 char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];/*nickname fp\n\0 */
256 char *cp;
257 const char *mydesc, *datadir;
258 crypto_pk_env_t *prkey;
259 char digest[20];
260 or_options_t *options = get_options();
262 if (!key_lock)
263 key_lock = tor_mutex_new();
265 /* OP's don't need persistent keys; just make up an identity and
266 * initialize the TLS context. */
267 if (!server_mode(options)) {
268 if (!(prkey = crypto_new_pk_env()))
269 return -1;
270 if (crypto_pk_generate_key(prkey))
271 return -1;
272 set_identity_key(prkey);
273 /* Create a TLS context; default the client nickname to "client". */
274 if (tor_tls_context_new(get_identity_key(), 1,
275 options->Nickname ? options->Nickname : "client",
276 MAX_SSL_KEY_LIFETIME) < 0) {
277 err(LD_GENERAL,"Error creating TLS context for OP.");
278 return -1;
280 return 0;
282 /* Make sure DataDirectory exists, and is private. */
283 datadir = options->DataDirectory;
284 if (check_private_dir(datadir, CPD_CREATE)) {
285 return -1;
287 /* Check the key directory. */
288 tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
289 if (check_private_dir(keydir, CPD_CREATE)) {
290 return -1;
292 cp = keydir + strlen(keydir); /* End of string. */
294 /* 1. Read identity key. Make it if none is found. */
295 tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
296 tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
297 info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir2);
298 prkey = init_key_from_file_name_changed(keydir,keydir2);
299 if (!prkey) return -1;
300 set_identity_key(prkey);
301 /* 2. Read onion key. Make it if none is found. */
302 tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
303 tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
304 info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir2);
305 prkey = init_key_from_file_name_changed(keydir,keydir2);
306 if (!prkey) return -1;
307 set_onion_key(prkey);
308 tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
309 if (file_status(keydir) == FN_FILE) {
310 prkey = init_key_from_file(keydir);
311 if (prkey)
312 lastonionkey = prkey;
315 /* 3. Initialize link key and TLS context. */
316 if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
317 MAX_SSL_KEY_LIFETIME) < 0) {
318 err(LD_GENERAL,"Error initializing TLS context");
319 return -1;
321 /* 4. Dump router descriptor to 'router.desc' */
322 /* Must be called after keys are initialized. */
323 mydesc = router_get_my_descriptor();
324 if (!mydesc) {
325 err(LD_GENERAL,"Error initializing descriptor.");
326 return -1;
328 if (authdir_mode(options)) {
329 const char *m;
330 /* We need to add our own fingerprint so it gets recognized. */
331 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
332 err(LD_GENERAL,"Error adding own fingerprint to approved set");
333 return -1;
335 if (dirserv_add_descriptor(mydesc, &m) < 0) {
336 err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
337 m?m:"<unknown error>");
338 return -1;
342 tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
343 info(LD_GENERAL,"Dumping descriptor to \"%s\"...",keydir);
344 if (write_str_to_file(keydir, mydesc,0)) {
345 return -1;
347 /* 5. Dump fingerprint to 'fingerprint' */
348 tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
349 info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
350 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
351 err(LD_GENERAL,"Error computing fingerprint");
352 return -1;
354 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
355 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
356 "%s %s\n",options->Nickname, fingerprint) < 0) {
357 err(LD_GENERAL,"Error writing fingerprint line");
358 return -1;
360 if (write_str_to_file(keydir, fingerprint_line, 0)) {
361 err(LD_FS, "Error writing fingerprint line to file");
362 return -1;
364 if (!authdir_mode(options))
365 return 0;
366 /* 6. [authdirserver only] load approved-routers file */
367 tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
368 info(LD_DIRSERV,"Loading approved fingerprints from \"%s\"...",keydir);
369 if (dirserv_parse_fingerprint_file(keydir) < 0) {
370 err(LD_GENERAL,"Error loading fingerprints");
371 return -1;
373 /* 6b. [authdirserver only] add own key to approved directories. */
374 crypto_pk_get_digest(get_identity_key(), digest);
375 if (!router_digest_is_trusted_dir(digest)) {
376 add_trusted_dir_server(options->Nickname, NULL,
377 (uint16_t)options->DirPort, digest,
378 options->V1AuthoritativeDir);
380 /* success */
381 return 0;
384 /* Keep track of whether we should upload our server descriptor,
385 * and what type of server we are.
388 /** Whether we can reach our ORPort from the outside. */
389 static int can_reach_or_port = 0;
390 /** Whether we can reach our DirPort from the outside. */
391 static int can_reach_dir_port = 0;
393 /** Return 1 if or port is known reachable; else return 0. */
395 check_whether_orport_reachable(void)
397 or_options_t *options = get_options();
398 return clique_mode(options) ||
399 options->AssumeReachable ||
400 can_reach_or_port;
403 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
405 check_whether_dirport_reachable(void)
407 or_options_t *options = get_options();
408 return !options->DirPort ||
409 options->AssumeReachable ||
410 we_are_hibernating() ||
411 can_reach_dir_port;
414 /** Look at a variety of factors, and return 0 if we don't want to
415 * advertise the fact that we have a DirPort open. Else return the
416 * DirPort we want to advertise. */
417 static int
418 decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
420 if (!router->dir_port) /* short circuit the rest of the function */
421 return 0;
422 if (authdir_mode(options)) /* always publish */
423 return router->dir_port;
424 if (we_are_hibernating())
425 return 0;
426 if (!check_whether_dirport_reachable())
427 return 0;
428 if (router->bandwidthcapacity >= router->bandwidthrate) {
429 /* check if we might potentially hibernate. */
430 if (options->AccountingMax != 0)
431 return 0;
432 /* also check if we're advertising a small amount, and have
433 a "boring" DirPort. */
434 if (router->bandwidthrate < 50000 && router->dir_port > 1024)
435 return 0;
438 /* Sounds like a great idea. Let's publish it. */
439 return router->dir_port;
442 /** Some time has passed, or we just got new directory information.
443 * See if we currently believe our ORPort or DirPort to be
444 * unreachable. If so, launch a new test for it.
446 * For ORPort, we simply try making a circuit that ends at ourselves.
447 * Success is noticed in onionskin_answer().
449 * For DirPort, we make a connection via Tor to our DirPort and ask
450 * for our own server descriptor.
451 * Success is noticed in connection_dir_client_reached_eof().
453 void
454 consider_testing_reachability(void)
456 routerinfo_t *me = router_get_my_routerinfo();
457 if (!me) {
458 warn(LD_BUG,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
459 return;
462 if (!check_whether_orport_reachable()) {
463 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
466 if (!check_whether_dirport_reachable()) {
467 /* ask myself, via tor, for my server descriptor. */
468 directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
469 1, "authority", NULL, 0);
473 /** Annotate that we found our ORPort reachable. */
474 void
475 router_orport_found_reachable(void)
477 if (!can_reach_or_port) {
478 if (!clique_mode(get_options()))
479 notice(LD_OR,"Self-testing indicates your ORPort is reachable from the outside. Excellent.%s",
480 get_options()->NoPublish ? "" : " Publishing server descriptor.");
481 can_reach_or_port = 1;
482 mark_my_descriptor_dirty();
483 consider_publishable_server(time(NULL), 1);
487 /** Annotate that we found our DirPort reachable. */
488 void
489 router_dirport_found_reachable(void)
491 if (!can_reach_dir_port) {
492 notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable from the outside. Excellent.");
493 can_reach_dir_port = 1;
497 /** Our router has just moved to a new IP. Reset stats. */
498 void
499 server_has_changed_ip(void)
501 stats_n_seconds_working = 0;
502 can_reach_or_port = 0;
503 can_reach_dir_port = 0;
504 mark_my_descriptor_dirty();
507 /** Return true iff we believe ourselves to be an authoritative
508 * directory server.
511 authdir_mode(or_options_t *options)
513 return options->AuthoritativeDir != 0;
515 /** Return true iff we try to stay connected to all ORs at once.
518 clique_mode(or_options_t *options)
520 return authdir_mode(options);
523 /** Return true iff we are trying to be a server.
526 server_mode(or_options_t *options)
528 if (options->ClientOnly) return 0;
529 return (options->ORPort != 0 || options->ORListenAddress);
532 /** Remember if we've advertised ourselves to the dirservers. */
533 static int server_is_advertised=0;
535 /** Return true iff we have published our descriptor lately.
538 advertised_server_mode(void)
540 return server_is_advertised;
544 * Called with a boolean: set whether we have recently published our descriptor.
546 static void
547 set_server_advertised(int s)
549 server_is_advertised = s;
552 /** Return true iff we are trying to be a socks proxy. */
554 proxy_mode(or_options_t *options)
556 return (options->SocksPort != 0 || options->SocksListenAddress);
559 /** Decide if we're a publishable server. We are a publishable server if:
560 * - We don't have the ClientOnly option set
561 * and
562 * - We don't have the NoPublish option set
563 * and
564 * - We have ORPort set
565 * and
566 * - We believe we are reachable from the outside; or
567 * - We have the AuthoritativeDirectory option set.
569 static int
570 decide_if_publishable_server(time_t now)
572 or_options_t *options = get_options();
574 if (options->ClientOnly)
575 return 0;
576 if (options->NoPublish)
577 return 0;
578 if (!server_mode(options))
579 return 0;
580 if (options->AuthoritativeDir)
581 return 1;
583 return check_whether_orport_reachable();
586 /** Initiate server descriptor upload as reasonable (if server is publishable,
587 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
589 void
590 consider_publishable_server(time_t now, int force)
592 if (decide_if_publishable_server(now)) {
593 set_server_advertised(1);
594 if (router_rebuild_descriptor(0) == 0)
595 router_upload_dir_desc_to_dirservers(force);
596 } else {
597 set_server_advertised(0);
602 * Clique maintenance
605 /** OR only: if in clique mode, try to open connections to all of the
606 * other ORs we know about. Otherwise, open connections to those we
607 * think are in clique mode.o
609 * If <b>force</b> is zero, only open the connection if we don't already
610 * have one.
612 void
613 router_retry_connections(int force)
615 time_t now = time(NULL);
616 routerlist_t *rl = router_get_routerlist();
617 or_options_t *options = get_options();
619 tor_assert(server_mode(options));
621 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
622 if (router_is_me(router))
623 continue;
624 if (!clique_mode(options) && !router_is_clique_mode(router))
625 continue;
626 if (force ||
627 !connection_get_by_identity_digest(router->identity_digest,
628 CONN_TYPE_OR)) {
629 debug(LD_OR,"%sconnecting to %s at %s:%u.",
630 clique_mode(options) ? "(forced) " : "",
631 router->nickname, router->address, router->or_port);
632 /* Remember when we started trying to determine reachability */
633 if (!router->testing_since)
634 router->testing_since = now;
635 connection_or_connect(router->addr, router->or_port, router->identity_digest);
640 /** Return true iff this OR should try to keep connections open to all
641 * other ORs. */
643 router_is_clique_mode(routerinfo_t *router)
645 if (router_digest_is_trusted_dir(router->identity_digest))
646 return 1;
647 return 0;
651 * OR descriptor generation.
654 /** My routerinfo. */
655 static routerinfo_t *desc_routerinfo = NULL;
656 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
657 * now. */
658 static time_t desc_clean_since = 0;
659 /** Boolean: do we need to regenerate the above? */
660 static int desc_needs_upload = 0;
662 /** OR only: If <b>force</b> is true, or we haven't uploaded this
663 * descriptor successfully yet, try to upload our signed descriptor to
664 * all the directory servers we know about.
666 void
667 router_upload_dir_desc_to_dirservers(int force)
669 const char *s;
671 s = router_get_my_descriptor();
672 if (!s) {
673 warn(LD_GENERAL, "No descriptor; skipping upload");
674 return;
676 if (!force && !desc_needs_upload)
677 return;
678 desc_needs_upload = 0;
679 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
682 /** OR only: Check whether my exit policy says to allow connection to
683 * conn. Return 0 if we accept; non-0 if we reject.
686 router_compare_to_my_exit_policy(connection_t *conn)
688 tor_assert(desc_routerinfo);
690 /* make sure it's resolved to something. this way we can't get a
691 'maybe' below. */
692 if (!conn->addr)
693 return -1;
695 return router_compare_addr_to_addr_policy(conn->addr, conn->port,
696 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
699 /** Return true iff I'm a server and <b>digest</b> is equal to
700 * my identity digest. */
702 router_digest_is_me(const char *digest)
704 routerinfo_t *me = router_get_my_routerinfo();
705 if (!me || memcmp(me->identity_digest, digest, DIGEST_LEN))
706 return 0;
707 return 1;
710 /** A wrapper around router_digest_is_me(). */
712 router_is_me(routerinfo_t *router)
714 return router_digest_is_me(router->identity_digest);
717 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
719 router_fingerprint_is_me(const char *fp)
721 char digest[DIGEST_LEN];
722 if (strlen(fp) == HEX_DIGEST_LEN &&
723 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
724 return router_digest_is_me(digest);
726 return 0;
729 /** Return a routerinfo for this OR, rebuilding a fresh one if
730 * necessary. Return NULL on error, or if called on an OP. */
731 routerinfo_t *
732 router_get_my_routerinfo(void)
734 if (!server_mode(get_options()))
735 return NULL;
737 if (!desc_routerinfo) {
738 if (router_rebuild_descriptor(1))
739 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 if (!desc_routerinfo) {
751 if (router_rebuild_descriptor(1))
752 return NULL;
754 debug(LD_GENERAL,"my desc is '%s'",desc_routerinfo->signed_descriptor);
755 return desc_routerinfo->signed_descriptor;
758 /*DOCDOC*/
759 static smartlist_t *warned_nonexistent_family = NULL;
761 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
762 * a fresh routerinfo and signed server descriptor for this OR.
763 * Return 0 on success, -1 on error.
766 router_rebuild_descriptor(int force)
768 routerinfo_t *ri;
769 uint32_t addr;
770 char platform[256];
771 int hibernating = we_are_hibernating();
772 or_options_t *options = get_options();
774 if (desc_clean_since && !force)
775 return 0;
777 if (resolve_my_address(options, &addr, NULL) < 0) {
778 warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
779 return -1;
782 ri = tor_malloc_zero(sizeof(routerinfo_t));
783 ri->address = tor_dup_addr(addr);
784 ri->nickname = tor_strdup(options->Nickname);
785 ri->addr = addr;
786 ri->or_port = options->ORPort;
787 ri->dir_port = options->DirPort;
788 ri->published_on = time(NULL);
789 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
790 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
791 if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
792 routerinfo_free(ri);
793 return -1;
795 get_platform_str(platform, sizeof(platform));
796 ri->platform = tor_strdup(platform);
797 ri->bandwidthrate = (int)options->BandwidthRate;
798 ri->bandwidthburst = (int)options->BandwidthBurst;
799 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
801 if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
802 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
804 config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy, -1);
805 options_append_default_exit_policy(&ri->exit_policy);
807 if (desc_routerinfo) { /* inherit values */
808 ri->is_verified = desc_routerinfo->is_verified;
809 ri->is_running = desc_routerinfo->is_running;
810 ri->is_named = desc_routerinfo->is_named;
812 if (authdir_mode(options))
813 ri->is_verified = ri->is_named = 1; /* believe in yourself */
814 if (options->MyFamily) {
815 smartlist_t *family;
816 if (!warned_nonexistent_family)
817 warned_nonexistent_family = smartlist_create();
818 family = smartlist_create();
819 ri->declared_family = smartlist_create();
820 smartlist_split_string(family, options->MyFamily, ",",
821 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
822 SMARTLIST_FOREACH(family, char *, name,
824 routerinfo_t *member;
825 if (!strcasecmp(name, options->Nickname))
826 member = ri;
827 else
828 member = router_get_by_nickname(name, 1);
829 if (!member) {
830 if (!smartlist_string_isin(warned_nonexistent_family, name)) {
831 warn(LD_CONFIG, "I have no descriptor for the router named \"%s\" "
832 "in my declared family; I'll use the nickname as is, but "
833 "this may confuse clients.", name);
834 smartlist_add(warned_nonexistent_family, tor_strdup(name));
836 smartlist_add(ri->declared_family, name);
837 name = NULL;
838 } else {
839 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
840 fp[0] = '$';
841 base16_encode(fp+1,HEX_DIGEST_LEN+1,
842 member->identity_digest, DIGEST_LEN);
843 smartlist_add(ri->declared_family, fp);
844 if (smartlist_string_isin(warned_nonexistent_family, name))
845 smartlist_string_remove(warned_nonexistent_family, name);
847 tor_free(name);
849 smartlist_free(family);
851 ri->signed_descriptor = tor_malloc(8192);
852 if (router_dump_router_to_string(ri->signed_descriptor, 8192,
853 ri, get_identity_key())<0) {
854 warn(LD_BUG, "Couldn't allocate string for descriptor.");
855 return -1;
857 ri->signed_descriptor_len = strlen(ri->signed_descriptor);
858 crypto_digest(ri->signed_descriptor_digest,
859 ri->signed_descriptor, ri->signed_descriptor_len);
861 if (desc_routerinfo)
862 routerinfo_free(desc_routerinfo);
863 desc_routerinfo = ri;
865 desc_clean_since = time(NULL);
866 desc_needs_upload = 1;
867 return 0;
870 /** Mark descriptor out of date if it's older than <b>when</b> */
871 void
872 mark_my_descriptor_dirty_if_older_than(time_t when)
874 if (desc_clean_since < when)
875 mark_my_descriptor_dirty();
878 /** Call when the current descriptor is out of date. */
879 void
880 mark_my_descriptor_dirty(void)
882 desc_clean_since = 0;
885 #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
886 /** Check whether bandwidth has changed a lot since the last time we announced
887 * bandwidth. If so, mark our descriptor dirty.*/
888 void
889 check_descriptor_bandwidth_changed(time_t now)
891 static time_t last_changed = 0;
892 uint64_t prev, cur;
893 if (!desc_routerinfo)
894 return;
896 prev = desc_routerinfo->bandwidthcapacity;
897 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
898 if ((prev != cur && (!prev || !cur)) ||
899 cur > prev*2 ||
900 cur < prev/2) {
901 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
902 info(LD_GENERAL,"Measured bandwidth has changed; rebuilding descriptor.");
903 mark_my_descriptor_dirty();
904 last_changed = now;
909 #define MAX_IPADDRESS_CHANGE_FREQ 60*60
910 /** Check whether our own address as defined by the Address configuration
911 * has changed. This is for routers that get their address from a service
912 * like dyndns. If our address has changed, mark our descriptor dirty.*/
913 void
914 check_descriptor_ipaddress_changed(time_t now)
916 static time_t last_changed = 0;
917 static time_t last_warned_lastchangetime = 0;
918 uint32_t prev, cur;
919 or_options_t *options = get_options();
921 if (!desc_routerinfo)
922 return;
924 prev = desc_routerinfo->addr;
925 if (resolve_my_address(options, &cur, NULL) < 0) {
926 warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
927 return;
930 if (prev != cur) {
931 char addrbuf_prev[INET_NTOA_BUF_LEN];
932 char addrbuf_cur[INET_NTOA_BUF_LEN];
933 struct in_addr in_prev;
934 struct in_addr in_cur;
936 in_prev.s_addr = htonl(prev);
937 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
939 in_cur.s_addr = htonl(cur);
940 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
942 if (last_changed+MAX_IPADDRESS_CHANGE_FREQ < now) {
943 info(LD_GENERAL,"Our IP Address has changed from %s to %s; rebuilding descriptor.", addrbuf_prev, addrbuf_cur);
944 mark_my_descriptor_dirty();
945 last_changed = now;
946 last_warned_lastchangetime = 0;
948 else
950 if (last_warned_lastchangetime != last_changed) {
951 warn(LD_GENERAL,"Our IP Address seems to be flapping. It has changed twice within one hour (from %s to %s this time). Ignoring for now.", addrbuf_prev, addrbuf_cur);
952 last_warned_lastchangetime = last_changed;
958 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
959 * string describing the version of Tor and the operating system we're
960 * currently running on.
962 void
963 get_platform_str(char *platform, size_t len)
965 tor_snprintf(platform, len, "Tor %s on %s",
966 VERSION, get_uname());
967 return;
970 /* XXX need to audit this thing and count fenceposts. maybe
971 * refactor so we don't have to keep asking if we're
972 * near the end of maxlen?
974 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
976 /** OR only: Given a routerinfo for this router, and an identity key to sign
977 * with, encode the routerinfo as a signed server descriptor and write the
978 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
979 * failure, and the number of bytes used on success.
982 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
983 crypto_pk_env_t *ident_key)
985 char *onion_pkey; /* Onion key, PEM-encoded. */
986 char *identity_pkey; /* Identity key, PEM-encoded. */
987 char digest[DIGEST_LEN];
988 char published[ISO_TIME_LEN+1];
989 char fingerprint[FINGERPRINT_LEN+1];
990 struct in_addr in;
991 char addrbuf[INET_NTOA_BUF_LEN];
992 size_t onion_pkeylen, identity_pkeylen;
993 size_t written;
994 int result=0;
995 addr_policy_t *tmpe;
996 char *bandwidth_usage;
997 char *family_line;
998 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
999 char *s_tmp, *s_dup;
1000 const char *cp;
1001 routerinfo_t *ri_tmp;
1002 #endif
1003 or_options_t *options = get_options();
1005 /* Make sure the identity key matches the one in the routerinfo. */
1006 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1007 warn(LD_BUG,"Tried to sign a router with a private key that didn't match router's public key!");
1008 return -1;
1011 /* record our fingerprint, so we can include it in the descriptor */
1012 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1013 err(LD_BUG,"Error computing fingerprint");
1014 return -1;
1017 /* PEM-encode the onion key */
1018 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1019 &onion_pkey,&onion_pkeylen)<0) {
1020 warn(LD_BUG,"write onion_pkey to string failed!");
1021 return -1;
1024 /* PEM-encode the identity key key */
1025 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1026 &identity_pkey,&identity_pkeylen)<0) {
1027 warn(LD_BUG,"write identity_pkey to string failed!");
1028 tor_free(onion_pkey);
1029 return -1;
1032 /* Encode the publication time. */
1033 format_iso_time(published, router->published_on);
1035 /* How busy have we been? */
1036 bandwidth_usage = rep_hist_get_bandwidth_lines();
1038 if (router->declared_family && smartlist_len(router->declared_family)) {
1039 size_t n;
1040 char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
1041 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1042 family_line = tor_malloc(n);
1043 tor_snprintf(family_line, n, "family %s\n", s);
1044 tor_free(s);
1045 } else {
1046 family_line = tor_strdup("");
1049 /* Generate the easy portion of the router descriptor. */
1050 result = tor_snprintf(s, maxlen,
1051 "router %s %s %d 0 %d\n"
1052 "platform %s\n"
1053 "published %s\n"
1054 "opt fingerprint %s\n"
1055 "uptime %ld\n"
1056 "bandwidth %d %d %d\n"
1057 "onion-key\n%s"
1058 "signing-key\n%s%s%s%s",
1059 router->nickname,
1060 router->address,
1061 router->or_port,
1062 decide_to_advertise_dirport(options, router),
1063 router->platform,
1064 published,
1065 fingerprint,
1066 stats_n_seconds_working,
1067 (int) router->bandwidthrate,
1068 (int) router->bandwidthburst,
1069 (int) router->bandwidthcapacity,
1070 onion_pkey, identity_pkey,
1071 family_line, bandwidth_usage,
1072 we_are_hibernating() ? "opt hibernating 1\n" : "");
1073 tor_free(family_line);
1074 tor_free(onion_pkey);
1075 tor_free(identity_pkey);
1076 tor_free(bandwidth_usage);
1078 if (result < 0)
1079 return -1;
1080 /* From now on, we use 'written' to remember the current length of 's'. */
1081 written = result;
1083 if (options->ContactInfo && strlen(options->ContactInfo)) {
1084 result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
1085 options->ContactInfo);
1086 if (result<0)
1087 return -1;
1088 written += result;
1091 /* Write the exit policy to the end of 's'. */
1092 for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
1093 /* Write: "accept 1.2.3.4" */
1094 in.s_addr = htonl(tmpe->addr);
1095 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
1096 result = tor_snprintf(s+written, maxlen-written, "%s %s",
1097 tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
1098 tmpe->msk == 0 ? "*" : addrbuf);
1099 if (result < 0)
1100 return -1;
1101 written += result;
1102 if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
1103 /* Write "/255.255.0.0" */
1104 in.s_addr = htonl(tmpe->msk);
1105 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
1106 result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
1107 if (result<0)
1108 return -1;
1109 written += result;
1111 if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
1112 /* There is no port set; write ":*" */
1113 if (written+4 > maxlen)
1114 return -1;
1115 strlcat(s+written, ":*\n", maxlen-written);
1116 written += 3;
1117 } else if (tmpe->prt_min == tmpe->prt_max) {
1118 /* There is only one port; write ":80". */
1119 result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
1120 if (result<0)
1121 return -1;
1122 written += result;
1123 } else {
1124 /* There is a range of ports; write ":79-80". */
1125 result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
1126 tmpe->prt_max);
1127 if (result<0)
1128 return -1;
1129 written += result;
1131 if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
1132 /* This was a catch-all rule, so future rules are irrelevant. */
1133 break;
1134 } /* end for */
1135 if (written+256 > maxlen) /* Not enough room for signature. */
1136 return -1;
1138 /* Sign the directory */
1139 strlcat(s+written, "router-signature\n", maxlen-written);
1140 written += strlen(s+written);
1141 s[written] = '\0';
1142 if (router_get_router_hash(s, digest) < 0)
1143 return -1;
1145 if (router_append_dirobj_signature(s+written,maxlen-written,
1146 digest,ident_key)<0) {
1147 warn(LD_BUG, "Couldn't sign router descriptor");
1148 return -1;
1150 written += strlen(s+written);
1152 if (written+2 > maxlen)
1153 return -1;
1154 /* include a last '\n' */
1155 s[written] = '\n';
1156 s[written+1] = 0;
1158 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1159 cp = s_tmp = s_dup = tor_strdup(s);
1160 ri_tmp = router_parse_entry_from_string(cp, NULL);
1161 if (!ri_tmp) {
1162 err(LD_BUG,"We just generated a router descriptor we can't parse: <<%s>>", s);
1163 return -1;
1165 tor_free(s_dup);
1166 routerinfo_free(ri_tmp);
1167 #endif
1169 return written+1;
1172 /** Return true iff <b>s</b> is a legally valid server nickname. */
1174 is_legal_nickname(const char *s)
1176 size_t len;
1177 tor_assert(s);
1178 len = strlen(s);
1179 return len > 0 && len <= MAX_NICKNAME_LEN &&
1180 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1183 /** Return true iff <b>s</b> is a legally valid server nickname or
1184 * hex-encoded identity-key digest. */
1186 is_legal_nickname_or_hexdigest(const char *s)
1188 size_t len;
1189 tor_assert(s);
1190 if (*s!='$')
1191 return is_legal_nickname(s);
1193 len = strlen(s);
1194 return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
1197 /** Forget that we have issued any router-related warnings, so that we'll
1198 * warn again if we see the same errors. */
1199 void
1200 router_reset_warnings(void)
1202 if (warned_nonexistent_family) {
1203 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1204 smartlist_clear(warned_nonexistent_family);
1208 /** Release all static resources held in router.c */
1209 void
1210 router_free_all(void)
1212 if (onionkey)
1213 crypto_free_pk_env(onionkey);
1214 if (lastonionkey)
1215 crypto_free_pk_env(lastonionkey);
1216 if (identitykey)
1217 crypto_free_pk_env(identitykey);
1218 if (key_lock)
1219 tor_mutex_free(key_lock);
1220 if (desc_routerinfo)
1221 routerinfo_free(desc_routerinfo);
1222 if (warned_nonexistent_family) {
1223 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1224 smartlist_free(warned_nonexistent_family);