Check for named servers when looking them up by nickname;
[tor.git] / src / or / router.c
blob5835c38aed166546e7bf48d3f2bd3dae479d118f
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
38 set_onion_key(crypto_pk_env_t *k)
40 tor_mutex_acquire(key_lock);
41 onionkey = k;
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. */
49 crypto_pk_env_t *
50 get_onion_key(void)
52 tor_assert(onionkey);
53 return onionkey;
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.
60 crypto_pk_env_t *
61 get_previous_onion_key(void)
63 return lastonionkey;
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>.
69 void
70 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
72 tor_assert(key);
73 tor_assert(last);
74 tor_mutex_acquire(key_lock);
75 *key = crypto_pk_dup_key(onionkey);
76 if (lastonionkey)
77 *last = crypto_pk_dup_key(lastonionkey);
78 else
79 *last = NULL;
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.
87 time_t
88 get_onion_key_set_at(void)
90 return onionkey_set_at;
93 /** Set the current identity key to k.
95 void
96 set_identity_key(crypto_pk_env_t *k)
98 if (identitykey)
99 crypto_free_pk_env(identitykey);
100 identitykey = k;
103 /** Returns the current identity key; requires that the identity key has been
104 * set.
106 crypto_pk_env_t *
107 get_identity_key(void)
109 tor_assert(identitykey);
110 return 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,
122 * the OR should:
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.
127 void
128 rotate_onion_key(void)
130 char fname[512];
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.");
139 goto error;
141 if (crypto_pk_generate_key(prkey)) {
142 log(LOG_ERR, "Error generating onion key");
143 goto error;
145 if (file_status(fname) == FN_FILE) {
146 if (replace_file(fname, fname_prev))
147 goto error;
149 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
150 log(LOG_ERR, "Couldn't write generated key to \"%s\".", fname);
151 goto error;
153 log_fn(LOG_INFO, "Rotating onion key");
154 tor_mutex_acquire(key_lock);
155 if (lastonionkey)
156 crypto_free_pk_env(lastonionkey);
157 lastonionkey = onionkey;
158 onionkey = prkey;
159 onionkey_set_at = time(NULL);
160 tor_mutex_release(key_lock);
161 mark_my_descriptor_dirty();
162 return;
163 error:
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,
181 strerror(errno));
182 return NULL;
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.
191 crypto_pk_env_t *
192 init_key_from_file(const char *fname)
194 crypto_pk_env_t *prkey = NULL;
195 FILE *file = NULL;
197 if (!(prkey = crypto_new_pk_env())) {
198 log(LOG_ERR, "Error creating crypto environment.");
199 goto error;
202 switch (file_status(fname)) {
203 case FN_DIR:
204 case FN_ERROR:
205 log(LOG_ERR, "Can't read key from \"%s\"", fname);
206 goto error;
207 case FN_NOENT:
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");
211 goto error;
213 if (crypto_pk_check_key(prkey) <= 0) {
214 log(LOG_ERR, "Generated key seems invalid");
215 goto error;
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);
220 goto error;
222 return prkey;
223 case FN_FILE:
224 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
225 log(LOG_ERR, "Error loading private key.");
226 goto error;
228 return prkey;
229 default:
230 tor_assert(0);
233 error:
234 if (prkey)
235 crypto_free_pk_env(prkey);
236 if (file)
237 fclose(file);
238 return NULL;
241 /** Initialize all OR private keys, and the TLS context, as necessary.
242 * On OPs, this only initializes the tls context.
245 init_keys(void)
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.
251 char keydir[512];
252 char keydir2[512];
253 char fingerprint[FINGERPRINT_LEN+1];
254 char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];/*nickname fp\n\0 */
255 char *cp;
256 const char *mydesc, *datadir;
257 crypto_pk_env_t *prkey;
258 char digest[20];
259 or_options_t *options = get_options();
261 if (!key_lock)
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()))
268 return -1;
269 if (crypto_pk_generate_key(prkey))
270 return -1;
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.");
277 return -1;
279 return 0;
281 /* Make sure DataDirectory exists, and is private. */
282 datadir = options->DataDirectory;
283 if (check_private_dir(datadir, CPD_CREATE)) {
284 return -1;
286 /* Check the key directory. */
287 tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
288 if (check_private_dir(keydir, CPD_CREATE)) {
289 return -1;
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);
310 if (prkey)
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");
318 return -1;
320 /* 4. Dump router descriptor to 'router.desc' */
321 /* Must be called after keys are initialized. */
322 mydesc = router_get_my_descriptor();
323 if (!mydesc) {
324 log_fn(LOG_ERR, "Error initializing descriptor.");
325 return -1;
327 if (authdir_mode(options)) {
328 const char *m;
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");
332 return -1;
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>");
337 return -1;
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)) {
344 return -1;
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");
351 return -1;
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");
357 return -1;
359 if (write_str_to_file(keydir, fingerprint_line, 0))
360 return -1;
361 if (!authdir_mode(options))
362 return 0;
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");
368 return -1;
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);
377 /* success */
378 return 0;
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 ||
397 can_reach_or_port;
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 ||
407 can_reach_dir_port;
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. */
413 static int
414 decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
416 if (!router->dir_port) /* short circuit the rest of the function */
417 return 0;
418 if (authdir_mode(options)) /* always publish */
419 return router->dir_port;
420 if (we_are_hibernating())
421 return 0;
422 if (!check_whether_dirport_reachable())
423 return 0;
424 if (router->bandwidthcapacity >= router->bandwidthrate) {
425 /* check if we might potentially hibernate. */
426 if (options->AccountingMax != 0)
427 return 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)
431 return 0;
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().
449 void
450 consider_testing_reachability(void)
452 routerinfo_t *me = router_get_my_routerinfo();
453 if (!me) {
454 log_fn(LOG_WARN,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
455 return;
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. */
470 void
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. */
484 void
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. */
494 void
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
504 * directory server.
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.
542 static void
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
557 * and
558 * - We don't have the NoPublish option set
559 * and
560 * - We have ORPort set
561 * and
562 * - We believe we are reachable from the outside; or
563 * - We have the AuthoritativeDirectory option set.
565 static int
566 decide_if_publishable_server(time_t now)
568 or_options_t *options = get_options();
570 if (options->ClientOnly)
571 return 0;
572 if (options->NoPublish)
573 return 0;
574 if (!server_mode(options))
575 return 0;
576 if (options->AuthoritativeDir)
577 return 1;
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.
585 void
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);
592 } else {
593 set_server_advertised(0);
598 * Clique maintenance
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
606 * have one.
608 void
609 router_retry_connections(int force)
611 int i;
612 time_t now = time(NULL);
613 routerinfo_t *router;
614 routerlist_t *rl;
615 or_options_t *options = get_options();
617 tor_assert(server_mode(options));
619 router_get_routerlist(&rl);
620 if (!rl) return;
621 for (i=0;i < smartlist_len(rl->routers);i++) {
622 router = smartlist_get(rl->routers, i);
623 if (router_is_me(router))
624 continue;
625 if (!clique_mode(options) && !router_is_clique_mode(router))
626 continue;
627 if (force ||
628 !connection_get_by_identity_digest(router->identity_digest,
629 CONN_TYPE_OR)) {
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
642 * other ORs. */
644 router_is_clique_mode(routerinfo_t *router)
646 if (router_digest_is_trusted_dir(router->identity_digest))
647 return 1;
648 return 0;
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
658 * now. */
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.
667 void
668 router_upload_dir_desc_to_dirservers(int force)
670 const char *s;
672 s = router_get_my_descriptor();
673 if (!s) {
674 log_fn(LOG_WARN, "No descriptor; skipping upload");
675 return;
677 if (!force && !desc_needs_upload)
678 return;
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
692 'maybe' below. */
693 if (!conn->addr)
694 return -1;
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))
707 return 0;
708 return 1;
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);
727 return 0;
730 /** Return a routerinfo for this OR, rebuilding a fresh one if
731 * necessary. Return NULL on error, or if called on an OP. */
732 routerinfo_t *
733 router_get_my_routerinfo(void)
735 if (!server_mode(get_options()))
736 return NULL;
738 if (!desc_routerinfo) {
739 if (router_rebuild_descriptor(1))
740 return NULL;
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.
748 const char *
749 router_get_my_descriptor(void)
751 if (!desc_routerinfo) {
752 if (router_rebuild_descriptor(1))
753 return NULL;
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)
766 routerinfo_t *ri;
767 uint32_t addr;
768 char platform[256];
769 int hibernating = we_are_hibernating();
770 or_options_t *options = get_options();
772 if (desc_clean_since && !force)
773 return 0;
775 if (resolve_my_address(options, &addr, NULL) < 0) {
776 log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
777 return -1;
780 ri = tor_malloc_zero(sizeof(routerinfo_t));
781 ri->address = tor_dup_addr(addr);
782 ri->nickname = tor_strdup(options->Nickname);
783 ri->addr = addr;
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) {
790 routerinfo_free(ri);
791 return -1;
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))
821 member = ri;
822 else
823 member = router_get_by_nickname(name, 1);
824 if (!member) {
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);
829 name = NULL;
830 } else {
831 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
832 fp[0] = '$';
833 base16_encode(fp+1,HEX_DIGEST_LEN+1,
834 member->identity_digest, DIGEST_LEN);
835 smartlist_add(ri->declared_family, fp);
837 tor_free(name);
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.");
845 return -1;
847 ri->signed_descriptor_len = strlen(ri->signed_descriptor);
848 crypto_digest(ri->signed_descriptor_digest,
849 ri->signed_descriptor, ri->signed_descriptor_len);
851 if (desc_routerinfo)
852 routerinfo_free(desc_routerinfo);
853 desc_routerinfo = ri;
855 desc_clean_since = time(NULL);
856 desc_needs_upload = 1;
857 return 0;
860 /** Mark descriptor out of date if it's older than <b>when</b> */
861 void
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. */
869 void
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.*/
878 void
879 check_descriptor_bandwidth_changed(time_t now)
881 static time_t last_changed = 0;
882 uint64_t prev, cur;
883 if (!desc_routerinfo)
884 return;
886 prev = desc_routerinfo->bandwidthcapacity;
887 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
888 if ((prev != cur && (!prev || !cur)) ||
889 cur > prev*2 ||
890 cur < prev/2) {
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();
894 last_changed = now;
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.
903 void
904 get_platform_str(char *platform, size_t len)
906 tor_snprintf(platform, len, "Tor %s on %s",
907 VERSION, get_uname());
908 return;
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];
931 struct in_addr in;
932 char addrbuf[INET_NTOA_BUF_LEN];
933 size_t onion_pkeylen, identity_pkeylen;
934 size_t written;
935 int result=0;
936 addr_policy_t *tmpe;
937 char *bandwidth_usage;
938 char *family_line;
939 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
940 char *s_tmp, *s_dup;
941 const char *cp;
942 routerinfo_t *ri_tmp;
943 #endif
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!");
949 return -1;
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");
955 return -1;
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!");
962 return -1;
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);
970 return -1;
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)) {
980 size_t n;
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);
985 tor_free(s);
986 } else {
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"
993 "platform %s\n"
994 "published %s\n"
995 "opt fingerprint %s\n"
996 "uptime %ld\n"
997 "bandwidth %d %d %d\n"
998 "onion-key\n%s"
999 "signing-key\n%s%s%s%s",
1000 router->nickname,
1001 router->address,
1002 router->or_port,
1003 decide_to_advertise_dirport(options, router),
1004 router->platform,
1005 published,
1006 fingerprint,
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);
1019 if (result < 0)
1020 return -1;
1021 /* From now on, we use 'written' to remember the current length of 's'. */
1022 written = result;
1024 if (options->ContactInfo && strlen(options->ContactInfo)) {
1025 result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
1026 options->ContactInfo);
1027 if (result<0)
1028 return -1;
1029 written += result;
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);
1040 if (result < 0)
1041 return -1;
1042 written += result;
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);
1048 if (result<0)
1049 return -1;
1050 written += result;
1052 if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
1053 /* There is no port set; write ":*" */
1054 if (written+4 > maxlen)
1055 return -1;
1056 strlcat(s+written, ":*\n", maxlen-written);
1057 written += 3;
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);
1061 if (result<0)
1062 return -1;
1063 written += result;
1064 } else {
1065 /* There is a range of ports; write ":79-80". */
1066 result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
1067 tmpe->prt_max);
1068 if (result<0)
1069 return -1;
1070 written += result;
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. */
1074 break;
1075 } /* end for */
1076 if (written+256 > maxlen) /* Not enough room for signature. */
1077 return -1;
1079 /* Sign the directory */
1080 strlcat(s+written, "router-signature\n", maxlen-written);
1081 written += strlen(s+written);
1082 s[written] = '\0';
1083 if (router_get_router_hash(s, digest) < 0)
1084 return -1;
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");
1089 return -1;
1091 written += strlen(s+written);
1093 if (written+2 > maxlen)
1094 return -1;
1095 /* include a last '\n' */
1096 s[written] = '\n';
1097 s[written+1] = 0;
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);
1102 if (!ri_tmp) {
1103 log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
1105 return -1;
1107 tor_free(s_dup);
1108 routerinfo_free(ri_tmp);
1109 #endif
1111 return written+1;
1114 /** Return true iff <b>s</b> is a legally valid server nickname. */
1116 is_legal_nickname(const char *s)
1118 size_t len;
1119 tor_assert(s);
1120 len = strlen(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)
1129 size_t len;
1130 tor_assert(s);
1131 if (*s!='$')
1132 return is_legal_nickname(s);
1134 len = strlen(s);
1135 return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
1138 /** Release all resources held in router keys. */
1139 void
1140 router_free_all_keys(void)
1142 if (onionkey)
1143 crypto_free_pk_env(onionkey);
1144 if (lastonionkey)
1145 crypto_free_pk_env(lastonionkey);
1146 if (identitykey)
1147 crypto_free_pk_env(identitykey);
1148 if (key_lock)
1149 tor_mutex_free(key_lock);
1150 if (desc_routerinfo)
1151 routerinfo_free(desc_routerinfo);