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().
37 void set_onion_key(crypto_pk_env_t
*k
) {
38 tor_mutex_acquire(key_lock
);
40 onionkey_set_at
= time(NULL
);
41 tor_mutex_release(key_lock
);
42 mark_my_descriptor_dirty();
45 /** Return the current onion key. Requires that the onion key has been
46 * loaded or generated. */
47 crypto_pk_env_t
*get_onion_key(void) {
52 /** Return the onion key that was current before the most recent onion
53 * key rotation. If no rotation has been performed since this process
54 * started, return NULL.
56 crypto_pk_env_t
*get_previous_onion_key(void) {
60 /** Store a copy of the current onion key into *<b>key</b>, and a copy
61 * of the most recent onion key into *<b>last</b>.
63 void dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
67 tor_mutex_acquire(key_lock
);
68 *key
= crypto_pk_dup_key(onionkey
);
70 *last
= crypto_pk_dup_key(lastonionkey
);
73 tor_mutex_release(key_lock
);
76 /** Return the time when the onion key was last set. This is either the time
77 * when the process launched, or the time of the most recent key rotation since
78 * the process launched.
80 time_t get_onion_key_set_at(void) {
81 return onionkey_set_at
;
84 /** Set the current identity key to k.
86 void set_identity_key(crypto_pk_env_t
*k
) {
90 /** Returns the current identity key; requires that the identity key has been
93 crypto_pk_env_t
*get_identity_key(void) {
94 tor_assert(identitykey
);
98 /** Return true iff the identity key has been set. */
99 int identity_key_is_set(void) {
100 return identitykey
!= NULL
;
103 /** Replace the previous onion key with the current onion key, and generate
104 * a new previous onion key. Immediately after calling this function,
106 * - schedule all previous cpuworkers to shut down _after_ processing
107 * pending work. (This will cause fresh cpuworkers to be generated.)
108 * - generate and upload a fresh routerinfo.
110 void rotate_onion_key(void)
113 char fname_prev
[512];
114 crypto_pk_env_t
*prkey
;
115 tor_snprintf(fname
,sizeof(fname
),
116 "%s/keys/secret_onion_key",get_options()->DataDirectory
);
117 tor_snprintf(fname_prev
,sizeof(fname_prev
),
118 "%s/keys/secret_onion_key.old",get_options()->DataDirectory
);
119 if (!(prkey
= crypto_new_pk_env())) {
120 log(LOG_ERR
, "Error creating crypto environment.");
123 if (crypto_pk_generate_key(prkey
)) {
124 log(LOG_ERR
, "Error generating onion key");
127 if (file_status(fname
) == FN_FILE
) {
128 if (replace_file(fname
, fname_prev
))
131 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
132 log(LOG_ERR
, "Couldn't write generated key to %s.", fname
);
135 log_fn(LOG_INFO
, "Rotating onion key");
136 tor_mutex_acquire(key_lock
);
138 crypto_free_pk_env(lastonionkey
);
139 lastonionkey
= onionkey
;
141 onionkey_set_at
= time(NULL
);
142 tor_mutex_release(key_lock
);
143 mark_my_descriptor_dirty();
146 log_fn(LOG_WARN
, "Couldn't rotate onion key.");
149 /* Read an RSA secret key key from a file that was once named fname_old,
150 * but is now named fname_new. Rename the file from old to new as needed.
152 static crypto_pk_env_t
*
153 init_key_from_file_name_changed(const char *fname_old
,
154 const char *fname_new
)
157 if (file_status(fname_new
) == FN_FILE
|| file_status(fname_old
) != FN_FILE
)
158 /* The new filename is there, or both are, or neither is. */
159 return init_key_from_file(fname_new
);
161 /* The old filename exists, and the new one doesn't. Rename and load. */
162 if (rename(fname_old
, fname_new
) < 0) {
163 log_fn(LOG_ERR
, "Couldn't rename %s to %s: %s", fname_old
, fname_new
,
167 return init_key_from_file(fname_new
);
170 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
171 * create a new RSA key and save it in <b>fname</b>. Return the read/created
172 * key, or NULL on error.
174 crypto_pk_env_t
*init_key_from_file(const char *fname
)
176 crypto_pk_env_t
*prkey
= NULL
;
179 if (!(prkey
= crypto_new_pk_env())) {
180 log(LOG_ERR
, "Error creating crypto environment.");
184 switch (file_status(fname
)) {
187 log(LOG_ERR
, "Can't read key from %s", fname
);
190 log(LOG_INFO
, "No key found in %s; generating fresh key.", fname
);
191 if (crypto_pk_generate_key(prkey
)) {
192 log(LOG_ERR
, "Error generating onion key");
195 if (crypto_pk_check_key(prkey
) <= 0) {
196 log(LOG_ERR
, "Generated key seems invalid");
199 log(LOG_INFO
, "Generated key seems valid");
200 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
201 log(LOG_ERR
, "Couldn't write generated key to %s.", fname
);
206 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
207 log(LOG_ERR
, "Error loading private key.");
217 crypto_free_pk_env(prkey
);
223 /** Initialize all OR private keys, and the TLS context, as necessary.
224 * On OPs, this only initializes the tls context.
226 int init_keys(void) {
227 /* XXX009 Two problems with how this is called:
228 * 1. It should be idempotent for servers, so we can call init_keys
229 * as much as we need to.
230 * 2. Clients should rotate their identity keys at least whenever
235 char fingerprint
[FINGERPRINT_LEN
+1];
236 char fingerprint_line
[FINGERPRINT_LEN
+MAX_NICKNAME_LEN
+3];/*nickname fp\n\0 */
238 const char *tmp
, *mydesc
, *datadir
;
239 crypto_pk_env_t
*prkey
;
241 or_options_t
*options
= get_options();
244 key_lock
= tor_mutex_new();
246 /* OP's don't need persistent keys; just make up an identity and
247 * initialize the TLS context. */
248 if (!server_mode(options
)) {
249 if (!(prkey
= crypto_new_pk_env()))
251 if (crypto_pk_generate_key(prkey
))
253 set_identity_key(prkey
);
254 /* Create a TLS context; default the client nickname to "client". */
255 if (tor_tls_context_new(get_identity_key(), 1,
256 options
->Nickname
? options
->Nickname
: "client",
257 MAX_SSL_KEY_LIFETIME
) < 0) {
258 log_fn(LOG_ERR
, "Error creating TLS context for OP.");
263 /* Make sure DataDirectory exists, and is private. */
264 datadir
= options
->DataDirectory
;
265 if (check_private_dir(datadir
, CPD_CREATE
)) {
268 /* Check the key directory. */
269 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys", datadir
);
270 if (check_private_dir(keydir
, CPD_CREATE
)) {
273 cp
= keydir
+ strlen(keydir
); /* End of string. */
275 /* 1. Read identity key. Make it if none is found. */
276 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/identity.key",datadir
);
277 tor_snprintf(keydir2
,sizeof(keydir2
),"%s/keys/secret_id_key",datadir
);
278 log_fn(LOG_INFO
,"Reading/making identity key %s...",keydir2
);
279 prkey
= init_key_from_file_name_changed(keydir
,keydir2
);
280 if (!prkey
) return -1;
281 set_identity_key(prkey
);
282 /* 2. Read onion key. Make it if none is found. */
283 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/onion.key",datadir
);
284 tor_snprintf(keydir2
,sizeof(keydir2
),"%s/keys/secret_onion_key",datadir
);
285 log_fn(LOG_INFO
,"Reading/making onion key %s...",keydir2
);
286 prkey
= init_key_from_file_name_changed(keydir
,keydir2
);
287 if (!prkey
) return -1;
288 set_onion_key(prkey
);
289 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/secret_onion_key.old",datadir
);
290 if (file_status(keydir
) == FN_FILE
) {
291 prkey
= init_key_from_file(keydir
);
293 lastonionkey
= prkey
;
296 /* 3. Initialize link key and TLS context. */
297 if (tor_tls_context_new(get_identity_key(), 1, options
->Nickname
,
298 MAX_SSL_KEY_LIFETIME
) < 0) {
299 log_fn(LOG_ERR
, "Error initializing TLS context");
302 /* 4. Dump router descriptor to 'router.desc' */
303 /* Must be called after keys are initialized. */
304 tmp
= mydesc
= router_get_my_descriptor();
306 log_fn(LOG_ERR
, "Error initializing descriptor.");
309 if (authdir_mode(options
)) {
311 /* We need to add our own fingerprint so it gets recognized. */
312 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
313 log_fn(LOG_ERR
, "Error adding own fingerprint to approved set");
316 if (dirserv_add_descriptor(&tmp
, &m
) != 1) {
317 log(LOG_ERR
, "Unable to add own descriptor to directory: %s",
318 m
?m
:"<unknown error>");
323 tor_snprintf(keydir
,sizeof(keydir
),"%s/router.desc", datadir
);
324 log_fn(LOG_INFO
,"Dumping descriptor to %s...",keydir
);
325 if (write_str_to_file(keydir
, mydesc
,0)) {
328 /* 5. Dump fingerprint to 'fingerprint' */
329 tor_snprintf(keydir
,sizeof(keydir
),"%s/fingerprint", datadir
);
330 log_fn(LOG_INFO
,"Dumping fingerprint to %s...",keydir
);
331 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 1)<0) {
332 log_fn(LOG_ERR
, "Error computing fingerprint");
335 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
336 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
337 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
338 log_fn(LOG_ERR
, "Error writing fingerprint line");
341 if (write_str_to_file(keydir
, fingerprint_line
, 0))
343 if (!authdir_mode(options
))
345 /* 6. [authdirserver only] load approved-routers file */
346 tor_snprintf(keydir
,sizeof(keydir
),"%s/approved-routers", datadir
);
347 log_fn(LOG_INFO
,"Loading approved fingerprints from %s...",keydir
);
348 if (dirserv_parse_fingerprint_file(keydir
) < 0) {
349 log_fn(LOG_ERR
, "Error loading fingerprints");
352 /* 6b. [authdirserver only] add own key to approved directories. */
353 crypto_pk_get_digest(get_identity_key(), digest
);
354 if (!router_digest_is_trusted_dir(digest
)) {
355 add_trusted_dir_server(options
->Address
, (uint16_t)options
->DirPort
, digest
);
357 /* 7. [authdirserver only] load old directory, if it's there */
358 tor_snprintf(keydir
,sizeof(keydir
),"%s/cached-directory", datadir
);
359 log_fn(LOG_INFO
,"Loading cached directory from %s...",keydir
);
360 cp
= read_file_to_str(keydir
,0);
362 log_fn(LOG_INFO
,"Cached directory %s not present. Ok.",keydir
);
364 if (dirserv_load_from_directory_string(cp
) < 0) {
365 log_fn(LOG_WARN
, "Cached directory %s is corrupt, only loaded part of it.", keydir
);
375 /* Keep track of whether we should upload our server descriptor,
376 * and what type of server we are.
379 /** Whether we can reach our ORPort from the outside. */
380 static int can_reach_or_port
= 0;
381 /** Whether we can reach our DirPort from the outside. */
382 static int can_reach_dir_port
= 0;
384 /** Return 1 if or port is known reachable; else return 0. */
385 int check_whether_orport_reachable(void) {
386 return clique_mode(get_options()) || can_reach_or_port
;
388 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
389 int check_whether_dirport_reachable(void) {
390 return !get_options()->DirPort
|| can_reach_dir_port
;
393 void consider_testing_reachability(void) {
394 routerinfo_t
*me
= router_get_my_routerinfo();
396 log_fn(LOG_WARN
,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
400 if (!check_whether_orport_reachable()) {
401 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
, 0, 1, 1);
404 if (!check_whether_dirport_reachable()) {
406 directory_initiate_command_router(me
, DIR_PURPOSE_FETCH_DIR
, 1, NULL
, NULL
, 0);
408 log_fn(LOG_NOTICE
,"Delaying checking DirPort reachability; can't build descriptor.");
413 /** Annotate that we found our ORPort reachable. */
414 void router_orport_found_reachable(void) {
415 if (!can_reach_or_port
) {
416 if (!clique_mode(get_options()))
417 log_fn(LOG_NOTICE
,"Your ORPort is reachable from the outside. Excellent. Publishing server descriptor.");
418 can_reach_or_port
= 1;
419 consider_publishable_server(time(NULL
), 1);
423 /** Annotate that we found our DirPort reachable. */
424 void router_dirport_found_reachable(void) {
425 if (!can_reach_dir_port
) {
426 log_fn(LOG_NOTICE
,"Your DirPort is reachable from the outside. Excellent.");
427 can_reach_dir_port
= 1;
431 /** Our router has just moved to a new IP. Reset stats. */
432 void server_has_changed_ip(void) {
433 stats_n_seconds_working
= 0;
434 can_reach_or_port
= 0;
435 can_reach_dir_port
= 0;
436 mark_my_descriptor_dirty();
439 /** Return true iff we believe ourselves to be an authoritative
442 int authdir_mode(or_options_t
*options
) {
443 return options
->AuthoritativeDir
!= 0;
445 /** Return true iff we try to stay connected to all ORs at once.
447 int clique_mode(or_options_t
*options
) {
448 return authdir_mode(options
);
451 /** Return true iff we are trying to be a server.
453 int server_mode(or_options_t
*options
) {
454 return (options
->ORPort
!= 0 || options
->ORBindAddress
);
457 /** Remember if we've advertised ourselves to the dirservers. */
458 static int server_is_advertised
=0;
460 /** Return true iff we have published our descriptor lately.
462 int advertised_server_mode(void) {
463 return server_is_advertised
;
466 static void set_server_advertised(int s
) {
467 server_is_advertised
= s
;
470 /** Return true iff we are trying to be a socks proxy. */
471 int proxy_mode(or_options_t
*options
) {
472 return (options
->SocksPort
!= 0 || options
->SocksBindAddress
);
475 /** Decide if we're a publishable server or just a client. We are a server if:
476 * - We have the AuthoritativeDirectory option set.
478 * - We don't have the ClientOnly option set; and
479 * - We have ORPort set; and
480 * - We believe we are reachable from the outside.
482 static int decide_if_publishable_server(time_t now
) {
483 or_options_t
*options
= get_options();
485 if (options
->ClientOnly
)
487 if (!server_mode(options
))
489 if (options
->AuthoritativeDir
)
492 return check_whether_orport_reachable();
495 void consider_publishable_server(time_t now
, int force
) {
496 if (decide_if_publishable_server(now
)) {
497 set_server_advertised(1);
498 router_rebuild_descriptor(force
);
499 router_upload_dir_desc_to_dirservers(force
);
501 set_server_advertised(0);
509 /** OR only: if in clique mode, try to open connections to all of the
510 * other ORs we know about. Otherwise, open connections to those we
511 * think are in clique mode.
513 void router_retry_connections(void) {
515 routerinfo_t
*router
;
517 or_options_t
*options
= get_options();
519 tor_assert(server_mode(options
));
521 router_get_routerlist(&rl
);
523 for (i
=0;i
< smartlist_len(rl
->routers
);i
++) {
524 router
= smartlist_get(rl
->routers
, i
);
525 if (router_is_me(router
))
527 if (!clique_mode(options
) && !router_is_clique_mode(router
))
529 if (!connection_get_by_identity_digest(router
->identity_digest
,
531 /* not in the list */
532 log_fn(LOG_DEBUG
,"connecting to OR at %s:%u.",router
->address
,router
->or_port
);
533 connection_or_connect(router
->addr
, router
->or_port
, router
->identity_digest
);
538 /** Return true iff this OR should try to keep connections open to all
540 int router_is_clique_mode(routerinfo_t
*router
) {
541 if (router_digest_is_trusted_dir(router
->identity_digest
))
547 * OR descriptor generation.
550 /** My routerinfo. */
551 static routerinfo_t
*desc_routerinfo
= NULL
;
552 /** Boolean: do we need to regenerate the above? */
553 static int desc_is_dirty
= 1;
554 /** Boolean: do we need to regenerate the above? */
555 static int desc_needs_upload
= 0;
557 /** OR only: If <b>force</b> is true, or we haven't uploaded this
558 * descriptor successfully yet, try to upload our signed descriptor to
559 * all the directory servers we know about.
561 void router_upload_dir_desc_to_dirservers(int force
) {
564 s
= router_get_my_descriptor();
566 log_fn(LOG_WARN
, "No descriptor; skipping upload");
569 if (!force
|| !desc_needs_upload
)
571 desc_needs_upload
= 0;
572 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
, s
, strlen(s
));
575 #define DEFAULT_EXIT_POLICY "reject 0.0.0.0/8,reject 169.254.0.0/16,reject 127.0.0.0/8,reject 192.168.0.0/16,reject 10.0.0.0/8,reject 172.16.0.0/12,reject *:25,reject *:119,reject *:135-139,reject *:445,reject *:1214,reject *:4661-4666,reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
577 /** Set the exit policy on <b>router</b> to match the exit policy in the
578 * current configuration file. If the exit policy doesn't have a catch-all
579 * rule, then append the default exit policy as well.
581 static void router_add_exit_policy_from_config(routerinfo_t
*router
) {
583 struct config_line_t default_policy
;
584 config_parse_addr_policy(get_options()->ExitPolicy
, &router
->exit_policy
);
586 for (ep
= router
->exit_policy
; ep
; ep
= ep
->next
) {
587 if (ep
->msk
== 0 && ep
->prt_min
<= 1 && ep
->prt_max
>= 65535) {
588 /* if exitpolicy includes a *:* line, then we're done. */
593 /* Else, append the default exitpolicy. */
594 default_policy
.key
= NULL
;
595 default_policy
.value
= (char*)DEFAULT_EXIT_POLICY
;
596 default_policy
.next
= NULL
;
597 config_parse_addr_policy(&default_policy
, &router
->exit_policy
);
600 /** OR only: Check whether my exit policy says to allow connection to
601 * conn. Return false if we accept; true if we reject.
603 int router_compare_to_my_exit_policy(connection_t
*conn
)
605 tor_assert(desc_routerinfo
);
607 /* make sure it's resolved to something. this way we can't get a
612 return router_compare_addr_to_addr_policy(conn
->addr
, conn
->port
,
613 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
617 /** Return true iff <b>router</b> has the same nickname as this OR. (For an
618 * OP, always returns false.)
620 int router_is_me(routerinfo_t
*router
)
622 routerinfo_t
*me
= router_get_my_routerinfo();
624 if (!me
|| memcmp(me
->identity_digest
, router
->identity_digest
, DIGEST_LEN
))
629 /** Return a routerinfo for this OR, rebuilding a fresh one if
630 * necessary. Return NULL on error, or if called on an OP. */
631 routerinfo_t
*router_get_my_routerinfo(void)
633 if (!server_mode(get_options()))
636 if (!desc_routerinfo
) {
637 if (router_rebuild_descriptor(1))
640 return desc_routerinfo
;
643 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
644 * one if necessary. Return NULL on error.
646 const char *router_get_my_descriptor(void) {
647 if (!desc_routerinfo
) {
648 if (router_rebuild_descriptor(1))
651 log_fn(LOG_DEBUG
,"my desc is '%s'",desc_routerinfo
->signed_descriptor
);
652 return desc_routerinfo
->signed_descriptor
;
655 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
656 * a fresh routerinfo and signed server descriptor for this OR.
657 * Return 0 on success, -1 on error.
659 int router_rebuild_descriptor(int force
) {
664 int hibernating
= we_are_hibernating();
665 or_options_t
*options
= get_options();
666 char addrbuf
[INET_NTOA_BUF_LEN
];
668 if (!desc_is_dirty
&& !force
)
671 if (resolve_my_address(options
->Address
, &addr
) < 0) {
672 log_fn(LOG_WARN
,"options->Address didn't resolve into an IP.");
676 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
677 in
.s_addr
= htonl(addr
);
678 tor_inet_ntoa(&in
, addrbuf
, sizeof(addrbuf
));
679 ri
->address
= tor_strdup(addrbuf
);
680 ri
->nickname
= tor_strdup(options
->Nickname
);
682 ri
->or_port
= options
->ORPort
;
683 ri
->dir_port
= hibernating
?
684 0 : options
->DirPort
;
685 ri
->published_on
= time(NULL
);
686 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
687 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
688 if (crypto_pk_get_digest(ri
->identity_pkey
, ri
->identity_digest
)<0) {
692 get_platform_str(platform
, sizeof(platform
));
693 ri
->platform
= tor_strdup(platform
);
694 ri
->bandwidthrate
= (int)options
->BandwidthRate
;
695 ri
->bandwidthburst
= (int)options
->BandwidthBurst
;
696 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
698 if (options
->BandwidthRate
> options
->MaxAdvertisedBandwidth
)
699 ri
->bandwidthrate
= (int)options
->MaxAdvertisedBandwidth
;
701 router_add_exit_policy_from_config(ri
);
702 if (desc_routerinfo
) /* inherit values */
703 ri
->is_verified
= desc_routerinfo
->is_verified
;
704 if (options
->MyFamily
) {
705 ri
->declared_family
= smartlist_create();
706 smartlist_split_string(ri
->declared_family
, options
->MyFamily
, ",",
707 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
709 ri
->signed_descriptor
= tor_malloc(8192);
710 if (router_dump_router_to_string(ri
->signed_descriptor
, 8192,
711 ri
, get_identity_key())<0) {
712 log_fn(LOG_WARN
, "Couldn't dump router to string.");
717 routerinfo_free(desc_routerinfo
);
718 desc_routerinfo
= ri
;
721 desc_needs_upload
= 1;
725 /** Call when the current descriptor is out of date. */
727 mark_my_descriptor_dirty(void)
732 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
733 * string describing the version of Tor and the operating system we're
734 * currently running on.
736 void get_platform_str(char *platform
, size_t len
)
738 tor_snprintf(platform
, len
, "Tor %s on %s",
739 VERSION
, get_uname());
743 /* XXX need to audit this thing and count fenceposts. maybe
744 * refactor so we don't have to keep asking if we're
745 * near the end of maxlen?
747 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
749 /** OR only: Given a routerinfo for this router, and an identity key to sign
750 * with, encode the routerinfo as a signed server descriptor and write the
751 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
752 * failure, and the number of bytes used on success.
754 int router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
755 crypto_pk_env_t
*ident_key
) {
756 char *onion_pkey
; /* Onion key, PEM-encoded. */
757 char *identity_pkey
; /* Identity key, PEM-encoded. */
761 char fingerprint
[FINGERPRINT_LEN
+1];
763 char addrbuf
[INET_NTOA_BUF_LEN
];
764 size_t onion_pkeylen
, identity_pkeylen
;
768 char *bandwidth_usage
;
770 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
773 routerinfo_t
*ri_tmp
;
776 /* Make sure the identity key matches the one in the routerinfo. */
777 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
778 log_fn(LOG_WARN
,"Tried to sign a router with a private key that didn't match router's public key!");
782 /* record our fingerprint, so we can include it in the descriptor */
783 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
784 log_fn(LOG_ERR
, "Error computing fingerprint");
788 /* PEM-encode the onion key */
789 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
790 &onion_pkey
,&onion_pkeylen
)<0) {
791 log_fn(LOG_WARN
,"write onion_pkey to string failed!");
795 /* PEM-encode the identity key key */
796 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
797 &identity_pkey
,&identity_pkeylen
)<0) {
798 log_fn(LOG_WARN
,"write identity_pkey to string failed!");
799 tor_free(onion_pkey
);
803 /* Encode the publication time. */
804 format_iso_time(published
, router
->published_on
);
806 /* How busy have we been? */
807 bandwidth_usage
= rep_hist_get_bandwidth_lines();
809 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
811 char *s
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
812 n
+= strlen("opt family ") + 2; /* 1 for \n, 1 for \0. */
813 family_line
= tor_malloc(n
);
814 tor_snprintf(family_line
, n
, "opt family %s\n", s
);
817 family_line
= tor_strdup("");
820 /* Generate the easy portion of the router descriptor. */
821 result
= tor_snprintf(s
, maxlen
,
822 "router %s %s %d 0 %d\n"
825 "opt fingerprint %s\n"
827 "bandwidth %d %d %d\n"
829 "signing-key\n%s%s%s%s",
833 check_whether_dirport_reachable
? router
->dir_port
: 0,
837 stats_n_seconds_working
,
838 (int) router
->bandwidthrate
,
839 (int) router
->bandwidthburst
,
840 (int) router
->bandwidthcapacity
,
841 onion_pkey
, identity_pkey
,
842 family_line
, bandwidth_usage
,
843 we_are_hibernating() ? "opt hibernating 1\n" : "");
844 tor_free(family_line
);
845 tor_free(onion_pkey
);
846 tor_free(identity_pkey
);
847 tor_free(bandwidth_usage
);
851 /* From now on, we use 'written' to remember the current length of 's'. */
854 if (get_options()->ContactInfo
&& strlen(get_options()->ContactInfo
)) {
855 result
= tor_snprintf(s
+written
,maxlen
-written
, "opt contact %s\n",
856 get_options()->ContactInfo
);
862 /* Write the exit policy to the end of 's'. */
863 for (tmpe
=router
->exit_policy
; tmpe
; tmpe
=tmpe
->next
) {
864 in
.s_addr
= htonl(tmpe
->addr
);
865 /* Write: "accept 1.2.3.4" */
866 tor_inet_ntoa(&in
, addrbuf
, sizeof(addrbuf
));
867 result
= tor_snprintf(s
+written
, maxlen
-written
, "%s %s",
868 tmpe
->policy_type
== ADDR_POLICY_ACCEPT
? "accept" : "reject",
869 tmpe
->msk
== 0 ? "*" : addrbuf
);
873 if (tmpe
->msk
!= 0xFFFFFFFFu
&& tmpe
->msk
!= 0) {
874 /* Write "/255.255.0.0" */
875 tor_inet_ntoa(&in
, addrbuf
, sizeof(addrbuf
));
876 in
.s_addr
= htonl(tmpe
->msk
);
877 result
= tor_snprintf(s
+written
, maxlen
-written
, "/%s", addrbuf
);
882 if (tmpe
->prt_min
<= 1 && tmpe
->prt_max
== 65535) {
883 /* There is no port set; write ":*" */
884 if (written
+4 > maxlen
)
886 strlcat(s
+written
, ":*\n", maxlen
-written
);
888 } else if (tmpe
->prt_min
== tmpe
->prt_max
) {
889 /* There is only one port; write ":80". */
890 result
= tor_snprintf(s
+written
, maxlen
-written
, ":%d\n", tmpe
->prt_min
);
895 /* There is a range of ports; write ":79-80". */
896 result
= tor_snprintf(s
+written
, maxlen
-written
, ":%d-%d\n", tmpe
->prt_min
,
902 if (tmpe
->msk
== 0 && tmpe
->prt_min
<= 1 && tmpe
->prt_max
== 65535)
903 /* This was a catch-all rule, so future rules are irrelevant. */
906 if (written
+256 > maxlen
) /* Not enough room for signature. */
909 /* Sign the directory */
910 strlcat(s
+written
, "router-signature\n", maxlen
-written
);
911 written
+= strlen(s
+written
);
913 if (router_get_router_hash(s
, digest
) < 0)
916 if (crypto_pk_private_sign(ident_key
, signature
, digest
, 20) < 0) {
917 log_fn(LOG_WARN
, "Error signing digest");
920 strlcat(s
+written
, "-----BEGIN SIGNATURE-----\n", maxlen
-written
);
921 written
+= strlen(s
+written
);
922 if (base64_encode(s
+written
, maxlen
-written
, signature
, 128) < 0) {
923 log_fn(LOG_WARN
, "Couldn't base64-encode signature");
926 written
+= strlen(s
+written
);
927 strlcat(s
+written
, "-----END SIGNATURE-----\n", maxlen
-written
);
928 written
+= strlen(s
+written
);
930 if (written
+2 > maxlen
)
932 /* include a last '\n' */
936 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
937 cp
= s_tmp
= s_dup
= tor_strdup(s
);
938 ri_tmp
= router_parse_entry_from_string(cp
, NULL
);
940 log_fn(LOG_ERR
, "We just generated a router descriptor we can't parse: <<%s>>",
945 routerinfo_free(ri_tmp
);
951 /** Return true iff <b>s</b> is a legally valid server nickname. */
952 int is_legal_nickname(const char *s
)
957 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
958 strspn(s
,LEGAL_NICKNAME_CHARACTERS
)==len
;
960 /** Return true iff <b>s</b> is a legally valid server nickname or
961 * hex-encoded identity-key digest. */
962 int is_legal_nickname_or_hexdigest(const char *s
)
967 return is_legal_nickname(s
);
970 return len
== HEX_DIGEST_LEN
+1 && strspn(s
+1,HEX_CHARACTERS
)==len
-1;
973 /** Release all resources held in router keys. */
974 void router_free_all_keys(void)
977 crypto_free_pk_env(onionkey
);
979 crypto_free_pk_env(lastonionkey
);
981 crypto_free_pk_env(identitykey
);
983 tor_mutex_free(key_lock
);
985 routerinfo_free(desc_routerinfo
);