clean up a few more log entries
[tor.git] / src / or / router.c
blob6bcc678d52fb4e4f855b4808a1049d5a7faf88c3
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 #include "or.h"
10 /**
11 * \file router.c
12 * \brief OR functionality, including key maintenance, generating
13 * and uploading server descriptors, retrying OR connections.
14 **/
16 extern long stats_n_seconds_working;
18 /* Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
20 /************************************************************/
22 /*****
23 * Key management: ORs only.
24 *****/
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);
39 onionkey = k;
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) {
48 tor_assert(onionkey);
49 return onionkey;
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) {
57 return lastonionkey;
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)
65 tor_assert(key);
66 tor_assert(last);
67 tor_mutex_acquire(key_lock);
68 *key = crypto_pk_dup_key(onionkey);
69 if (lastonionkey)
70 *last = crypto_pk_dup_key(lastonionkey);
71 else
72 *last = NULL;
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) {
87 identitykey = k;
90 /** Returns the current identity key; requires that the identity key has been
91 * set.
93 crypto_pk_env_t *get_identity_key(void) {
94 tor_assert(identitykey);
95 return 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,
105 * the OR should:
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)
112 char fname[512];
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.");
121 goto error;
123 if (crypto_pk_generate_key(prkey)) {
124 log(LOG_ERR, "Error generating onion key");
125 goto error;
127 if (file_status(fname) == FN_FILE) {
128 if (replace_file(fname, fname_prev))
129 goto error;
131 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
132 log(LOG_ERR, "Couldn't write generated key to %s.", fname);
133 goto error;
135 log_fn(LOG_INFO, "Rotating onion key");
136 tor_mutex_acquire(key_lock);
137 if (lastonionkey)
138 crypto_free_pk_env(lastonionkey);
139 lastonionkey = onionkey;
140 onionkey = prkey;
141 onionkey_set_at = time(NULL);
142 tor_mutex_release(key_lock);
143 mark_my_descriptor_dirty();
144 return;
145 error:
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,
164 strerror(errno));
165 return NULL;
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;
177 FILE *file = NULL;
179 if (!(prkey = crypto_new_pk_env())) {
180 log(LOG_ERR, "Error creating crypto environment.");
181 goto error;
184 switch (file_status(fname)) {
185 case FN_DIR:
186 case FN_ERROR:
187 log(LOG_ERR, "Can't read key from %s", fname);
188 goto error;
189 case FN_NOENT:
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");
193 goto error;
195 if (crypto_pk_check_key(prkey) <= 0) {
196 log(LOG_ERR, "Generated key seems invalid");
197 goto error;
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);
202 goto error;
204 return prkey;
205 case FN_FILE:
206 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
207 log(LOG_ERR, "Error loading private key.");
208 goto error;
210 return prkey;
211 default:
212 tor_assert(0);
215 error:
216 if (prkey)
217 crypto_free_pk_env(prkey);
218 if (file)
219 fclose(file);
220 return NULL;
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
231 * their IPs change.
233 char keydir[512];
234 char keydir2[512];
235 char fingerprint[FINGERPRINT_LEN+1];
236 char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];/*nickname fp\n\0 */
237 char *cp;
238 const char *tmp, *mydesc, *datadir;
239 crypto_pk_env_t *prkey;
240 char digest[20];
241 or_options_t *options = get_options();
243 if (!key_lock)
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()))
250 return -1;
251 if (crypto_pk_generate_key(prkey))
252 return -1;
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.");
259 return -1;
261 return 0;
263 /* Make sure DataDirectory exists, and is private. */
264 datadir = options->DataDirectory;
265 if (check_private_dir(datadir, CPD_CREATE)) {
266 return -1;
268 /* Check the key directory. */
269 tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
270 if (check_private_dir(keydir, CPD_CREATE)) {
271 return -1;
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);
292 if (prkey)
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");
300 return -1;
302 /* 4. Dump router descriptor to 'router.desc' */
303 /* Must be called after keys are initialized. */
304 tmp = mydesc = router_get_my_descriptor();
305 if (!mydesc) {
306 log_fn(LOG_ERR, "Error initializing descriptor.");
307 return -1;
309 if (authdir_mode(options)) {
310 const char *m;
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");
314 return -1;
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>");
319 return -1;
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)) {
326 return -1;
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");
333 return -1;
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");
339 return -1;
341 if (write_str_to_file(keydir, fingerprint_line, 0))
342 return -1;
343 if (!authdir_mode(options))
344 return 0;
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");
350 return -1;
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);
361 if (!cp) {
362 log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
363 } else {
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);
366 tor_free(cp);
367 return 0;
369 tor_free(cp);
371 /* success */
372 return 0;
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();
395 if (!me) {
396 log_fn(LOG_WARN,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
397 return;
400 if (!check_whether_orport_reachable()) {
401 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
404 if (!check_whether_dirport_reachable()) {
405 if (me) {
406 directory_initiate_command_router(me, DIR_PURPOSE_FETCH_DIR, 1, NULL, NULL, 0);
407 } else {
408 log(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(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(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
440 * directory server.
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. We are a publishable server if:
476 * - We don't have the ClientOnly option set
477 * and
478 * - We don't have the NoPublish option set
479 * and
480 * - We have ORPort set
481 * and
482 * - We believe we are reachable from the outside; or
483 * - We have the AuthoritativeDirectory option set.
485 static int decide_if_publishable_server(time_t now) {
486 or_options_t *options = get_options();
488 if (options->ClientOnly)
489 return 0;
490 if (options->NoPublish)
491 return 0;
492 if (!server_mode(options))
493 return 0;
494 if (options->AuthoritativeDir)
495 return 1;
497 return check_whether_orport_reachable();
500 void consider_publishable_server(time_t now, int force) {
501 if (decide_if_publishable_server(now)) {
502 set_server_advertised(1);
503 router_rebuild_descriptor(force);
504 router_upload_dir_desc_to_dirservers(force);
505 } else {
506 set_server_advertised(0);
511 * Clique maintenance
514 /** OR only: if in clique mode, try to open connections to all of the
515 * other ORs we know about. Otherwise, open connections to those we
516 * think are in clique mode.
518 void router_retry_connections(void) {
519 int i;
520 routerinfo_t *router;
521 routerlist_t *rl;
522 or_options_t *options = get_options();
524 tor_assert(server_mode(options));
526 router_get_routerlist(&rl);
527 if (!rl) return;
528 for (i=0;i < smartlist_len(rl->routers);i++) {
529 router = smartlist_get(rl->routers, i);
530 if (router_is_me(router))
531 continue;
532 if (!clique_mode(options) && !router_is_clique_mode(router))
533 continue;
534 if (!connection_get_by_identity_digest(router->identity_digest,
535 CONN_TYPE_OR)) {
536 /* not in the list */
537 log_fn(LOG_DEBUG,"connecting to OR at %s:%u.",router->address,router->or_port);
538 connection_or_connect(router->addr, router->or_port, router->identity_digest);
543 /** Return true iff this OR should try to keep connections open to all
544 * other ORs. */
545 int router_is_clique_mode(routerinfo_t *router) {
546 if (router_digest_is_trusted_dir(router->identity_digest))
547 return 1;
548 return 0;
552 * OR descriptor generation.
555 /** My routerinfo. */
556 static routerinfo_t *desc_routerinfo = NULL;
557 /** Boolean: do we need to regenerate the above? */
558 static int desc_is_dirty = 1;
559 /** Boolean: do we need to regenerate the above? */
560 static int desc_needs_upload = 0;
562 /** OR only: If <b>force</b> is true, or we haven't uploaded this
563 * descriptor successfully yet, try to upload our signed descriptor to
564 * all the directory servers we know about.
566 void router_upload_dir_desc_to_dirservers(int force) {
567 const char *s;
569 s = router_get_my_descriptor();
570 if (!s) {
571 log_fn(LOG_WARN, "No descriptor; skipping upload");
572 return;
574 if (!force || !desc_needs_upload)
575 return;
576 desc_needs_upload = 0;
577 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
580 /** OR only: Check whether my exit policy says to allow connection to
581 * conn. Return false if we accept; true if we reject.
583 int router_compare_to_my_exit_policy(connection_t *conn)
585 tor_assert(desc_routerinfo);
587 /* make sure it's resolved to something. this way we can't get a
588 'maybe' below. */
589 if (!conn->addr)
590 return -1;
592 return router_compare_addr_to_addr_policy(conn->addr, conn->port,
593 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
596 /** Return true iff I'm a server and <b>digest</b> is equal to
597 * my identity digest. */
598 int router_digest_is_me(const char *digest)
600 routerinfo_t *me = router_get_my_routerinfo();
601 if (!me || memcmp(me->identity_digest, digest, DIGEST_LEN))
602 return 0;
603 return 1;
606 /** A wrapper around router_digest_is_me(). */
607 int router_is_me(routerinfo_t *router)
609 return router_digest_is_me(router->identity_digest);
612 /** Return a routerinfo for this OR, rebuilding a fresh one if
613 * necessary. Return NULL on error, or if called on an OP. */
614 routerinfo_t *router_get_my_routerinfo(void)
616 if (!server_mode(get_options()))
617 return NULL;
619 if (!desc_routerinfo) {
620 if (router_rebuild_descriptor(1))
621 return NULL;
623 return desc_routerinfo;
626 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
627 * one if necessary. Return NULL on error.
629 const char *router_get_my_descriptor(void) {
630 if (!desc_routerinfo) {
631 if (router_rebuild_descriptor(1))
632 return NULL;
634 log_fn(LOG_DEBUG,"my desc is '%s'",desc_routerinfo->signed_descriptor);
635 return desc_routerinfo->signed_descriptor;
638 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
639 * a fresh routerinfo and signed server descriptor for this OR.
640 * Return 0 on success, -1 on error.
642 int router_rebuild_descriptor(int force) {
643 routerinfo_t *ri;
644 uint32_t addr;
645 char platform[256];
646 struct in_addr in;
647 int hibernating = we_are_hibernating();
648 or_options_t *options = get_options();
649 char addrbuf[INET_NTOA_BUF_LEN];
651 if (!desc_is_dirty && !force)
652 return 0;
654 if (resolve_my_address(options, &addr) < 0) {
655 log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
656 return -1;
659 ri = tor_malloc_zero(sizeof(routerinfo_t));
660 in.s_addr = htonl(addr);
661 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
662 ri->address = tor_strdup(addrbuf);
663 ri->nickname = tor_strdup(options->Nickname);
664 ri->addr = addr;
665 ri->or_port = options->ORPort;
666 ri->dir_port = hibernating ?
667 0 : options->DirPort;
668 ri->published_on = time(NULL);
669 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
670 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
671 if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
672 routerinfo_free(ri);
673 return -1;
675 get_platform_str(platform, sizeof(platform));
676 ri->platform = tor_strdup(platform);
677 ri->bandwidthrate = (int)options->BandwidthRate;
678 ri->bandwidthburst = (int)options->BandwidthBurst;
679 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
681 if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
682 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
684 config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy);
685 config_append_default_exit_policy(&ri->exit_policy);
687 if (desc_routerinfo) /* inherit values */
688 ri->is_verified = desc_routerinfo->is_verified;
689 if (options->MyFamily) {
690 ri->declared_family = smartlist_create();
691 smartlist_split_string(ri->declared_family, options->MyFamily, ",",
692 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
694 ri->signed_descriptor = tor_malloc(8192);
695 if (router_dump_router_to_string(ri->signed_descriptor, 8192,
696 ri, get_identity_key())<0) {
697 log_fn(LOG_WARN, "Couldn't dump router to string.");
698 return -1;
701 if (desc_routerinfo)
702 routerinfo_free(desc_routerinfo);
703 desc_routerinfo = ri;
705 desc_is_dirty = 0;
706 desc_needs_upload = 1;
707 return 0;
710 /** Call when the current descriptor is out of date. */
711 void
712 mark_my_descriptor_dirty(void)
714 desc_is_dirty = 1;
717 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
718 * string describing the version of Tor and the operating system we're
719 * currently running on.
721 void get_platform_str(char *platform, size_t len)
723 tor_snprintf(platform, len, "Tor %s on %s",
724 VERSION, get_uname());
725 return;
728 /* XXX need to audit this thing and count fenceposts. maybe
729 * refactor so we don't have to keep asking if we're
730 * near the end of maxlen?
732 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
734 /** OR only: Given a routerinfo for this router, and an identity key to sign
735 * with, encode the routerinfo as a signed server descriptor and write the
736 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
737 * failure, and the number of bytes used on success.
739 int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
740 crypto_pk_env_t *ident_key) {
741 char *onion_pkey; /* Onion key, PEM-encoded. */
742 char *identity_pkey; /* Identity key, PEM-encoded. */
743 char digest[20];
744 char signature[128];
745 char published[32];
746 char fingerprint[FINGERPRINT_LEN+1];
747 struct in_addr in;
748 char addrbuf[INET_NTOA_BUF_LEN];
749 size_t onion_pkeylen, identity_pkeylen;
750 size_t written;
751 int result=0;
752 addr_policy_t *tmpe;
753 char *bandwidth_usage;
754 char *family_line;
755 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
756 char *s_tmp, *s_dup;
757 const char *cp;
758 routerinfo_t *ri_tmp;
759 #endif
761 /* Make sure the identity key matches the one in the routerinfo. */
762 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
763 log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
764 return -1;
767 /* record our fingerprint, so we can include it in the descriptor */
768 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
769 log_fn(LOG_ERR, "Error computing fingerprint");
770 return -1;
773 /* PEM-encode the onion key */
774 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
775 &onion_pkey,&onion_pkeylen)<0) {
776 log_fn(LOG_WARN,"write onion_pkey to string failed!");
777 return -1;
780 /* PEM-encode the identity key key */
781 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
782 &identity_pkey,&identity_pkeylen)<0) {
783 log_fn(LOG_WARN,"write identity_pkey to string failed!");
784 tor_free(onion_pkey);
785 return -1;
788 /* Encode the publication time. */
789 format_iso_time(published, router->published_on);
791 /* How busy have we been? */
792 bandwidth_usage = rep_hist_get_bandwidth_lines();
794 if (router->declared_family && smartlist_len(router->declared_family)) {
795 size_t n;
796 char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
797 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
798 family_line = tor_malloc(n);
799 tor_snprintf(family_line, n, "family %s\n", s);
800 tor_free(s);
801 } else {
802 family_line = tor_strdup("");
805 /* Generate the easy portion of the router descriptor. */
806 result = tor_snprintf(s, maxlen,
807 "router %s %s %d 0 %d\n"
808 "platform %s\n"
809 "published %s\n"
810 "opt fingerprint %s\n"
811 "uptime %ld\n"
812 "bandwidth %d %d %d\n"
813 "onion-key\n%s"
814 "signing-key\n%s%s%s%s",
815 router->nickname,
816 router->address,
817 router->or_port,
818 check_whether_dirport_reachable() ? router->dir_port : 0,
819 router->platform,
820 published,
821 fingerprint,
822 stats_n_seconds_working,
823 (int) router->bandwidthrate,
824 (int) router->bandwidthburst,
825 (int) router->bandwidthcapacity,
826 onion_pkey, identity_pkey,
827 family_line, bandwidth_usage,
828 we_are_hibernating() ? "opt hibernating 1\n" : "");
829 tor_free(family_line);
830 tor_free(onion_pkey);
831 tor_free(identity_pkey);
832 tor_free(bandwidth_usage);
834 if (result < 0)
835 return -1;
836 /* From now on, we use 'written' to remember the current length of 's'. */
837 written = result;
839 if (get_options()->ContactInfo && strlen(get_options()->ContactInfo)) {
840 result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
841 get_options()->ContactInfo);
842 if (result<0)
843 return -1;
844 written += result;
847 /* Write the exit policy to the end of 's'. */
848 for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
849 /* Write: "accept 1.2.3.4" */
850 in.s_addr = htonl(tmpe->addr);
851 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
852 result = tor_snprintf(s+written, maxlen-written, "%s %s",
853 tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
854 tmpe->msk == 0 ? "*" : addrbuf);
855 if (result < 0)
856 return -1;
857 written += result;
858 if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
859 /* Write "/255.255.0.0" */
860 in.s_addr = htonl(tmpe->msk);
861 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
862 result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
863 if (result<0)
864 return -1;
865 written += result;
867 if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
868 /* There is no port set; write ":*" */
869 if (written+4 > maxlen)
870 return -1;
871 strlcat(s+written, ":*\n", maxlen-written);
872 written += 3;
873 } else if (tmpe->prt_min == tmpe->prt_max) {
874 /* There is only one port; write ":80". */
875 result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
876 if (result<0)
877 return -1;
878 written += result;
879 } else {
880 /* There is a range of ports; write ":79-80". */
881 result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
882 tmpe->prt_max);
883 if (result<0)
884 return -1;
885 written += result;
887 if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
888 /* This was a catch-all rule, so future rules are irrelevant. */
889 break;
890 } /* end for */
891 if (written+256 > maxlen) /* Not enough room for signature. */
892 return -1;
894 /* Sign the directory */
895 strlcat(s+written, "router-signature\n", maxlen-written);
896 written += strlen(s+written);
897 s[written] = '\0';
898 if (router_get_router_hash(s, digest) < 0)
899 return -1;
901 if (crypto_pk_private_sign(ident_key, signature, digest, 20) < 0) {
902 log_fn(LOG_WARN, "Error signing digest");
903 return -1;
905 strlcat(s+written, "-----BEGIN SIGNATURE-----\n", maxlen-written);
906 written += strlen(s+written);
907 if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
908 log_fn(LOG_WARN, "Couldn't base64-encode signature");
909 return -1;
911 written += strlen(s+written);
912 strlcat(s+written, "-----END SIGNATURE-----\n", maxlen-written);
913 written += strlen(s+written);
915 if (written+2 > maxlen)
916 return -1;
917 /* include a last '\n' */
918 s[written] = '\n';
919 s[written+1] = 0;
921 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
922 cp = s_tmp = s_dup = tor_strdup(s);
923 ri_tmp = router_parse_entry_from_string(cp, NULL);
924 if (!ri_tmp) {
925 log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
927 return -1;
929 tor_free(s_dup);
930 routerinfo_free(ri_tmp);
931 #endif
933 return written+1;
936 /** Return true iff <b>s</b> is a legally valid server nickname. */
937 int is_legal_nickname(const char *s)
939 size_t len;
940 tor_assert(s);
941 len = strlen(s);
942 return len > 0 && len <= MAX_NICKNAME_LEN &&
943 strspn(s,LEGAL_NICKNAME_CHARACTERS)==len;
945 /** Return true iff <b>s</b> is a legally valid server nickname or
946 * hex-encoded identity-key digest. */
947 int is_legal_nickname_or_hexdigest(const char *s)
949 size_t len;
950 tor_assert(s);
951 if (*s!='$')
952 return is_legal_nickname(s);
954 len = strlen(s);
955 return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
958 /** Release all resources held in router keys. */
959 void router_free_all_keys(void)
961 if (onionkey)
962 crypto_free_pk_env(onionkey);
963 if (lastonionkey)
964 crypto_free_pk_env(lastonionkey);
965 if (identitykey)
966 crypto_free_pk_env(identitykey);
967 if (key_lock)
968 tor_mutex_free(key_lock);
969 if (desc_routerinfo)
970 routerinfo_free(desc_routerinfo);