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$";
12 * \brief OR functionality, including key maintenance, generating
13 * and uploading server descriptors, retrying OR connections.
16 extern long stats_n_seconds_working
;
18 /* Exposed for test.c. */ void get_platform_str(char *platform
, size_t len
);
20 /************************************************************/
23 * Key management: ORs only.
26 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
28 static tor_mutex_t
*key_lock
=NULL
;
29 static time_t onionkey_set_at
=0; /* When was onionkey last changed? */
30 static crypto_pk_env_t
*onionkey
=NULL
;
31 static crypto_pk_env_t
*lastonionkey
=NULL
;
32 static crypto_pk_env_t
*identitykey
=NULL
;
34 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
35 * to update onionkey correctly, call rotate_onion_key().
38 set_onion_key(crypto_pk_env_t
*k
)
40 tor_mutex_acquire(key_lock
);
42 onionkey_set_at
= time(NULL
);
43 tor_mutex_release(key_lock
);
44 mark_my_descriptor_dirty();
47 /** Return the current onion key. Requires that the onion key has been
48 * loaded or generated. */
56 /** Return the onion key that was current before the most recent onion
57 * key rotation. If no rotation has been performed since this process
58 * started, return NULL.
61 get_previous_onion_key(void)
66 /** Store a copy of the current onion key into *<b>key</b>, and a copy
67 * of the most recent onion key into *<b>last</b>.
70 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
74 tor_mutex_acquire(key_lock
);
75 *key
= crypto_pk_dup_key(onionkey
);
77 *last
= crypto_pk_dup_key(lastonionkey
);
80 tor_mutex_release(key_lock
);
83 /** Return the time when the onion key was last set. This is either the time
84 * when the process launched, or the time of the most recent key rotation since
85 * the process launched.
88 get_onion_key_set_at(void)
90 return onionkey_set_at
;
93 /** Set the current identity key to k.
96 set_identity_key(crypto_pk_env_t
*k
)
99 crypto_free_pk_env(identitykey
);
103 /** Returns the current identity key; requires that the identity key has been
107 get_identity_key(void)
109 tor_assert(identitykey
);
113 /** Return true iff the identity key has been set. */
115 identity_key_is_set(void)
117 return identitykey
!= NULL
;
120 /** Replace the previous onion key with the current onion key, and generate
121 * a new previous onion key. Immediately after calling this function,
123 * - schedule all previous cpuworkers to shut down _after_ processing
124 * pending work. (This will cause fresh cpuworkers to be generated.)
125 * - generate and upload a fresh routerinfo.
128 rotate_onion_key(void)
131 char fname_prev
[512];
132 crypto_pk_env_t
*prkey
;
133 tor_snprintf(fname
,sizeof(fname
),
134 "%s/keys/secret_onion_key",get_options()->DataDirectory
);
135 tor_snprintf(fname_prev
,sizeof(fname_prev
),
136 "%s/keys/secret_onion_key.old",get_options()->DataDirectory
);
137 if (!(prkey
= crypto_new_pk_env())) {
138 log(LOG_ERR
, "Error creating crypto environment.");
141 if (crypto_pk_generate_key(prkey
)) {
142 log(LOG_ERR
, "Error generating onion key");
145 if (file_status(fname
) == FN_FILE
) {
146 if (replace_file(fname
, fname_prev
))
149 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
150 log(LOG_ERR
, "Couldn't write generated key to \"%s\".", fname
);
153 log_fn(LOG_INFO
, "Rotating onion key");
154 tor_mutex_acquire(key_lock
);
156 crypto_free_pk_env(lastonionkey
);
157 lastonionkey
= onionkey
;
159 onionkey_set_at
= time(NULL
);
160 tor_mutex_release(key_lock
);
161 mark_my_descriptor_dirty();
164 log_fn(LOG_WARN
, "Couldn't rotate onion key.");
167 /* Read an RSA secret key key from a file that was once named fname_old,
168 * but is now named fname_new. Rename the file from old to new as needed.
170 static crypto_pk_env_t
*
171 init_key_from_file_name_changed(const char *fname_old
,
172 const char *fname_new
)
174 if (file_status(fname_new
) == FN_FILE
|| file_status(fname_old
) != FN_FILE
)
175 /* The new filename is there, or both are, or neither is. */
176 return init_key_from_file(fname_new
);
178 /* The old filename exists, and the new one doesn't. Rename and load. */
179 if (rename(fname_old
, fname_new
) < 0) {
180 log_fn(LOG_ERR
, "Couldn't rename \"%s\" to \"%s\": %s", fname_old
, fname_new
,
184 return init_key_from_file(fname_new
);
187 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
188 * create a new RSA key and save it in <b>fname</b>. Return the read/created
189 * key, or NULL on error.
192 init_key_from_file(const char *fname
)
194 crypto_pk_env_t
*prkey
= NULL
;
197 if (!(prkey
= crypto_new_pk_env())) {
198 log(LOG_ERR
, "Error creating crypto environment.");
202 switch (file_status(fname
)) {
205 log(LOG_ERR
, "Can't read key from \"%s\"", fname
);
208 log(LOG_INFO
, "No key found in \"%s\"; generating fresh key.", fname
);
209 if (crypto_pk_generate_key(prkey
)) {
210 log(LOG_ERR
, "Error generating onion key");
213 if (crypto_pk_check_key(prkey
) <= 0) {
214 log(LOG_ERR
, "Generated key seems invalid");
217 log(LOG_INFO
, "Generated key seems valid");
218 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
219 log(LOG_ERR
, "Couldn't write generated key to \"%s\".", fname
);
224 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
225 log(LOG_ERR
, "Error loading private key.");
235 crypto_free_pk_env(prkey
);
241 /** Initialize all OR private keys, and the TLS context, as necessary.
242 * On OPs, this only initializes the tls context.
247 /* XXX009 Two problems with how this is called:
248 * 1. It should be idempotent for servers, so we can call init_keys
249 * as much as we need to.
253 char fingerprint
[FINGERPRINT_LEN
+1];
254 char fingerprint_line
[FINGERPRINT_LEN
+MAX_NICKNAME_LEN
+3];/*nickname fp\n\0 */
256 const char *mydesc
, *datadir
;
257 crypto_pk_env_t
*prkey
;
259 or_options_t
*options
= get_options();
262 key_lock
= tor_mutex_new();
264 /* OP's don't need persistent keys; just make up an identity and
265 * initialize the TLS context. */
266 if (!server_mode(options
)) {
267 if (!(prkey
= crypto_new_pk_env()))
269 if (crypto_pk_generate_key(prkey
))
271 set_identity_key(prkey
);
272 /* Create a TLS context; default the client nickname to "client". */
273 if (tor_tls_context_new(get_identity_key(), 1,
274 options
->Nickname
? options
->Nickname
: "client",
275 MAX_SSL_KEY_LIFETIME
) < 0) {
276 log_fn(LOG_ERR
, "Error creating TLS context for OP.");
281 /* Make sure DataDirectory exists, and is private. */
282 datadir
= options
->DataDirectory
;
283 if (check_private_dir(datadir
, CPD_CREATE
)) {
286 /* Check the key directory. */
287 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys", datadir
);
288 if (check_private_dir(keydir
, CPD_CREATE
)) {
291 cp
= keydir
+ strlen(keydir
); /* End of string. */
293 /* 1. Read identity key. Make it if none is found. */
294 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/identity.key",datadir
);
295 tor_snprintf(keydir2
,sizeof(keydir2
),"%s/keys/secret_id_key",datadir
);
296 log_fn(LOG_INFO
,"Reading/making identity key \"%s\"...",keydir2
);
297 prkey
= init_key_from_file_name_changed(keydir
,keydir2
);
298 if (!prkey
) return -1;
299 set_identity_key(prkey
);
300 /* 2. Read onion key. Make it if none is found. */
301 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/onion.key",datadir
);
302 tor_snprintf(keydir2
,sizeof(keydir2
),"%s/keys/secret_onion_key",datadir
);
303 log_fn(LOG_INFO
,"Reading/making onion key \"%s\"...",keydir2
);
304 prkey
= init_key_from_file_name_changed(keydir
,keydir2
);
305 if (!prkey
) return -1;
306 set_onion_key(prkey
);
307 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/secret_onion_key.old",datadir
);
308 if (file_status(keydir
) == FN_FILE
) {
309 prkey
= init_key_from_file(keydir
);
311 lastonionkey
= prkey
;
314 /* 3. Initialize link key and TLS context. */
315 if (tor_tls_context_new(get_identity_key(), 1, options
->Nickname
,
316 MAX_SSL_KEY_LIFETIME
) < 0) {
317 log_fn(LOG_ERR
, "Error initializing TLS context");
320 /* 4. Dump router descriptor to 'router.desc' */
321 /* Must be called after keys are initialized. */
322 mydesc
= router_get_my_descriptor();
324 log_fn(LOG_ERR
, "Error initializing descriptor.");
327 if (authdir_mode(options
)) {
329 /* We need to add our own fingerprint so it gets recognized. */
330 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
331 log_fn(LOG_ERR
, "Error adding own fingerprint to approved set");
334 if (dirserv_add_descriptor(mydesc
, &m
) < 0) {
335 log(LOG_ERR
, "Unable to add own descriptor to directory: %s",
336 m
?m
:"<unknown error>");
341 tor_snprintf(keydir
,sizeof(keydir
),"%s/router.desc", datadir
);
342 log_fn(LOG_INFO
,"Dumping descriptor to \"%s\"...",keydir
);
343 if (write_str_to_file(keydir
, mydesc
,0)) {
346 /* 5. Dump fingerprint to 'fingerprint' */
347 tor_snprintf(keydir
,sizeof(keydir
),"%s/fingerprint", datadir
);
348 log_fn(LOG_INFO
,"Dumping fingerprint to \"%s\"...",keydir
);
349 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 1)<0) {
350 log_fn(LOG_ERR
, "Error computing fingerprint");
353 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
354 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
355 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
356 log_fn(LOG_ERR
, "Error writing fingerprint line");
359 if (write_str_to_file(keydir
, fingerprint_line
, 0))
361 if (!authdir_mode(options
))
363 /* 6. [authdirserver only] load approved-routers file */
364 tor_snprintf(keydir
,sizeof(keydir
),"%s/approved-routers", datadir
);
365 log_fn(LOG_INFO
,"Loading approved fingerprints from \"%s\"...",keydir
);
366 if (dirserv_parse_fingerprint_file(keydir
) < 0) {
367 log_fn(LOG_ERR
, "Error loading fingerprints");
370 /* 6b. [authdirserver only] add own key to approved directories. */
371 crypto_pk_get_digest(get_identity_key(), digest
);
372 if (!router_digest_is_trusted_dir(digest
)) {
373 add_trusted_dir_server(options
->Nickname
, NULL
,
374 (uint16_t)options
->DirPort
, digest
,
375 options
->V1AuthoritativeDir
);
381 /* Keep track of whether we should upload our server descriptor,
382 * and what type of server we are.
385 /** Whether we can reach our ORPort from the outside. */
386 static int can_reach_or_port
= 0;
387 /** Whether we can reach our DirPort from the outside. */
388 static int can_reach_dir_port
= 0;
390 /** Return 1 if or port is known reachable; else return 0. */
392 check_whether_orport_reachable(void)
394 or_options_t
*options
= get_options();
395 return clique_mode(options
) ||
396 options
->AssumeReachable
||
400 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
402 check_whether_dirport_reachable(void)
404 or_options_t
*options
= get_options();
405 return !options
->DirPort
||
406 options
->AssumeReachable
||
410 /** Look at a variety of factors, and return 0 if we don't want to
411 * advertise the fact that we have a DirPort open. Else return the
412 * DirPort we want to advertise. */
414 decide_to_advertise_dirport(or_options_t
*options
, routerinfo_t
*router
)
416 if (!router
->dir_port
) /* short circuit the rest of the function */
418 if (authdir_mode(options
)) /* always publish */
419 return router
->dir_port
;
420 if (we_are_hibernating())
422 if (!check_whether_dirport_reachable())
424 if (router
->bandwidthcapacity
>= router
->bandwidthrate
) {
425 /* check if we might potentially hibernate. */
426 if (options
->AccountingMax
!= 0)
428 /* also check if we're advertising a small amount, and have
429 a "boring" DirPort. */
430 if (router
->bandwidthrate
< 50000 && router
->dir_port
> 1024)
434 /* Sounds like a great idea. Let's publish it. */
435 return router
->dir_port
;
438 /** Some time has passed, or we just got new directory information.
439 * See if we currently believe our ORPort or DirPort to be
440 * unreachable. If so, launch a new test for it.
442 * For ORPort, we simply try making a circuit that ends at ourselves.
443 * Success is noticed in onionskin_answer().
445 * For DirPort, we make a connection via Tor to our DirPort and ask
446 * for our own server descriptor.
447 * Success is noticed in connection_dir_client_reached_eof().
450 consider_testing_reachability(void)
452 routerinfo_t
*me
= router_get_my_routerinfo();
454 log_fn(LOG_WARN
,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
458 if (!check_whether_orport_reachable()) {
459 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
, 0, 1, 1);
462 if (!check_whether_dirport_reachable()) {
463 /* ask myself, via tor, for my server descriptor. */
464 directory_initiate_command_router(me
, DIR_PURPOSE_FETCH_SERVERDESC
,
465 1, "authority", NULL
, 0);
469 /** Annotate that we found our ORPort reachable. */
471 router_orport_found_reachable(void)
473 if (!can_reach_or_port
) {
474 if (!clique_mode(get_options()))
475 log(LOG_NOTICE
,"Self-testing indicates your ORPort is reachable from the outside. Excellent.%s",
476 get_options()->NoPublish
? "" : " Publishing server descriptor.");
477 can_reach_or_port
= 1;
478 mark_my_descriptor_dirty();
479 consider_publishable_server(time(NULL
), 1);
483 /** Annotate that we found our DirPort reachable. */
485 router_dirport_found_reachable(void)
487 if (!can_reach_dir_port
) {
488 log(LOG_NOTICE
,"Self-testing indicates your DirPort is reachable from the outside. Excellent.");
489 can_reach_dir_port
= 1;
493 /** Our router has just moved to a new IP. Reset stats. */
495 server_has_changed_ip(void)
497 stats_n_seconds_working
= 0;
498 can_reach_or_port
= 0;
499 can_reach_dir_port
= 0;
500 mark_my_descriptor_dirty();
503 /** Return true iff we believe ourselves to be an authoritative
507 authdir_mode(or_options_t
*options
)
509 return options
->AuthoritativeDir
!= 0;
511 /** Return true iff we try to stay connected to all ORs at once.
514 clique_mode(or_options_t
*options
)
516 return authdir_mode(options
);
519 /** Return true iff we are trying to be a server.
522 server_mode(or_options_t
*options
)
524 if (options
->ClientOnly
) return 0;
525 return (options
->ORPort
!= 0 || options
->ORBindAddress
);
528 /** Remember if we've advertised ourselves to the dirservers. */
529 static int server_is_advertised
=0;
531 /** Return true iff we have published our descriptor lately.
534 advertised_server_mode(void)
536 return server_is_advertised
;
540 * Called with a boolean: set whether we have recently published our descriptor.
543 set_server_advertised(int s
)
545 server_is_advertised
= s
;
548 /** Return true iff we are trying to be a socks proxy. */
550 proxy_mode(or_options_t
*options
)
552 return (options
->SocksPort
!= 0 || options
->SocksBindAddress
);
555 /** Decide if we're a publishable server. We are a publishable server if:
556 * - We don't have the ClientOnly option set
558 * - We don't have the NoPublish option set
560 * - We have ORPort set
562 * - We believe we are reachable from the outside; or
563 * - We have the AuthoritativeDirectory option set.
566 decide_if_publishable_server(time_t now
)
568 or_options_t
*options
= get_options();
570 if (options
->ClientOnly
)
572 if (options
->NoPublish
)
574 if (!server_mode(options
))
576 if (options
->AuthoritativeDir
)
579 return check_whether_orport_reachable();
582 /** Initiate server descriptor upload as reasonable (if server is publishable,
583 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
586 consider_publishable_server(time_t now
, int force
)
588 if (decide_if_publishable_server(now
)) {
589 set_server_advertised(1);
590 if (router_rebuild_descriptor(0) == 0)
591 router_upload_dir_desc_to_dirservers(force
);
593 set_server_advertised(0);
601 /** OR only: if in clique mode, try to open connections to all of the
602 * other ORs we know about. Otherwise, open connections to those we
603 * think are in clique mode.o
605 * If <b>force</b> is zero, only open the connection if we don't already
609 router_retry_connections(int force
)
612 time_t now
= time(NULL
);
613 routerinfo_t
*router
;
615 or_options_t
*options
= get_options();
617 tor_assert(server_mode(options
));
619 router_get_routerlist(&rl
);
621 for (i
=0;i
< smartlist_len(rl
->routers
);i
++) {
622 router
= smartlist_get(rl
->routers
, i
);
623 if (router_is_me(router
))
625 if (!clique_mode(options
) && !router_is_clique_mode(router
))
628 !connection_get_by_identity_digest(router
->identity_digest
,
630 log_fn(LOG_INFO
,"%sconnecting to %s at %s:%u.",
631 clique_mode(options
) ? "(forced) " : "",
632 router
->nickname
, router
->address
, router
->or_port
);
633 /* Remember when we started trying to determine reachability */
634 if (!router
->testing_since
)
635 router
->testing_since
= now
;
636 connection_or_connect(router
->addr
, router
->or_port
, router
->identity_digest
);
641 /** Return true iff this OR should try to keep connections open to all
644 router_is_clique_mode(routerinfo_t
*router
)
646 if (router_digest_is_trusted_dir(router
->identity_digest
))
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
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.
668 router_upload_dir_desc_to_dirservers(int force
)
672 s
= router_get_my_descriptor();
674 log_fn(LOG_WARN
, "No descriptor; skipping upload");
677 if (!force
&& !desc_needs_upload
)
679 desc_needs_upload
= 0;
680 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
, s
, strlen(s
));
683 /** OR only: Check whether my exit policy says to allow connection to
684 * conn. Return 0 if we accept; non-0 if we reject.
687 router_compare_to_my_exit_policy(connection_t
*conn
)
689 tor_assert(desc_routerinfo
);
691 /* make sure it's resolved to something. this way we can't get a
696 return router_compare_addr_to_addr_policy(conn
->addr
, conn
->port
,
697 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
700 /** Return true iff I'm a server and <b>digest</b> is equal to
701 * my identity digest. */
703 router_digest_is_me(const char *digest
)
705 routerinfo_t
*me
= router_get_my_routerinfo();
706 if (!me
|| memcmp(me
->identity_digest
, digest
, DIGEST_LEN
))
711 /** A wrapper around router_digest_is_me(). */
713 router_is_me(routerinfo_t
*router
)
715 return router_digest_is_me(router
->identity_digest
);
718 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
720 router_fingerprint_is_me(const char *fp
)
722 char digest
[DIGEST_LEN
];
723 if (strlen(fp
) == HEX_DIGEST_LEN
&&
724 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
725 return router_digest_is_me(digest
);
730 /** Return a routerinfo for this OR, rebuilding a fresh one if
731 * necessary. Return NULL on error, or if called on an OP. */
733 router_get_my_routerinfo(void)
735 if (!server_mode(get_options()))
738 if (!desc_routerinfo
) {
739 if (router_rebuild_descriptor(1))
742 return desc_routerinfo
;
745 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
746 * one if necessary. Return NULL on error.
749 router_get_my_descriptor(void)
751 if (!desc_routerinfo
) {
752 if (router_rebuild_descriptor(1))
755 log_fn(LOG_DEBUG
,"my desc is '%s'",desc_routerinfo
->signed_descriptor
);
756 return desc_routerinfo
->signed_descriptor
;
759 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
760 * a fresh routerinfo and signed server descriptor for this OR.
761 * Return 0 on success, -1 on error.
764 router_rebuild_descriptor(int force
)
769 int hibernating
= we_are_hibernating();
770 or_options_t
*options
= get_options();
772 if (desc_clean_since
&& !force
)
775 if (resolve_my_address(options
, &addr
, NULL
) < 0) {
776 log_fn(LOG_WARN
,"options->Address didn't resolve into an IP.");
780 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
781 ri
->address
= tor_dup_addr(addr
);
782 ri
->nickname
= tor_strdup(options
->Nickname
);
784 ri
->or_port
= options
->ORPort
;
785 ri
->dir_port
= options
->DirPort
;
786 ri
->published_on
= time(NULL
);
787 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
788 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
789 if (crypto_pk_get_digest(ri
->identity_pkey
, ri
->identity_digest
)<0) {
793 get_platform_str(platform
, sizeof(platform
));
794 ri
->platform
= tor_strdup(platform
);
795 ri
->bandwidthrate
= (int)options
->BandwidthRate
;
796 ri
->bandwidthburst
= (int)options
->BandwidthBurst
;
797 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
799 if (options
->BandwidthRate
> options
->MaxAdvertisedBandwidth
)
800 ri
->bandwidthrate
= (int)options
->MaxAdvertisedBandwidth
;
802 config_parse_addr_policy(get_options()->ExitPolicy
, &ri
->exit_policy
, -1);
803 options_append_default_exit_policy(&ri
->exit_policy
);
805 if (desc_routerinfo
) { /* inherit values */
806 ri
->is_verified
= desc_routerinfo
->is_verified
;
807 ri
->is_running
= desc_routerinfo
->is_running
;
808 ri
->is_named
= desc_routerinfo
->is_named
;
810 if (authdir_mode(options
))
811 ri
->is_verified
= ri
->is_named
= 1; /* believe in yourself */
812 if (options
->MyFamily
) {
813 smartlist_t
*family
= smartlist_create();
814 ri
->declared_family
= smartlist_create();
815 smartlist_split_string(family
, options
->MyFamily
, ",",
816 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
817 SMARTLIST_FOREACH(family
, char *, name
,
819 routerinfo_t
*member
;
820 if (!strcasecmp(name
, options
->Nickname
))
823 member
= router_get_by_nickname(name
, 1);
825 log_fn(LOG_WARN
, "I have no descriptor for the router named \"%s\" "
826 "in my declared family; I'll use the nickname verbatim, but "
827 "this may confuse clients.", name
);
828 smartlist_add(ri
->declared_family
, name
);
831 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
833 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
834 member
->identity_digest
, DIGEST_LEN
);
835 smartlist_add(ri
->declared_family
, fp
);
839 smartlist_free(family
);
841 ri
->signed_descriptor
= tor_malloc(8192);
842 if (router_dump_router_to_string(ri
->signed_descriptor
, 8192,
843 ri
, get_identity_key())<0) {
844 log_fn(LOG_WARN
, "Couldn't allocate string for descriptor.");
847 ri
->signed_descriptor_len
= strlen(ri
->signed_descriptor
);
848 crypto_digest(ri
->signed_descriptor_digest
,
849 ri
->signed_descriptor
, ri
->signed_descriptor_len
);
852 routerinfo_free(desc_routerinfo
);
853 desc_routerinfo
= ri
;
855 desc_clean_since
= time(NULL
);
856 desc_needs_upload
= 1;
860 /** Mark descriptor out of date if it's older than <b>when</b> */
862 mark_my_descriptor_dirty_if_older_than(time_t when
)
864 if (desc_clean_since
< when
)
865 mark_my_descriptor_dirty();
868 /** Call when the current descriptor is out of date. */
870 mark_my_descriptor_dirty(void)
872 desc_clean_since
= 0;
875 #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
876 /** Check whether bandwidth has changed a lot since the last time we announced
877 * bandwidth. If so, mark our descriptor dirty.*/
879 check_descriptor_bandwidth_changed(time_t now
)
881 static time_t last_changed
= 0;
883 if (!desc_routerinfo
)
886 prev
= desc_routerinfo
->bandwidthcapacity
;
887 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
888 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
891 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
892 log_fn(LOG_INFO
,"Measured bandwidth has changed; rebuilding descriptor.");
893 mark_my_descriptor_dirty();
899 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
900 * string describing the version of Tor and the operating system we're
901 * currently running on.
904 get_platform_str(char *platform
, size_t len
)
906 tor_snprintf(platform
, len
, "Tor %s on %s",
907 VERSION
, get_uname());
911 /* XXX need to audit this thing and count fenceposts. maybe
912 * refactor so we don't have to keep asking if we're
913 * near the end of maxlen?
915 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
917 /** OR only: Given a routerinfo for this router, and an identity key to sign
918 * with, encode the routerinfo as a signed server descriptor and write the
919 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
920 * failure, and the number of bytes used on success.
923 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
924 crypto_pk_env_t
*ident_key
)
926 char *onion_pkey
; /* Onion key, PEM-encoded. */
927 char *identity_pkey
; /* Identity key, PEM-encoded. */
928 char digest
[DIGEST_LEN
];
929 char published
[ISO_TIME_LEN
+1];
930 char fingerprint
[FINGERPRINT_LEN
+1];
932 char addrbuf
[INET_NTOA_BUF_LEN
];
933 size_t onion_pkeylen
, identity_pkeylen
;
937 char *bandwidth_usage
;
939 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
942 routerinfo_t
*ri_tmp
;
944 or_options_t
*options
= get_options();
946 /* Make sure the identity key matches the one in the routerinfo. */
947 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
948 log_fn(LOG_WARN
,"Tried to sign a router with a private key that didn't match router's public key!");
952 /* record our fingerprint, so we can include it in the descriptor */
953 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
954 log_fn(LOG_ERR
, "Error computing fingerprint");
958 /* PEM-encode the onion key */
959 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
960 &onion_pkey
,&onion_pkeylen
)<0) {
961 log_fn(LOG_WARN
,"write onion_pkey to string failed!");
965 /* PEM-encode the identity key key */
966 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
967 &identity_pkey
,&identity_pkeylen
)<0) {
968 log_fn(LOG_WARN
,"write identity_pkey to string failed!");
969 tor_free(onion_pkey
);
973 /* Encode the publication time. */
974 format_iso_time(published
, router
->published_on
);
976 /* How busy have we been? */
977 bandwidth_usage
= rep_hist_get_bandwidth_lines();
979 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
981 char *s
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
982 n
+= strlen("family ") + 2; /* 1 for \n, 1 for \0. */
983 family_line
= tor_malloc(n
);
984 tor_snprintf(family_line
, n
, "family %s\n", s
);
987 family_line
= tor_strdup("");
990 /* Generate the easy portion of the router descriptor. */
991 result
= tor_snprintf(s
, maxlen
,
992 "router %s %s %d 0 %d\n"
995 "opt fingerprint %s\n"
997 "bandwidth %d %d %d\n"
999 "signing-key\n%s%s%s%s",
1003 decide_to_advertise_dirport(options
, router
),
1007 stats_n_seconds_working
,
1008 (int) router
->bandwidthrate
,
1009 (int) router
->bandwidthburst
,
1010 (int) router
->bandwidthcapacity
,
1011 onion_pkey
, identity_pkey
,
1012 family_line
, bandwidth_usage
,
1013 we_are_hibernating() ? "opt hibernating 1\n" : "");
1014 tor_free(family_line
);
1015 tor_free(onion_pkey
);
1016 tor_free(identity_pkey
);
1017 tor_free(bandwidth_usage
);
1021 /* From now on, we use 'written' to remember the current length of 's'. */
1024 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1025 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n",
1026 options
->ContactInfo
);
1032 /* Write the exit policy to the end of 's'. */
1033 for (tmpe
=router
->exit_policy
; tmpe
; tmpe
=tmpe
->next
) {
1034 /* Write: "accept 1.2.3.4" */
1035 in
.s_addr
= htonl(tmpe
->addr
);
1036 tor_inet_ntoa(&in
, addrbuf
, sizeof(addrbuf
));
1037 result
= tor_snprintf(s
+written
, maxlen
-written
, "%s %s",
1038 tmpe
->policy_type
== ADDR_POLICY_ACCEPT
? "accept" : "reject",
1039 tmpe
->msk
== 0 ? "*" : addrbuf
);
1043 if (tmpe
->msk
!= 0xFFFFFFFFu
&& tmpe
->msk
!= 0) {
1044 /* Write "/255.255.0.0" */
1045 in
.s_addr
= htonl(tmpe
->msk
);
1046 tor_inet_ntoa(&in
, addrbuf
, sizeof(addrbuf
));
1047 result
= tor_snprintf(s
+written
, maxlen
-written
, "/%s", addrbuf
);
1052 if (tmpe
->prt_min
<= 1 && tmpe
->prt_max
== 65535) {
1053 /* There is no port set; write ":*" */
1054 if (written
+4 > maxlen
)
1056 strlcat(s
+written
, ":*\n", maxlen
-written
);
1058 } else if (tmpe
->prt_min
== tmpe
->prt_max
) {
1059 /* There is only one port; write ":80". */
1060 result
= tor_snprintf(s
+written
, maxlen
-written
, ":%d\n", tmpe
->prt_min
);
1065 /* There is a range of ports; write ":79-80". */
1066 result
= tor_snprintf(s
+written
, maxlen
-written
, ":%d-%d\n", tmpe
->prt_min
,
1072 if (tmpe
->msk
== 0 && tmpe
->prt_min
<= 1 && tmpe
->prt_max
== 65535)
1073 /* This was a catch-all rule, so future rules are irrelevant. */
1076 if (written
+256 > maxlen
) /* Not enough room for signature. */
1079 /* Sign the directory */
1080 strlcat(s
+written
, "router-signature\n", maxlen
-written
);
1081 written
+= strlen(s
+written
);
1083 if (router_get_router_hash(s
, digest
) < 0)
1086 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1087 digest
,ident_key
)<0) {
1088 log_fn(LOG_WARN
, "Couldn't sign router descriptor");
1091 written
+= strlen(s
+written
);
1093 if (written
+2 > maxlen
)
1095 /* include a last '\n' */
1099 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1100 cp
= s_tmp
= s_dup
= tor_strdup(s
);
1101 ri_tmp
= router_parse_entry_from_string(cp
, NULL
);
1103 log_fn(LOG_ERR
, "We just generated a router descriptor we can't parse: <<%s>>",
1108 routerinfo_free(ri_tmp
);
1114 /** Return true iff <b>s</b> is a legally valid server nickname. */
1116 is_legal_nickname(const char *s
)
1121 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
1122 strspn(s
,LEGAL_NICKNAME_CHARACTERS
)==len
;
1124 /** Return true iff <b>s</b> is a legally valid server nickname or
1125 * hex-encoded identity-key digest. */
1127 is_legal_nickname_or_hexdigest(const char *s
)
1132 return is_legal_nickname(s
);
1135 return len
== HEX_DIGEST_LEN
+1 && strspn(s
+1,HEX_CHARACTERS
)==len
-1;
1138 /** Release all resources held in router keys. */
1140 router_free_all_keys(void)
1143 crypto_free_pk_env(onionkey
);
1145 crypto_free_pk_env(lastonionkey
);
1147 crypto_free_pk_env(identitykey
);
1149 tor_mutex_free(key_lock
);
1150 if (desc_routerinfo
)
1151 routerinfo_free(desc_routerinfo
);