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 */
6 const char router_c_id
[] = "$Id$";
8 #define NEW_LOG_INTERFACE
13 * \brief OR functionality, including key maintenance, generating
14 * and uploading server descriptors, retrying OR connections.
17 extern long stats_n_seconds_working
;
19 /* Exposed for test.c. */ void get_platform_str(char *platform
, size_t len
);
21 /************************************************************/
24 * Key management: ORs only.
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().
39 set_onion_key(crypto_pk_env_t
*k
)
41 tor_mutex_acquire(key_lock
);
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. */
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.
62 get_previous_onion_key(void)
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>.
71 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
75 tor_mutex_acquire(key_lock
);
76 *key
= crypto_pk_dup_key(onionkey
);
78 *last
= crypto_pk_dup_key(lastonionkey
);
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.
89 get_onion_key_set_at(void)
91 return onionkey_set_at
;
94 /** Set the current identity key to k.
97 set_identity_key(crypto_pk_env_t
*k
)
100 crypto_free_pk_env(identitykey
);
104 /** Returns the current identity key; requires that the identity key has been
108 get_identity_key(void)
110 tor_assert(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,
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.
129 rotate_onion_key(void)
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.");
142 if (crypto_pk_generate_key(prkey
)) {
143 err(LD_BUG
,"Error generating onion key");
146 if (file_status(fname
) == FN_FILE
) {
147 if (replace_file(fname
, fname_prev
))
150 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
151 err(LD_FS
,"Couldn't write generated key to \"%s\".", fname
);
154 info(LD_GENERAL
, "Rotating onion key");
155 tor_mutex_acquire(key_lock
);
157 crypto_free_pk_env(lastonionkey
);
158 lastonionkey
= onionkey
;
160 onionkey_set_at
= time(NULL
);
161 tor_mutex_release(key_lock
);
162 mark_my_descriptor_dirty();
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
));
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.
193 init_key_from_file(const char *fname
)
195 crypto_pk_env_t
*prkey
= NULL
;
198 if (!(prkey
= crypto_new_pk_env())) {
199 err(LD_GENERAL
,"Error creating crypto environment.");
203 switch (file_status(fname
)) {
206 err(LD_FS
,"Can't read key from \"%s\"", fname
);
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");
214 if (crypto_pk_check_key(prkey
) <= 0) {
215 err(LD_GENERAL
,"Generated key seems invalid");
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
);
225 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
226 err(LD_GENERAL
,"Error loading private key.");
236 crypto_free_pk_env(prkey
);
242 /** Initialize all OR private keys, and the TLS context, as necessary.
243 * On OPs, this only initializes the tls context.
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.
254 char fingerprint
[FINGERPRINT_LEN
+1];
255 char fingerprint_line
[FINGERPRINT_LEN
+MAX_NICKNAME_LEN
+3];/*nickname fp\n\0 */
257 const char *mydesc
, *datadir
;
258 crypto_pk_env_t
*prkey
;
260 or_options_t
*options
= get_options();
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()))
270 if (crypto_pk_generate_key(prkey
))
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.");
282 /* Make sure DataDirectory exists, and is private. */
283 datadir
= options
->DataDirectory
;
284 if (check_private_dir(datadir
, CPD_CREATE
)) {
287 /* Check the key directory. */
288 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys", datadir
);
289 if (check_private_dir(keydir
, CPD_CREATE
)) {
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
);
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");
321 /* 4. Dump router descriptor to 'router.desc' */
322 /* Must be called after keys are initialized. */
323 mydesc
= router_get_my_descriptor();
325 err(LD_GENERAL
,"Error initializing descriptor.");
328 if (authdir_mode(options
)) {
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");
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>");
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)) {
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");
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");
360 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
361 err(LD_FS
, "Error writing fingerprint line to file");
364 if (!authdir_mode(options
))
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");
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
);
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
||
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() ||
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. */
418 decide_to_advertise_dirport(or_options_t
*options
, routerinfo_t
*router
)
420 if (!router
->dir_port
) /* short circuit the rest of the function */
422 if (authdir_mode(options
)) /* always publish */
423 return router
->dir_port
;
424 if (we_are_hibernating())
426 if (!check_whether_dirport_reachable())
428 if (router
->bandwidthcapacity
>= router
->bandwidthrate
) {
429 /* check if we might potentially hibernate. */
430 if (options
->AccountingMax
!= 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)
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().
454 consider_testing_reachability(void)
456 routerinfo_t
*me
= router_get_my_routerinfo();
458 warn(LD_BUG
,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
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. */
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. */
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. */
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
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.
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
562 * - We don't have the NoPublish option set
564 * - We have ORPort set
566 * - We believe we are reachable from the outside; or
567 * - We have the AuthoritativeDirectory option set.
570 decide_if_publishable_server(time_t now
)
572 or_options_t
*options
= get_options();
574 if (options
->ClientOnly
)
576 if (options
->NoPublish
)
578 if (!server_mode(options
))
580 if (options
->AuthoritativeDir
)
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.
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
);
597 set_server_advertised(0);
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
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
))
624 if (!clique_mode(options
) && !router_is_clique_mode(router
))
627 !connection_get_by_identity_digest(router
->identity_digest
,
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
643 router_is_clique_mode(routerinfo_t
*router
)
645 if (router_digest_is_trusted_dir(router
->identity_digest
))
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
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.
667 router_upload_dir_desc_to_dirservers(int force
)
671 s
= router_get_my_descriptor();
673 warn(LD_GENERAL
, "No descriptor; skipping upload");
676 if (!force
&& !desc_needs_upload
)
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
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
))
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
);
729 /** Return a routerinfo for this OR, rebuilding a fresh one if
730 * necessary. Return NULL on error, or if called on an OP. */
732 router_get_my_routerinfo(void)
734 if (!server_mode(get_options()))
737 if (!desc_routerinfo
) {
738 if (router_rebuild_descriptor(1))
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.
748 router_get_my_descriptor(void)
750 if (!desc_routerinfo
) {
751 if (router_rebuild_descriptor(1))
754 debug(LD_GENERAL
,"my desc is '%s'",desc_routerinfo
->signed_descriptor
);
755 return desc_routerinfo
->signed_descriptor
;
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
)
771 int hibernating
= we_are_hibernating();
772 or_options_t
*options
= get_options();
774 if (desc_clean_since
&& !force
)
777 if (resolve_my_address(options
, &addr
, NULL
) < 0) {
778 warn(LD_CONFIG
,"options->Address didn't resolve into an IP.");
782 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
783 ri
->address
= tor_dup_addr(addr
);
784 ri
->nickname
= tor_strdup(options
->Nickname
);
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) {
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
) {
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
))
828 member
= router_get_by_nickname(name
, 1);
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
);
839 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
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
);
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.");
857 ri
->signed_descriptor_len
= strlen(ri
->signed_descriptor
);
858 crypto_digest(ri
->signed_descriptor_digest
,
859 ri
->signed_descriptor
, ri
->signed_descriptor_len
);
862 routerinfo_free(desc_routerinfo
);
863 desc_routerinfo
= ri
;
865 desc_clean_since
= time(NULL
);
866 desc_needs_upload
= 1;
870 /** Mark descriptor out of date if it's older than <b>when</b> */
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. */
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.*/
889 check_descriptor_bandwidth_changed(time_t now
)
891 static time_t last_changed
= 0;
893 if (!desc_routerinfo
)
896 prev
= desc_routerinfo
->bandwidthcapacity
;
897 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
898 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
901 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
902 info(LD_GENERAL
,"Measured bandwidth has changed; rebuilding descriptor.");
903 mark_my_descriptor_dirty();
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.*/
914 check_descriptor_ipaddress_changed(time_t now
)
916 static time_t last_changed
= 0;
917 static time_t last_warned_lastchangetime
= 0;
919 or_options_t
*options
= get_options();
921 if (!desc_routerinfo
)
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.");
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();
946 last_warned_lastchangetime
= 0;
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.
963 get_platform_str(char *platform
, size_t len
)
965 tor_snprintf(platform
, len
, "Tor %s on %s",
966 VERSION
, get_uname());
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];
991 char addrbuf
[INET_NTOA_BUF_LEN
];
992 size_t onion_pkeylen
, identity_pkeylen
;
996 char *bandwidth_usage
;
998 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1001 routerinfo_t
*ri_tmp
;
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!");
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");
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!");
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
);
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
)) {
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
);
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"
1054 "opt fingerprint %s\n"
1056 "bandwidth %d %d %d\n"
1058 "signing-key\n%s%s%s%s",
1062 decide_to_advertise_dirport(options
, router
),
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
);
1080 /* From now on, we use 'written' to remember the current length of 's'. */
1083 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1084 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n",
1085 options
->ContactInfo
);
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
);
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
);
1111 if (tmpe
->prt_min
<= 1 && tmpe
->prt_max
== 65535) {
1112 /* There is no port set; write ":*" */
1113 if (written
+4 > maxlen
)
1115 strlcat(s
+written
, ":*\n", maxlen
-written
);
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
);
1124 /* There is a range of ports; write ":79-80". */
1125 result
= tor_snprintf(s
+written
, maxlen
-written
, ":%d-%d\n", tmpe
->prt_min
,
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. */
1135 if (written
+256 > maxlen
) /* Not enough room for signature. */
1138 /* Sign the directory */
1139 strlcat(s
+written
, "router-signature\n", maxlen
-written
);
1140 written
+= strlen(s
+written
);
1142 if (router_get_router_hash(s
, digest
) < 0)
1145 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1146 digest
,ident_key
)<0) {
1147 warn(LD_BUG
, "Couldn't sign router descriptor");
1150 written
+= strlen(s
+written
);
1152 if (written
+2 > maxlen
)
1154 /* include a last '\n' */
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
);
1162 err(LD_BUG
,"We just generated a router descriptor we can't parse: <<%s>>", s
);
1166 routerinfo_free(ri_tmp
);
1172 /** Return true iff <b>s</b> is a legally valid server nickname. */
1174 is_legal_nickname(const char *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
)
1191 return is_legal_nickname(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. */
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 */
1210 router_free_all(void)
1213 crypto_free_pk_env(onionkey
);
1215 crypto_free_pk_env(lastonionkey
);
1217 crypto_free_pk_env(identitykey
);
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
);