Make tor build on win32 again; handle locking for server
[tor.git] / src / or / router.c
blob9c263ecd2efd599dc3c633d8f84289f25f1f690a
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 #include "or.h"
7 /**
8 * \file router.c
9 * \brief OR functionality, including key maintenance, generating
10 * and uploading server descriptors, retrying OR connections.
11 **/
13 extern or_options_t options; /* command-line and config-file options */
15 /** Exposed for test.c. */ void get_platform_str(char *platform, int len);
17 /************************************************************/
19 /*****
20 * Key management: ORs only.
21 *****/
23 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
25 static tor_mutex_t *key_lock=NULL;
26 static time_t onionkey_set_at=0; /* When was onionkey last changed? */
27 static crypto_pk_env_t *onionkey=NULL;
28 static crypto_pk_env_t *lastonionkey=NULL;
29 static crypto_pk_env_t *identitykey=NULL;
31 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
32 * to update onionkey correctly, call rotate_onion_key().
34 void set_onion_key(crypto_pk_env_t *k) {
35 tor_mutex_acquire(key_lock);
36 onionkey = k;
37 onionkey_set_at = time(NULL);
38 tor_mutex_release(key_lock);
41 /** Return the current onion key. Requires that the onion key has been
42 * loaded or generated. */
43 crypto_pk_env_t *get_onion_key(void) {
44 tor_assert(onionkey);
45 return onionkey;
48 /** Return the onion key that was current before the most recent onion
49 * key rotation. If no rotation has been performed since this process
50 * started, return NULL.
52 crypto_pk_env_t *get_previous_onion_key(void) {
53 return lastonionkey;
56 void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
58 tor_assert(key && last);
59 tor_mutex_acquire(key_lock);
60 *key = crypto_pk_dup_key(onionkey);
61 if (lastonionkey)
62 *last = crypto_pk_dup_key(lastonionkey);
63 else
64 *last = NULL;
65 tor_mutex_release(key_lock);
68 /** Return the time when the onion key was last set. This is either the time
69 * when the process launched, or the time of the most recent key rotation since
70 * the process launched.
72 time_t get_onion_key_set_at(void) {
73 return onionkey_set_at;
76 /** Set the current identity key to k.
78 void set_identity_key(crypto_pk_env_t *k) {
79 identitykey = k;
82 /** Returns the current identity key; requires that the identity key has been
83 * set.
85 crypto_pk_env_t *get_identity_key(void) {
86 tor_assert(identitykey);
87 return identitykey;
90 /** Replace the previous onion key with the current onion key, and generate
91 * a new previous onion key. Immediately after calling this function,
92 * the OR should:
93 * - schedule all previous cpuworkers to shut down _after_ processing
94 * pending work. (This will cause fresh cpuworkers to be generated.)
95 * - generate and upload a fresh routerinfo.
97 void rotate_onion_key(void)
99 char fname[512];
100 crypto_pk_env_t *prkey;
101 sprintf(fname,"%s/keys/onion.key",options.DataDirectory);
102 if (!(prkey = crypto_new_pk_env())) {
103 log(LOG_ERR, "Error creating crypto environment.");
104 goto error;
106 if (crypto_pk_generate_key(prkey)) {
107 log(LOG_ERR, "Error generating onion key");
108 goto error;
110 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
111 log(LOG_ERR, "Couldn't write generated key to %s.", fname);
112 goto error;
114 tor_mutex_acquire(key_lock);
115 if (lastonionkey)
116 crypto_free_pk_env(lastonionkey);
117 log_fn(LOG_INFO, "Rotating onion key");
118 lastonionkey = onionkey;
119 set_onion_key(prkey);
120 tor_mutex_release(key_lock);
121 return;
122 error:
123 log_fn(LOG_WARN, "Couldn't rotate onion key.");
126 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
127 * create a new RSA key and save it in <b>fname</b>. Return the read/created
128 * key, or NULL on error.
130 crypto_pk_env_t *init_key_from_file(const char *fname)
132 crypto_pk_env_t *prkey = NULL;
133 FILE *file = NULL;
135 if (!(prkey = crypto_new_pk_env())) {
136 log(LOG_ERR, "Error creating crypto environment.");
137 goto error;
140 switch(file_status(fname)) {
141 case FN_DIR:
142 case FN_ERROR:
143 log(LOG_ERR, "Can't read key from %s", fname);
144 goto error;
145 case FN_NOENT:
146 log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
147 if (crypto_pk_generate_key(prkey)) {
148 log(LOG_ERR, "Error generating onion key");
149 goto error;
151 if (crypto_pk_check_key(prkey) <= 0) {
152 log(LOG_ERR, "Generated key seems invalid");
153 goto error;
155 log(LOG_INFO, "Generated key seems valid");
156 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
157 log(LOG_ERR, "Couldn't write generated key to %s.", fname);
158 goto error;
160 return prkey;
161 case FN_FILE:
162 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
163 log(LOG_ERR, "Error loading private key.");
164 goto error;
166 return prkey;
167 default:
168 tor_assert(0);
171 error:
172 if (prkey)
173 crypto_free_pk_env(prkey);
174 if (file)
175 fclose(file);
176 return NULL;
179 /** Initialize all OR private keys, and the TLS context, as necessary.
180 * On OPs, this only initializes the tls context.
182 int init_keys(void) {
183 char keydir[512];
184 char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
185 char *cp;
186 const char *tmp, *mydesc;
187 crypto_pk_env_t *prkey;
189 if (!key_lock)
190 key_lock = tor_mutex_new();
192 /* OP's don't need keys. Just initialize the TLS context.*/
193 if (!options.ORPort) {
194 tor_assert(!options.DirPort);
195 if (tor_tls_context_new(NULL, 0, NULL, 0)<0) {
196 log_fn(LOG_ERR, "Error creating TLS context for OP.");
197 return -1;
199 return 0;
201 /* Make sure DataDirectory exists, and is private. */
202 tor_assert(options.DataDirectory);
203 if (strlen(options.DataDirectory) > (512-128)) {
204 log_fn(LOG_ERR, "DataDirectory is too long.");
205 return -1;
207 if (check_private_dir(options.DataDirectory, 1)) {
208 return -1;
210 /* Check the key directory. */
211 sprintf(keydir,"%s/keys",options.DataDirectory);
212 if (check_private_dir(keydir, 1)) {
213 return -1;
215 cp = keydir + strlen(keydir); /* End of string. */
217 /* 1. Read identity key. Make it if none is found. */
218 strcpy(cp, "/identity.key");
219 log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
220 prkey = init_key_from_file(keydir);
221 if (!prkey) return -1;
222 set_identity_key(prkey);
223 /* 2. Read onion key. Make it if none is found. */
224 strcpy(cp, "/onion.key");
225 log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
226 prkey = init_key_from_file(keydir);
227 if (!prkey) return -1;
228 set_onion_key(prkey);
230 /* 3. Initialize link key and TLS context. */
231 if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
232 MAX_SSL_KEY_LIFETIME) < 0) {
233 log_fn(LOG_ERR, "Error initializing TLS context");
234 return -1;
236 /* 4. Dump router descriptor to 'router.desc' */
237 /* Must be called after keys are initialized. */
238 if (!(router_get_my_descriptor())) {
239 log_fn(LOG_ERR, "Error initializing descriptor.");
240 return -1;
242 /* We need to add our own fingerprint so it gets recognized. */
243 if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
244 log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
245 return -1;
247 tmp = mydesc = router_get_my_descriptor();
248 if (dirserv_add_descriptor(&tmp) != 1) {
249 log(LOG_ERR, "Unable to add own descriptor to directory.");
250 return -1;
252 sprintf(keydir,"%s/router.desc", options.DataDirectory);
253 log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
254 if (write_str_to_file(keydir, mydesc)) {
255 return -1;
257 /* 5. Dump fingerprint to 'fingerprint' */
258 sprintf(keydir,"%s/fingerprint", options.DataDirectory);
259 log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
260 tor_assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
261 strcpy(fingerprint, options.Nickname);
262 strcat(fingerprint, " ");
263 if (crypto_pk_get_fingerprint(get_identity_key(),
264 fingerprint+strlen(fingerprint))<0) {
265 log_fn(LOG_ERR, "Error computing fingerprint");
266 return -1;
268 strcat(fingerprint, "\n");
269 if (write_str_to_file(keydir, fingerprint))
270 return -1;
271 if(!options.DirPort)
272 return 0;
273 /* 6. [dirserver only] load approved-routers file */
274 sprintf(keydir,"%s/approved-routers", options.DataDirectory);
275 log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
276 if(dirserv_parse_fingerprint_file(keydir) < 0) {
277 log_fn(LOG_ERR, "Error loading fingerprints");
278 return -1;
280 /* 7. [dirserver only] load old directory, if it's there */
281 sprintf(keydir,"%s/cached-directory", options.DataDirectory);
282 log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
283 cp = read_file_to_str(keydir);
284 if(!cp) {
285 log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
286 } else {
287 if(dirserv_init_from_directory_string(cp) < 0) {
288 log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
289 free(cp);
290 return -1;
292 free(cp);
294 /* success */
295 return 0;
299 * Clique maintenance
302 /** OR only: try to open connections to all of the other ORs we know about.
304 void router_retry_connections(void) {
305 int i;
306 routerinfo_t *router;
307 routerlist_t *rl;
309 router_get_routerlist(&rl);
310 for (i=0;i < smartlist_len(rl->routers);i++) {
311 router = smartlist_get(rl->routers, i);
312 if(router_is_me(router))
313 continue;
314 if(!connection_exact_get_by_addr_port(router->addr,router->or_port)) {
315 /* not in the list */
316 log_fn(LOG_DEBUG,"connecting to OR %s:%u.",router->address,router->or_port);
317 connection_or_connect(router);
323 * OR descriptor generation.
326 /** My routerinfo. */
327 static routerinfo_t *desc_routerinfo = NULL;
328 /** String representation of my descriptor, signed by me. */
329 static char descriptor[8192];
331 /** OR only: try to upload our signed descriptor to all the directory servers
332 * we know about.
334 void router_upload_dir_desc_to_dirservers(void) {
335 const char *s;
337 s = router_get_my_descriptor();
338 if (!s) {
339 log_fn(LOG_WARN, "No descriptor; skipping upload");
340 return;
342 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
345 #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,accept *:20-22,accept *:53,accept *:79-81,accept *:110,accept *:143,accept *:443,accept *:873,accept *:993,accept *:995,accept *:1024-65535,reject *:*"
347 /** Set the exit policy on <b>router</b> to match the exit policy in the
348 * current configuration file. If the exit policy doesn't have a catch-all
349 * rule, then append the default exit policy as well.
351 static void router_add_exit_policy_from_config(routerinfo_t *router) {
352 struct exit_policy_t *ep;
353 struct config_line_t default_policy;
354 config_parse_exit_policy(options.ExitPolicy, &router->exit_policy);
356 for (ep = router->exit_policy; ep; ep = ep->next) {
357 if (ep->msk == 0 && ep->prt_min <= 1 && ep->prt_max >= 65535) {
358 /* if exitpolicy includes a *:* line, then we're done. */
359 return;
363 /* Else, append the default exitpolicy. */
364 default_policy.key = NULL;
365 default_policy.value = DEFAULT_EXIT_POLICY;
366 default_policy.next = NULL;
367 config_parse_exit_policy(&default_policy, &router->exit_policy);
370 /** OR only: Return false if my exit policy says to allow connection to
371 * conn. Else return true.
373 int router_compare_to_my_exit_policy(connection_t *conn)
375 tor_assert(desc_routerinfo);
376 tor_assert(conn->addr); /* make sure it's resolved to something. this
377 way we can't get a 'maybe' below. */
379 return router_compare_addr_to_exit_policy(conn->addr, conn->port,
380 desc_routerinfo->exit_policy);
384 /** Return true iff <b>router</b> has the same nickname as this OR. (For an
385 * OP, always returns false.)
387 int router_is_me(routerinfo_t *router)
389 tor_assert(router);
390 return options.Nickname && !strcasecmp(router->nickname, options.Nickname);
393 /** Return a routerinfo for this OR, rebuilding a fresh one if
394 * necessary. Return NULL on error, or if called on an OP. */
395 routerinfo_t *router_get_my_routerinfo(void)
397 if (!options.ORPort)
398 return NULL;
400 if (!desc_routerinfo) {
401 if (router_rebuild_descriptor())
402 return NULL;
404 return desc_routerinfo;
407 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
408 * one if necessary. Return NULL on error.
410 const char *router_get_my_descriptor(void) {
411 if (!desc_routerinfo) {
412 if (router_rebuild_descriptor())
413 return NULL;
415 log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
416 return descriptor;
419 /** Rebuild a fresh routerinfo and signed server descriptor for this
420 * OR. Return 0 on success, -1 on error.
422 int router_rebuild_descriptor(void) {
423 routerinfo_t *ri;
424 struct in_addr addr;
425 char platform[256];
426 if (!tor_inet_aton(options.Address, &addr)) {
427 log_fn(LOG_ERR, "options.Address didn't hold an IP.");
428 return -1;
431 ri = tor_malloc_zero(sizeof(routerinfo_t));
432 ri->address = tor_strdup(options.Address);
433 ri->nickname = tor_strdup(options.Nickname);
434 ri->addr = (uint32_t) ntohl(addr.s_addr);
435 ri->or_port = options.ORPort;
436 ri->socks_port = options.SocksPort;
437 ri->dir_port = options.DirPort;
438 ri->published_on = time(NULL);
439 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
440 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
441 get_platform_str(platform, sizeof(platform));
442 ri->platform = tor_strdup(platform);
443 ri->bandwidthrate = options.BandwidthRate;
444 ri->bandwidthburst = options.BandwidthBurst;
445 ri->exit_policy = NULL; /* zero it out first */
446 router_add_exit_policy_from_config(ri);
447 if (desc_routerinfo)
448 routerinfo_free(desc_routerinfo);
449 desc_routerinfo = ri;
450 if (router_dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
451 log_fn(LOG_WARN, "Couldn't dump router to string.");
452 return -1;
454 if (ri->dir_port)
455 ri->is_trusted_dir = 1;
456 return 0;
459 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
460 * string describing the version of Tor and the operating system we're
461 * currently running on.
463 void get_platform_str(char *platform, int len)
465 snprintf(platform, len-1, "Tor %s on %s", VERSION, get_uname());
466 platform[len-1] = '\0';
467 return;
470 /* XXX need to audit this thing and count fenceposts. maybe
471 * refactor so we don't have to keep asking if we're
472 * near the end of maxlen?
474 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
476 /** OR only: Given a routerinfo for this router, and an identity key to sign
477 * with, encode the routerinfo as a signed server descriptor and write the
478 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
479 * failure, and the number of bytes used on success.
481 int router_dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
482 crypto_pk_env_t *ident_key) {
483 char *onion_pkey; /* Onion key, PEM-encoded. */
484 char *identity_pkey; /* Identity key, PEM-encoded. */
485 char digest[20];
486 char signature[128];
487 char published[32];
488 struct in_addr in;
489 int onion_pkeylen, identity_pkeylen;
490 int written;
491 int result=0;
492 struct exit_policy_t *tmpe;
493 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
494 char *s_tmp, *s_dup;
495 const char *cp;
496 routerinfo_t *ri_tmp;
497 #endif
499 /* Make sure the identity key matches the one in the routerinfo. */
500 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
501 log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
502 return -1;
505 /* PEM-encode the onion key */
506 if(crypto_pk_write_public_key_to_string(router->onion_pkey,
507 &onion_pkey,&onion_pkeylen)<0) {
508 log_fn(LOG_WARN,"write onion_pkey to string failed!");
509 return -1;
512 /* PEM-encode the identity key key */
513 if(crypto_pk_write_public_key_to_string(router->identity_pkey,
514 &identity_pkey,&identity_pkeylen)<0) {
515 log_fn(LOG_WARN,"write identity_pkey to string failed!");
516 tor_free(onion_pkey);
517 return -1;
520 /* Encode the publication time. */
521 strftime(published, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router->published_on));
523 /* Generate the easy portion of the router descriptor. */
524 result = snprintf(s, maxlen,
525 "router %s %s %d %d %d\n"
526 "platform %s\n"
527 "published %s\n"
528 "bandwidth %d %d\n"
529 "onion-key\n%s"
530 "signing-key\n%s",
531 router->nickname,
532 router->address,
533 router->or_port,
534 router->socks_port,
535 router->dir_port,
536 router->platform,
537 published,
538 (int) router->bandwidthrate,
539 (int) router->bandwidthburst,
540 onion_pkey, identity_pkey);
542 tor_free(onion_pkey);
543 tor_free(identity_pkey);
545 if(result < 0 || result >= maxlen) {
546 /* apparently different glibcs do different things on snprintf error.. so check both */
547 return -1;
549 /* From now on, we use 'written' to remember the current length of 's'. */
550 written = result;
552 /* Write the exit policy to the end of 's'. */
553 for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
554 in.s_addr = htonl(tmpe->addr);
555 /* Write: "accept 1.2.3.4" */
556 result = snprintf(s+written, maxlen-written, "%s %s",
557 tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
558 tmpe->msk == 0 ? "*" : inet_ntoa(in));
559 if(result < 0 || result+written > maxlen) {
560 /* apparently different glibcs do different things on snprintf error.. so check both */
561 return -1;
563 written += result;
564 if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
565 /* Write "/255.255.0.0" */
566 in.s_addr = htonl(tmpe->msk);
567 result = snprintf(s+written, maxlen-written, "/%s", inet_ntoa(in));
568 if (result<0 || result+written > maxlen)
569 return -1;
570 written += result;
572 if (tmpe->prt_min == 0 && tmpe->prt_max == 65535) {
573 /* There is no port set; write ":*" */
574 if (written > maxlen-4)
575 return -1;
576 strcat(s+written, ":*\n");
577 written += 3;
578 } else if (tmpe->prt_min == tmpe->prt_max) {
579 /* There is only one port; write ":80". */
580 result = snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
581 if (result<0 || result+written > maxlen)
582 return -1;
583 written += result;
584 } else {
585 /* There is a range of ports; write ":79-80". */
586 result = snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
587 tmpe->prt_max);
588 if (result<0 || result+written > maxlen)
589 return -1;
590 written += result;
592 } /* end for */
593 if (written > maxlen-256) /* Not enough room for signature. */
594 return -1;
596 /* Sign the directory */
597 strcat(s+written, "router-signature\n");
598 written += strlen(s+written);
599 s[written] = '\0';
600 if (router_get_router_hash(s, digest) < 0)
601 return -1;
603 if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
604 log_fn(LOG_WARN, "Error signing digest");
605 return -1;
607 strcat(s+written, "-----BEGIN SIGNATURE-----\n");
608 written += strlen(s+written);
609 if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
610 log_fn(LOG_WARN, "Couldn't base64-encode signature");
611 return -1;
613 written += strlen(s+written);
614 strcat(s+written, "-----END SIGNATURE-----\n");
615 written += strlen(s+written);
617 if (written > maxlen-2)
618 return -1;
619 /* include a last '\n' */
620 s[written] = '\n';
621 s[written+1] = 0;
623 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
624 cp = s_tmp = s_dup = tor_strdup(s);
625 ri_tmp = router_parse_entry_from_string(cp, NULL);
626 if (!ri_tmp) {
627 log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
629 return -1;
631 free(s_dup);
632 routerinfo_free(ri_tmp);
633 #endif
635 return written+1;
639 Local Variables:
640 mode:c
641 indent-tabs-mode:nil
642 c-basic-offset:2
643 End: