Forward port changelog
[tor.git] / src / or / routerparse.c
blob07ecf44cd4108c176073f31ff7335c4289362c61
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char routerparse_c_id[] = "$Id$";
8 /**
9 * \file routerparse.c
11 * \brief Code to parse and validate router descriptors and directories.
12 **/
14 #include "or.h"
16 /****************************************************************************/
18 /** Enumeration of possible token types. The ones starting with K_
19 * correspond to directory 'keywords'. _UNRECOGNIZED is for an
20 * unrecognized keyword; _ERR is an error in the tokenizing process,
21 * _EOF is an end-of-file marker, and _NIL is used to encode
22 * not-a-token.
24 typedef enum {
25 K_ACCEPT,
26 K_DIRECTORY_SIGNATURE,
27 K_RECOMMENDED_SOFTWARE,
28 K_REJECT,
29 K_ROUTER,
30 K_SIGNED_DIRECTORY,
31 K_SIGNING_KEY,
32 K_ONION_KEY,
33 K_ROUTER_SIGNATURE,
34 K_PUBLISHED,
35 K_RUNNING_ROUTERS,
36 K_ROUTER_STATUS,
37 K_PLATFORM,
38 K_OPT,
39 K_BANDWIDTH,
40 K_PORTS,
41 K_DIRCACHEPORT,
42 K_CONTACT,
43 K_NETWORK_STATUS,
44 K_UPTIME,
45 K_DIR_SIGNING_KEY,
46 K_FAMILY,
47 _UNRECOGNIZED,
48 _ERR,
49 _EOF,
50 _NIL
51 } directory_keyword;
53 /** Structure to hold a single directory token.
55 * We parse a directory by breaking it into "tokens", each consisting
56 * of a keyword, a line full of arguments, and a binary object. The
57 * arguments and object are both optional, depending on the keyword
58 * type.
60 typedef struct directory_token_t {
61 directory_keyword tp; /**< Type of the token. */
62 int n_args; /**< Number of elements in args */
63 char **args; /**< Array of arguments from keyword line. */
64 char *object_type; /**< -----BEGIN [object_type]-----*/
65 size_t object_size; /**< Bytes in object_body */
66 char *object_body; /**< Contents of object, base64-decoded. */
67 crypto_pk_env_t *key; /**< For public keys only. */
68 const char *error; /**< For _ERR tokens only. */
69 } directory_token_t;
71 /* ********************************************************************** */
73 /** We use a table of rules to decide how to parse each token type. */
75 /** Rules for how many arguments a keyword can take. */
76 typedef enum {
77 NO_ARGS, /**< (1) no arguments, ever */
78 ARGS, /**< (2) a list of arguments separated by spaces */
79 CONCAT_ARGS, /**< or (3) the rest of the line, treated as a single argument. */
80 } arg_syntax;
82 /** Rules for whether the keyword needs an object. */
83 typedef enum {
84 NO_OBJ, /**< (1) no object, ever */
85 NEED_OBJ, /**< (2) object is required */
86 NEED_KEY, /**< (3) object is required, and must be a public key. */
87 OBJ_OK, /**< or (4) object is optional. */
88 } obj_syntax;
90 /** Rules for where a keyword can appear. */
91 typedef enum {
92 ANY = 0, /**< Appears in router descriptor or in directory sections. */
93 DIR_ONLY, /**< Appears only in directory. */
94 RTR_ONLY, /**< Appears only in router descriptor or runningrouters */
95 } where_syntax;
97 /** Table mapping keywords to token value and to argument rules. */
98 static struct {
99 const char *t; int v; arg_syntax s; obj_syntax os; where_syntax ws;
100 } token_table[] = {
101 { "accept", K_ACCEPT, ARGS, NO_OBJ, RTR_ONLY },
102 { "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ,DIR_ONLY},
103 { "reject", K_REJECT, ARGS, NO_OBJ, RTR_ONLY },
104 { "router", K_ROUTER, ARGS, NO_OBJ, RTR_ONLY },
105 { "recommended-software",K_RECOMMENDED_SOFTWARE,ARGS, NO_OBJ, DIR_ONLY },
106 { "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ, DIR_ONLY },
107 { "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
108 { "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
109 { "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ,RTR_ONLY },
110 { "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ, DIR_ONLY },
111 { "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ, DIR_ONLY },
112 { "ports", K_PORTS, ARGS, NO_OBJ, RTR_ONLY },
113 { "bandwidth", K_BANDWIDTH, ARGS, NO_OBJ, RTR_ONLY },
114 { "platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ, RTR_ONLY },
115 { "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ, ANY },
116 { "opt", K_OPT, CONCAT_ARGS, OBJ_OK, ANY },
117 { "dircacheport", K_DIRCACHEPORT, ARGS, NO_OBJ, RTR_ONLY },
118 { "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ, ANY },
119 { "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ, DIR_ONLY },
120 { "uptime", K_UPTIME, ARGS, NO_OBJ, RTR_ONLY },
121 { "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK, DIR_ONLY },
122 { "family", K_FAMILY, ARGS, NO_OBJ, RTR_ONLY },
123 { NULL, -1, NO_ARGS, NO_OBJ, ANY }
126 /* static function prototypes */
127 static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
128 static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
129 static int router_get_hash_impl(const char *s, char *digest,
130 const char *start_str, const char *end_str);
131 static void token_free(directory_token_t *tok);
132 static smartlist_t *find_all_exitpolicy(smartlist_t *s);
133 static directory_token_t *find_first_by_keyword(smartlist_t *s,
134 directory_keyword keyword);
135 static int tokenize_string(const char *start, const char *end,
136 smartlist_t *out, int is_dir);
137 static directory_token_t *get_next_token(const char **s, where_syntax where);
138 static int check_directory_signature(const char *digest,
139 directory_token_t *tok,
140 crypto_pk_env_t *pkey,
141 crypto_pk_env_t *declared_key);
142 static crypto_pk_env_t *find_dir_signing_key(const char *str);
143 /* static */ int is_obsolete_version(const char *myversion,
144 const char *versionlist);
146 /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
147 * <b>s</b>. Return 0 on success, nonzero on failure.
149 int router_get_dir_hash(const char *s, char *digest)
151 return router_get_hash_impl(s,digest,
152 "signed-directory","\ndirectory-signature");
155 /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
156 * <b>s</b>. Return 0 on success, nonzero on failure.
158 int router_get_router_hash(const char *s, char *digest)
160 return router_get_hash_impl(s,digest,
161 "router ","\nrouter-signature");
164 /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
165 * string in <b>s</b>. Return 0 on success, nonzero on failure.
167 int router_get_runningrouters_hash(const char *s, char *digest)
169 return router_get_hash_impl(s,digest,
170 "network-status","\ndirectory-signature");
174 * Find the first instance of "recommended-software ...\n" at the start of
175 * a line; return a newly allocated string containing the "..." portion.
176 * Return NULL if no such instance was found.
178 static char *
179 get_recommended_software_from_directory(const char *str)
181 #define REC "recommended-software "
182 const char *cp = str, *eol;
183 size_t len = strlen(REC);
184 cp = str;
185 if (strcmpstart(str, REC)==0) {
186 cp += len;
187 } else {
188 cp = strstr(str, "\n"REC);
189 if (!cp)
190 return NULL;
191 cp += len+1;
193 eol = strchr(cp, '\n');
194 if (!eol)
195 return NULL;
196 return tor_strndup(cp, eol-cp);
197 #undef REC
200 /** Return 1 if <b>myversion</b> is not in <b>versionlist</b>, and if at least
201 * one version of Tor on <b>versionlist</b> is newer than <b>myversion</b>.
202 * Otherwise return 0.
203 * (versionlist is a comma-separated list of version strings,
204 * optionally prefixed with "Tor". Versions that can't be parsed are
205 * ignored.) */
206 /* static */ int is_obsolete_version(const char *myversion,
207 const char *versionlist) {
208 const char *vl;
209 tor_version_t mine, other;
210 int found_newer = 0, r, ret;
211 static int warned_too_new=0;
212 smartlist_t *version_sl;
214 vl = versionlist;
216 log_fn(LOG_DEBUG,"Checking whether version '%s' is in '%s'", myversion, versionlist);
218 if (tor_version_parse(myversion, &mine)) {
219 log_fn(LOG_ERR, "I couldn't parse my own version (%s)", myversion);
220 tor_assert(0);
222 version_sl = smartlist_create();
223 smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
225 SMARTLIST_FOREACH(version_sl, const char *, cp, {
226 if (!strcmpstart(cp, "Tor "))
227 cp += 4;
229 if (tor_version_parse(cp, &other)) {
230 /* Couldn't parse other; it can't be a match. */
231 } else {
232 r = tor_version_compare(&mine, &other);
233 if (r==0) {
234 ret = 0;
235 goto done;
236 } else if (r<0) {
237 found_newer = 1;
242 if (!found_newer) {
243 if (!warned_too_new) {
244 log(LOG_WARN, "This version of Tor (%s) is newer than any on the recommended list (%s)",
245 myversion, versionlist);
246 warned_too_new=1;
248 ret = 0;
249 } else {
250 ret = 1;
253 done:
254 SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
255 smartlist_free(version_sl);
256 return ret;
259 /* Return 0 if myversion is supported; else log a message and return
260 * -1 (or exit if ignoreversions is false) */
261 int check_software_version_against_directory(const char *directory,
262 int ignoreversion)
264 char *v;
265 v = get_recommended_software_from_directory(directory);
266 if (!v) {
267 log_fn(LOG_WARN, "No recommended-versions string found in directory");
268 return -1;
270 if (!is_obsolete_version(VERSION, v)) {
271 tor_free(v);
272 return 0;
274 log(ignoreversion ? LOG_WARN : LOG_ERR,
275 "You are running Tor version %s, which will not work with this network.\n"
276 "Please use %s%s.",
277 VERSION, strchr(v,',') ? "one of " : "", v);
278 tor_free(v);
280 if (ignoreversion) {
281 log(LOG_WARN, "IgnoreVersion is set. If it breaks, we told you so.");
282 return -1;
283 } else {
284 fflush(0);
285 tor_cleanup();
286 exit(0);
287 return -1; /* never reached */
291 /** Parse a directory from <b>str</b> and, when done, store the
292 * resulting routerlist in *<b>dest</b>, freeing the old value if
293 * necessary.
295 * If <b>pkey</b> is provided, we check the directory signature with pkey.
297 * If <b>check_version</b> is non-zero, then examine the
298 * Recommended-versions * line in the directory, and warn or quit
299 * as needed.
301 * If <b>write_to_cache</b> is non-zero, then store this directory in
302 * memory and/or disk as well.
304 int /* Should be static; exposed for unit tests */
305 router_parse_routerlist_from_directory(const char *str,
306 routerlist_t **dest,
307 crypto_pk_env_t *pkey,
308 int check_version,
309 int write_to_cache)
311 directory_token_t *tok;
312 char digest[DIGEST_LEN];
313 routerlist_t *new_dir = NULL;
314 char *versions = NULL;
315 smartlist_t *good_nickname_list = NULL;
316 time_t published_on;
317 int i, r;
318 const char *end, *cp;
319 smartlist_t *tokens = NULL;
320 char dirnickname[MAX_NICKNAME_LEN+1];
321 crypto_pk_env_t *declared_key = NULL;
323 if (router_get_dir_hash(str, digest)) {
324 log_fn(LOG_WARN, "Unable to compute digest of directory");
325 goto err;
327 log_fn(LOG_DEBUG,"Received directory hashes to %s",hex_str(digest,4));
329 /* Check signature first, before we try to tokenize. */
330 cp = str;
331 while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
332 cp = end;
333 if (cp == str || !cp) {
334 log_fn(LOG_WARN, "No signature found on directory."); goto err;
336 ++cp;
337 tokens = smartlist_create();
338 if (tokenize_string(cp,strchr(cp,'\0'),tokens,1)) {
339 log_fn(LOG_WARN, "Error tokenizing directory signature"); goto err;
341 if (smartlist_len(tokens) != 1) {
342 log_fn(LOG_WARN, "Unexpected number of tokens in signature"); goto err;
344 tok=smartlist_get(tokens,0);
345 if (tok->tp != K_DIRECTORY_SIGNATURE) {
346 log_fn(LOG_WARN,"Expected a single directory signature"); goto err;
348 declared_key = find_dir_signing_key(str);
349 if (check_directory_signature(digest, tok, pkey, declared_key)<0)
350 goto err;
352 /* now we know tok->n_args == 1, so it's safe to access tok->args[0] */
353 if (!is_legal_nickname(tok->args[0])) {
354 log_fn(LOG_WARN, "Directory nickname '%s' is misformed", tok->args[0]);
355 goto err;
357 strlcpy(dirnickname, tok->args[0], sizeof(dirnickname));
359 SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
360 smartlist_free(tokens);
361 tokens = NULL;
363 /* Now that we know the signature is okay, check the version. */
364 if (check_version)
365 check_software_version_against_directory(str, get_options()->IgnoreVersion);
367 /* Now try to parse the first part of the directory. */
368 if ((end = strstr(str,"\nrouter "))) {
369 ++end;
370 } else if ((end = strstr(str, "\ndirectory-signature"))) {
371 ++end;
372 } else {
373 end = str + strlen(str);
376 tokens = smartlist_create();
377 if (tokenize_string(str,end,tokens,1)) {
378 log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
380 if (smartlist_len(tokens) < 1) {
381 log_fn(LOG_WARN, "Impossibly short directory header"); goto err;
383 if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
384 log_fn(LOG_WARN, "Unrecognized keyword \"%s\" in directory header; can't parse directory.",
385 tok->args[0]);
386 goto err;
389 tok = smartlist_get(tokens,0);
390 if (tok->tp != K_SIGNED_DIRECTORY) {
391 log_fn(LOG_WARN, "Directory doesn't start with signed-directory.");
392 goto err;
395 if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
396 log_fn(LOG_WARN, "Missing published time on directory.");
397 goto err;
399 tor_assert(tok->n_args == 1);
401 if (parse_iso_time(tok->args[0], &published_on) < 0) {
402 goto err;
405 /* Now that we know the signature is okay, and we have a
406 * publication time, cache the directory. */
407 if (!get_options()->AuthoritativeDir && write_to_cache)
408 dirserv_set_cached_directory(str, published_on, 0);
410 if (!(tok = find_first_by_keyword(tokens, K_RECOMMENDED_SOFTWARE))) {
411 log_fn(LOG_WARN, "Missing recommended-software line from directory.");
412 goto err;
414 if (tok->n_args > 1) {
415 log_fn(LOG_WARN, "Invalid recommended-software line");
416 goto err;
418 versions = tok->n_args ? tor_strdup(tok->args[0]) : tor_strdup("");
420 /* Prefer router-status, then running-routers. */
421 if (!(tok = find_first_by_keyword(tokens, K_ROUTER_STATUS))) {
422 if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
423 log_fn(LOG_WARN,
424 "Missing running-routers/router-status line from directory.");
425 goto err;
429 good_nickname_list = smartlist_create();
430 for (i=0; i<tok->n_args; ++i) {
431 smartlist_add(good_nickname_list, tok->args[i]);
433 tok->n_args = 0; /* Don't free the strings in good_nickname_list yet. */
435 /* Read the router list from s, advancing s up past the end of the last
436 * router. */
437 str = end;
438 if (router_parse_list_from_string(&str, &new_dir,
439 good_nickname_list,
440 tok->tp==K_RUNNING_ROUTERS,
441 published_on)) {
442 log_fn(LOG_WARN, "Error reading routers from directory");
443 goto err;
446 /* Determine if my routerinfo is considered verified. */
448 static int have_warned_about_unverified_status = 0;
449 routerinfo_t *me = router_get_my_routerinfo();
450 if (me) {
451 if (router_update_status_from_smartlist(me,
452 published_on, good_nickname_list, tok->tp==K_RUNNING_ROUTERS)==1 &&
453 me->is_verified == 0 && !have_warned_about_unverified_status) {
454 log_fn(LOG_WARN,"Dirserver '%s' lists your server as unverified. Please consider sending your identity fingerprint to the tor-ops.", dirnickname);
455 have_warned_about_unverified_status = 1;
460 new_dir->software_versions = versions; versions = NULL;
461 new_dir->published_on = published_on;
463 SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
464 smartlist_free(tokens);
465 tokens = NULL;
467 if (*dest)
468 routerlist_free(*dest);
469 *dest = new_dir;
471 r = 0;
472 goto done;
473 err:
474 r = -1;
475 if (new_dir)
476 routerlist_free(new_dir);
477 tor_free(versions);
478 done:
479 if (declared_key) crypto_free_pk_env(declared_key);
480 if (tokens) {
481 SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
482 smartlist_free(tokens);
484 if (good_nickname_list) {
485 SMARTLIST_FOREACH(good_nickname_list, char *, n, tor_free(n));
486 smartlist_free(good_nickname_list);
488 return r;
491 /* DOCDOC */
492 running_routers_t *
493 router_parse_runningrouters(const char *str, int write_to_cache)
495 char digest[DIGEST_LEN];
496 running_routers_t *new_list = NULL;
497 directory_token_t *tok;
498 time_t published_on;
499 int i;
500 crypto_pk_env_t *declared_key = NULL;
501 smartlist_t *tokens = NULL;
503 if (router_get_runningrouters_hash(str, digest)) {
504 log_fn(LOG_WARN, "Unable to compute digest of directory");
505 goto err;
507 tokens = smartlist_create();
508 if (tokenize_string(str,str+strlen(str),tokens,1)) {
509 log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
511 if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
512 log_fn(LOG_WARN, "Unrecognized keyword '%s'; can't parse running-routers",
513 tok->args[0]);
514 goto err;
516 tok = smartlist_get(tokens,0);
517 if (tok->tp != K_NETWORK_STATUS) {
518 log_fn(LOG_WARN, "Network-status starts with wrong token");
519 goto err;
522 if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
523 log_fn(LOG_WARN, "Missing published time on directory.");
524 goto err;
526 tor_assert(tok->n_args == 1);
527 if (parse_iso_time(tok->args[0], &published_on) < 0) {
528 goto err;
531 /* Now that we know the signature is okay, and we have a
532 * publication time, cache the list. */
533 if (!get_options()->AuthoritativeDir && write_to_cache)
534 dirserv_set_cached_directory(str, published_on, 1);
536 if (!(tok = find_first_by_keyword(tokens, K_ROUTER_STATUS))) {
537 if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
538 log_fn(LOG_WARN,
539 "Missing running-routers/router-status line from directory.");
540 goto err;
544 new_list = tor_malloc_zero(sizeof(running_routers_t));
545 new_list->published_on = published_on;
546 new_list->running_routers = smartlist_create();
547 new_list->is_running_routers_format = (tok->tp == K_RUNNING_ROUTERS);
548 for (i=0;i<tok->n_args;++i) {
549 smartlist_add(new_list->running_routers, tok->args[i]);
551 tok->n_args = 0; /* Don't free the elements of tok->args. */
553 if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
554 log_fn(LOG_WARN, "Missing signature on running-routers");
555 goto err;
557 declared_key = find_dir_signing_key(str);
558 if (check_directory_signature(digest, tok, NULL, declared_key) < 0)
559 goto err;
561 goto done;
562 err:
563 if (new_list) {
564 running_routers_free(new_list);
565 new_list = NULL;
567 done:
568 if (declared_key) crypto_free_pk_env(declared_key);
569 if (tokens) {
570 SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
571 smartlist_free(tokens);
573 return new_list;
576 /** Given a directory or running-routers string in <b>str</b>, try to
577 * find the its dir-signing-key token (if any). If this token is
578 * present, extract and return the key. Return NULL on failure. */
579 static crypto_pk_env_t *find_dir_signing_key(const char *str)
581 const char *cp;
582 directory_token_t *tok;
583 crypto_pk_env_t *key = NULL;
585 /* Is there a dir-signing-key in the directory? */
586 cp = strstr(str, "\nopt dir-signing-key");
587 if (!cp)
588 cp = strstr(str, "\ndir-signing-key");
589 if (!cp)
590 return NULL;
591 ++cp; /* Now cp points to the start of the token. */
593 tok = get_next_token(&cp, DIR_ONLY);
594 if (!tok) {
595 log_fn(LOG_WARN, "Unparseable dir-signing-key token");
596 return NULL;
598 if (tok->tp != K_DIR_SIGNING_KEY) {
599 log_fn(LOG_WARN, "Dir-signing-key token did not parse as expected");
600 return NULL;
603 if (tok->key) {
604 key = tok->key;
605 tok->key = NULL; /* steal reference. */
606 } else if (tok->n_args >= 1) {
607 key = crypto_pk_DER64_decode_public_key(tok->args[0]);
608 if (!key) {
609 log_fn(LOG_WARN, "Unparseable dir-signing-key argument");
610 return NULL;
612 } else {
613 log_fn(LOG_WARN, "Dir-signing-key token contained no key");
614 return NULL;
617 token_free(tok);
618 return key;
621 /** Return true iff <b>key</b> is allowed to sign directories.
623 static int dir_signing_key_is_trusted(crypto_pk_env_t *key)
625 char digest[DIGEST_LEN];
626 if (!key) return 0;
627 if (crypto_pk_get_digest(key, digest) < 0) {
628 log_fn(LOG_WARN, "Error computing dir-signing-key digest");
629 return 0;
631 if (!router_digest_is_trusted_dir(digest)) {
632 log_fn(LOG_WARN, "Listed dir-signing-key is not trusted");
633 return 0;
635 return 1;
638 /** Check whether the K_DIRECTORY_SIGNATURE token in <b>tok</b> has a
639 * good signature for <b>digest</b>.
641 * If <b>declared_key</b> is set, the directory has declared what key
642 * was used to sign it, so we will use that key only if it is an
643 * authoritative directory signing key.
645 * Otherwise, if pkey is provided, try to use it.
647 * (New callers should always use <b>declared_key</b> when possible;
648 * <b>pkey is only for debugging.)
650 static int check_directory_signature(const char *digest,
651 directory_token_t *tok,
652 crypto_pk_env_t *pkey,
653 crypto_pk_env_t *declared_key)
655 char signed_digest[PK_BYTES];
656 crypto_pk_env_t *_pkey = NULL;
658 if (tok->n_args != 1) {
659 log_fn(LOG_WARN, "Too many or too few arguments to directory-signature");
660 return -1;
663 if (declared_key) {
664 if (dir_signing_key_is_trusted(declared_key))
665 _pkey = declared_key;
667 if (!_pkey && pkey) {
668 /* pkey provided for debugging purposes */
669 _pkey = pkey;
671 if (!_pkey) {
672 log_fn(LOG_WARN, "Found directory in old (before 0.0.9pre3) format--rejecting.");
673 return -1;
676 if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
677 log_fn(LOG_WARN, "Bad object type or length on directory signature");
678 return -1;
681 tor_assert(_pkey);
683 if (crypto_pk_public_checksig(_pkey, signed_digest, tok->object_body, 128)
684 != 20) {
685 log_fn(LOG_WARN, "Error reading directory: invalid signature.");
686 return -1;
688 log_fn(LOG_DEBUG,"Signed directory hash starts %s", hex_str(signed_digest,4));
689 if (memcmp(digest, signed_digest, 20)) {
690 log_fn(LOG_WARN, "Error reading directory: signature does not match.");
691 return -1;
693 return 0;
696 /** Given a string *<b>s</b> containing a concatenated sequence of router
697 * descriptors, parses them and stores the result in *<b>dest</b>. If
698 * good_nickname_list is provided, then routers are marked as
699 * running/nonrunning and verified/unverified based on their status in the
700 * list. Otherwise, all routers are marked running and verified. Advances
701 * *s to a point immediately following the last router entry. Returns 0 on
702 * success and -1 on failure.
705 router_parse_list_from_string(const char **s, routerlist_t **dest,
706 smartlist_t *good_nickname_list,
707 int rr_format, time_t published_on)
709 routerinfo_t *router;
710 smartlist_t *routers;
711 const char *end;
713 tor_assert(s);
714 tor_assert(*s);
716 routers = smartlist_create();
718 while (1) {
719 *s = eat_whitespace(*s);
720 /* Don't start parsing the rest of *s unless it contains a router. */
721 if (strcmpstart(*s, "router ")!=0)
722 break;
723 if ((end = strstr(*s+1, "\nrouter "))) {
724 end++;
725 } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
726 end++;
727 } else {
728 end = *s+strlen(*s);
731 router = router_parse_entry_from_string(*s, end);
732 *s = end;
733 if (!router) {
734 log_fn(LOG_WARN, "Error reading router; skipping");
735 continue;
738 if (!good_nickname_list) {
739 router->is_running = 1; /* start out assuming all dirservers are up */
740 router->is_verified = 1;
741 router->status_set_at = time(NULL);
743 smartlist_add(routers, router);
744 // log_fn(LOG_DEBUG,"just added router #%d.",smartlist_len(routers));
747 if (good_nickname_list) {
748 SMARTLIST_FOREACH(good_nickname_list, const char *, cp,
749 routers_update_status_from_entry(routers, published_on,
750 cp, rr_format));
753 if (*dest)
754 routerlist_free(*dest);
755 *dest = tor_malloc_zero(sizeof(routerlist_t));
756 (*dest)->routers = routers;
758 return 0;
761 /** Helper function: reads a single router entry from *<b>s</b> ...
762 * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
763 * returns NULL.
765 routerinfo_t *router_parse_entry_from_string(const char *s,
766 const char *end) {
767 routerinfo_t *router = NULL;
768 char signed_digest[128];
769 char digest[128];
770 smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
771 directory_token_t *tok;
772 int t;
773 int ports_set, bw_set;
775 if (!end) {
776 end = s + strlen(s);
779 if (router_get_router_hash(s, digest) < 0) {
780 log_fn(LOG_WARN, "Couldn't compute router hash.");
781 return NULL;
783 tokens = smartlist_create();
784 if (tokenize_string(s,end,tokens,0)) {
785 log_fn(LOG_WARN, "Error tokeninzing router descriptor."); goto err;
788 if (smartlist_len(tokens) < 2) {
789 log_fn(LOG_WARN, "Impossibly short router descriptor.");
790 goto err;
792 if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
793 log_fn(LOG_WARN, "Unrecognized keyword '%s'; skipping descriptor.",
794 tok->args[0]);
795 goto err;
798 tok = smartlist_get(tokens,0);
799 if (tok->tp != K_ROUTER) {
800 log_fn(LOG_WARN,"Entry does not start with \"router\"");
801 goto err;
804 router = tor_malloc_zero(sizeof(routerinfo_t));
805 ports_set = bw_set = 0;
807 if (tok->n_args == 2 || tok->n_args == 5 || tok->n_args == 6) {
808 router->nickname = tor_strdup(tok->args[0]);
809 if (!is_legal_nickname(router->nickname)) {
810 log_fn(LOG_WARN,"Router nickname is invalid");
811 goto err;
813 router->address = tor_strdup(tok->args[1]);
814 router->addr = 0;
816 if (tok->n_args >= 5) {
817 router->or_port = (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
818 router->dir_port = (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
819 ports_set = 1;
821 } else {
822 log_fn(LOG_WARN,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
823 goto err;
826 tok = find_first_by_keyword(tokens, K_PORTS);
827 if (tok && ports_set) {
828 log_fn(LOG_WARN,"Redundant ports line");
829 goto err;
830 } else if (tok) {
831 if (tok->n_args != 3) {
832 log_fn(LOG_WARN,"Wrong # of arguments to \"ports\"");
833 goto err;
835 router->or_port = (uint16_t) tor_parse_long(tok->args[0],10,0,65535,NULL,NULL);
836 router->dir_port = (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
837 ports_set = 1;
840 tok = find_first_by_keyword(tokens, K_DIRCACHEPORT);
841 if (tok) {
842 if (router->dir_port)
843 log_fn(LOG_WARN,"Redundant dircacheport line");
844 if (tok->n_args != 1) {
845 log_fn(LOG_WARN,"Wrong # of arguments to \"dircacheport\"");
846 goto err;
848 router->dir_port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,NULL,NULL);
851 tok = find_first_by_keyword(tokens, K_BANDWIDTH);
852 if (tok && bw_set) {
853 log_fn(LOG_WARN,"Redundant bandwidth line");
854 goto err;
855 } else if (tok) {
856 if (tok->n_args < 3) {
857 /* XXXX Once 0.0.7 is *really* dead, restore this warning to its old form*/
858 log_fn(LOG_WARN,"Not enough arguments to \"bandwidth\": must be an obsolete server. Rejecting one server (nickname '%s').", router->nickname);
859 goto err;
861 router->bandwidthrate = tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
862 router->bandwidthburst = tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
863 router->bandwidthcapacity = tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
864 bw_set = 1;
867 if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
868 if (tok->n_args != 1) {
869 log_fn(LOG_WARN, "Unrecognized number of args on K_UPTIME; skipping.");
870 } else {
871 router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
875 if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
876 log_fn(LOG_WARN, "Missing published time"); goto err;
878 tor_assert(tok->n_args == 1);
879 if (parse_iso_time(tok->args[0], &router->published_on) < 0)
880 goto err;
882 if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
883 log_fn(LOG_WARN, "Missing onion key"); goto err;
885 if (crypto_pk_keysize(tok->key) != PK_BYTES) {
886 log_fn(LOG_WARN, "Wrong size on onion key: %d bits!",
887 crypto_pk_keysize(tok->key)*8);
888 goto err;
890 router->onion_pkey = tok->key;
891 tok->key = NULL; /* Prevent free */
893 if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
894 log_fn(LOG_WARN, "Missing identity key"); goto err;
896 if (crypto_pk_keysize(tok->key) != PK_BYTES) {
897 log_fn(LOG_WARN, "Wrong size on identity key: %d bits!",
898 crypto_pk_keysize(tok->key)*8);
899 goto err;
901 router->identity_pkey = tok->key;
902 tok->key = NULL; /* Prevent free */
903 if (crypto_pk_get_digest(router->identity_pkey,router->identity_digest)) {
904 log_fn(LOG_WARN, "Couldn't calculate key digest"); goto err;
907 if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
908 router->platform = tor_strdup(tok->args[0]);
911 exit_policy_tokens = find_all_exitpolicy(tokens);
912 SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
913 if (router_add_exit_policy(router,t)<0) {
914 log_fn(LOG_WARN,"Error in exit policy"); goto err;}
917 if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
918 int i;
919 router->declared_family = smartlist_create();
920 for (i=0;i<tok->n_args;++i) {
921 if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
922 log_fn(LOG_WARN, "Illegal nickname '%s' in family line", tok->args[i]);
923 goto err;
925 smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
929 if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
930 log_fn(LOG_WARN, "Missing router signature"); goto err;
932 if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
933 log_fn(LOG_WARN, "Bad object type or length on router signature");
934 goto err;
936 if ((t=crypto_pk_public_checksig(router->identity_pkey, signed_digest,
937 tok->object_body, 128)) != 20) {
938 log_fn(LOG_WARN, "Invalid signature %d",t); goto err;
940 if (memcmp(digest, signed_digest, 20)) {
941 log_fn(LOG_WARN, "Mismatched signature"); goto err;
944 if (!ports_set) {
945 log_fn(LOG_WARN,"No ports declared; failing."); goto err;
947 if (!bw_set) {
948 log_fn(LOG_WARN,"No bandwidth declared; failing."); goto err;
950 if (!router->or_port) {
951 log_fn(LOG_WARN,"or_port unreadable or 0. Failing.");
952 goto err;
954 if (!router->bandwidthrate) {
955 log_fn(LOG_WARN,"bandwidthrate unreadable or 0. Failing.");
956 goto err;
958 if (!router->platform) {
959 router->platform = tor_strdup("<unknown>");
962 // log_fn(LOG_DEBUG,"or_port %d, dir_port %d, bandwidthrate %u, bandwidthburst %u.",
963 // router->or_port, router->dir_port,
964 // (unsigned) router->bandwidthrate, (unsigned) router->bandwidthburst);
966 goto done;
967 return router;
969 err:
970 routerinfo_free(router);
971 router = NULL;
972 done:
973 if (tokens) {
974 SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
975 smartlist_free(tokens);
977 if (exit_policy_tokens) {
978 smartlist_free(exit_policy_tokens);
980 return router;
983 /** Parse the exit policy in the string <b>s</b> and return it.
985 addr_policy_t *
986 router_parse_addr_policy_from_string(const char *s)
988 directory_token_t *tok = NULL;
989 const char *cp;
990 char *tmp;
991 addr_policy_t *r;
992 size_t len, idx;
994 /* *s might not end with \n, so we need to extend it with one. */
995 len = strlen(s);
996 cp = tmp = tor_malloc(len+2);
997 for (idx = 0; idx < len; ++idx) {
998 tmp[idx] = tolower(s[idx]);
1000 tmp[len]='\n';
1001 tmp[len+1]='\0';
1002 tok = get_next_token(&cp, RTR_ONLY);
1003 if (tok->tp == _ERR) {
1004 log_fn(LOG_WARN, "Error reading exit policy: %s", tok->error);
1005 goto err;
1007 if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
1008 log_fn(LOG_WARN, "Expected 'accept' or 'reject'.");
1009 goto err;
1012 /* Now that we've gotten an exit policy, add it to the router. */
1013 r = router_parse_addr_policy(tok);
1014 goto done;
1015 err:
1016 r = NULL;
1017 done:
1018 tor_free(tmp);
1019 token_free(tok);
1020 return r;
1024 router_add_exit_policy_from_string(routerinfo_t *router, const char *s)
1026 addr_policy_t *newe, *tmpe;
1027 newe = router_parse_addr_policy_from_string(s);
1028 if (!newe)
1029 return -1;
1030 for (tmpe = router->exit_policy; tmpe; tmpe=tmpe->next)
1032 tmpe->next = newe;
1034 return 0;
1037 static int
1038 router_add_exit_policy(routerinfo_t *router,directory_token_t *tok)
1040 addr_policy_t *newe, **tmpe;
1041 newe = router_parse_addr_policy(tok);
1042 if (!newe)
1043 return -1;
1044 for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
1046 *tmpe = newe;
1048 return 0;
1051 /** Given a K_ACCEPT or K_REJECT token and a router, create and return
1052 * a new exit_policy_t corresponding to the token. */
1053 static addr_policy_t *
1054 router_parse_addr_policy(directory_token_t *tok) {
1056 addr_policy_t *newe;
1057 struct in_addr in;
1058 char *arg, *address;
1060 tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
1062 if (tok->n_args != 1)
1063 return NULL;
1064 arg = tok->args[0];
1066 newe = tor_malloc_zero(sizeof(addr_policy_t));
1068 newe->string = tor_malloc(8+strlen(arg));
1069 /* XXX eventually, use the code from router.c:727 to generate this */
1070 tor_snprintf(newe->string, 8+strlen(arg), "%s %s",
1071 (tok->tp == K_REJECT) ? "reject" : "accept", arg);
1072 newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
1073 : ADDR_POLICY_ACCEPT;
1075 if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
1076 &newe->prt_min, &newe->prt_max))
1077 goto policy_read_failed;
1079 in.s_addr = htonl(newe->addr);
1080 address = tor_strdup(inet_ntoa(in));
1081 // in.s_addr = htonl(newe->msk);
1082 // log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
1083 // newe->policy_type == ADDR_POLICY_REJECT ? "reject" : "accept",
1084 // address, inet_ntoa(in), newe->prt_min, newe->prt_max);
1085 tor_free(address);
1087 return newe;
1089 policy_read_failed:
1090 tor_assert(newe->string);
1091 log_fn(LOG_WARN,"Couldn't parse line '%s'. Dropping", newe->string);
1092 tor_free(newe->string);
1093 tor_free(newe);
1094 return NULL;
1097 void
1098 assert_addr_policy_ok(addr_policy_t *t)
1100 addr_policy_t *t2;
1101 while (t) {
1102 tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
1103 t->policy_type == ADDR_POLICY_ACCEPT);
1104 tor_assert(t->prt_min <= t->prt_max);
1105 t2 = router_parse_addr_policy_from_string(t->string);
1106 tor_assert(t2);
1107 tor_assert(t2->policy_type == t->policy_type);
1108 tor_assert(t2->addr == t->addr);
1109 tor_assert(t2->msk == t->msk);
1110 tor_assert(t2->prt_min == t->prt_min);
1111 tor_assert(t2->prt_max == t->prt_max);
1112 tor_assert(!strcmp(t2->string, t->string));
1113 tor_assert(t2->next == NULL);
1114 addr_policy_free(t2);
1116 t = t->next;
1122 * Low-level tokenizer for router descriptors and directories.
1125 /** Free all resources allocated for <b>tok</b> */
1126 static void
1127 token_free(directory_token_t *tok)
1129 int i;
1130 tor_assert(tok);
1131 if (tok->args) {
1132 for (i = 0; i < tok->n_args; ++i) {
1133 tor_free(tok->args[i]);
1135 tor_free(tok->args);
1137 tor_free(tok->object_type);
1138 tor_free(tok->object_body);
1139 if (tok->key)
1140 crypto_free_pk_env(tok->key);
1141 tor_free(tok);
1144 /** Helper function: read the next token from *s, advance *s to the end
1145 * of the token, and return the parsed token. If 'where' is DIR_ONLY
1146 * or RTR_ONLY, reject all tokens of the wrong type.
1148 static directory_token_t *
1149 get_next_token(const char **s, where_syntax where) {
1150 const char *next, *obstart;
1151 int i, done, allocated, is_opt;
1152 directory_token_t *tok;
1153 arg_syntax a_syn;
1154 obj_syntax o_syn = NO_OBJ;
1156 #define RET_ERR(msg) \
1157 do { if (tok) token_free(tok); \
1158 tok = tor_malloc_zero(sizeof(directory_token_t));\
1159 tok->tp = _ERR; \
1160 tok->error = msg; \
1161 goto done_tokenizing; } while (0)
1163 tok = tor_malloc_zero(sizeof(directory_token_t));
1164 tok->tp = _ERR;
1166 *s = eat_whitespace(*s);
1167 if (!**s) {
1168 tok->tp = _EOF;
1169 return tok;
1171 next = find_whitespace(*s);
1172 if (!next) {
1173 tok->error = "Unexpected EOF"; return tok;
1175 /* It's a keyword... but which one? */
1176 is_opt = !strncmp("opt", *s, next-*s);
1177 if (is_opt) {
1178 *s = eat_whitespace(next);
1179 next = NULL;
1180 if (**s)
1181 next = find_whitespace(*s);
1182 if (!**s || !next) {
1183 RET_ERR("opt without keyword");
1186 for (i = 0; token_table[i].t ; ++i) {
1187 if (!strncmp(token_table[i].t, *s, next-*s)) {
1188 /* We've found the keyword. */
1189 tok->tp = token_table[i].v;
1190 a_syn = token_table[i].s;
1191 o_syn = token_table[i].os;
1192 if (token_table[i].ws != ANY && token_table[i].ws != where) {
1193 if (where == DIR_ONLY) {
1194 RET_ERR("Found a router-only token in a directory section");
1195 } else {
1196 RET_ERR("Found a directory-only token in a router descriptor");
1199 if (a_syn == ARGS) {
1200 /* This keyword takes multiple arguments. */
1201 i = 0;
1202 done = (*next == '\n');
1203 allocated = 32;
1204 tok->args = tor_malloc(sizeof(char*)*32);
1205 *s = eat_whitespace_no_nl(next);
1206 while (**s != '\n' && !done) {
1207 next = find_whitespace(*s);
1208 if (*next == '\n')
1209 done = 1;
1210 if (i == allocated) {
1211 allocated *= 2;
1212 tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
1214 tok->args[i++] = tor_strndup(*s,next-*s);
1215 *s = eat_whitespace_no_nl(next+1);
1217 tok->n_args = i;
1218 } else if (a_syn == CONCAT_ARGS) {
1219 /* The keyword takes the line as a single argument */
1220 *s = eat_whitespace_no_nl(next);
1221 next = strchr(*s, '\n');
1222 if (!next)
1223 RET_ERR("Unexpected EOF");
1224 tok->args = tor_malloc(sizeof(char*));
1225 tok->args[0] = tor_strndup(*s,next-*s);
1226 tok->n_args = 1;
1227 *s = eat_whitespace_no_nl(next+1);
1228 } else {
1229 /* The keyword takes no arguments. */
1230 tor_assert(a_syn == NO_ARGS);
1231 *s = eat_whitespace_no_nl(next);
1232 if (**s != '\n') {
1233 RET_ERR("Unexpected arguments");
1235 tok->n_args = 0;
1236 *s = eat_whitespace_no_nl(*s+1);
1238 break;
1241 if (tok->tp == _ERR) {
1242 if (is_opt) {
1243 tok->tp = K_OPT;
1244 *s = eat_whitespace_no_nl(next);
1245 next = strchr(*s,'\n');
1246 if (!next)
1247 RET_ERR("Unexpected EOF");
1248 tok->args = tor_malloc(sizeof(char*));
1249 tok->args[0] = tor_strndup(*s,next-*s);
1250 tok->n_args = 1;
1251 *s = eat_whitespace_no_nl(next+1);
1252 o_syn = OBJ_OK;
1253 } else {
1254 tok->tp = _UNRECOGNIZED;
1255 next = strchr(*s, '\n');
1256 if (!next) {
1257 RET_ERR("Unexpected EOF");
1259 tok->args = tor_malloc(sizeof(char*));
1260 tok->args[0] = tor_strndup(*s,next-*s);
1261 tok->n_args = 1;
1262 *s = next+1;
1263 o_syn = OBJ_OK;
1266 *s = eat_whitespace(*s);
1267 if (strcmpstart(*s, "-----BEGIN ")) {
1268 goto done_tokenizing;
1270 obstart = *s;
1271 *s += 11; /* length of "-----BEGIN ". */
1272 next = strchr(*s, '\n');
1273 if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
1274 RET_ERR("Malformed object: bad begin line");
1276 tok->object_type = tor_strndup(*s, next-*s-5);
1277 *s = next+1;
1278 next = strstr(*s, "-----END ");
1279 if (!next) {
1280 RET_ERR("Malformed object: missing end line");
1282 if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
1283 if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
1284 RET_ERR("Malformed object: mismatched end line");
1285 next = strchr(next,'\n')+1;
1286 tok->key = crypto_new_pk_env();
1287 if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
1288 RET_ERR("Couldn't parse public key.");
1289 *s = next;
1290 } else {
1291 tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
1292 i = base64_decode(tok->object_body, 256, *s, next-*s);
1293 if (i<0) {
1294 RET_ERR("Malformed object: bad base64-encoded data");
1296 tok->object_size = i;
1297 *s = next + 9; /* length of "-----END ". */
1298 i = strlen(tok->object_type);
1299 if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
1300 RET_ERR("Malformed object: mismatched end tag");
1302 *s += i+6;
1304 switch (o_syn)
1306 case NO_OBJ:
1307 if (tok->object_body)
1308 RET_ERR("Unexpected object for keyword");
1309 if (tok->key)
1310 RET_ERR("Unexpected public key for keyword");
1311 break;
1312 case NEED_OBJ:
1313 if (!tok->object_body)
1314 RET_ERR("Missing object for keyword");
1315 break;
1316 case NEED_KEY:
1317 if (!tok->key)
1318 RET_ERR("Missing public key for keyword");
1319 break;
1320 case OBJ_OK:
1321 break;
1324 done_tokenizing:
1326 #if 0
1327 for (i = 0; token_table[i].t ; ++i) {
1328 if (token_table[i].v == tok->tp) {
1329 fputs(token_table[i].t, stdout);
1330 break;
1331 i = -1;
1334 if (i) {
1335 if (tok->tp == _UNRECOGNIZED) fputs("UNRECOGNIZED", stdout);
1336 if (tok->tp == _ERR) fputs("ERR",stdout);
1337 if (tok->tp == _EOF) fputs("EOF",stdout);
1338 if (tok->tp == _NIL) fputs("_NIL",stdout);
1340 for (i = 0; i < tok->n_args; ++i) {
1341 fprintf(stdout," \"%s\"", tok->args[i]);
1343 if (tok->error) { fprintf(stdout," *%s*", tok->error); }
1344 fputs("\n",stdout);
1345 #endif
1347 return tok;
1348 #undef RET_ERR
1351 /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
1352 * them to <b>out</b>. If <b>is_dir</b> is true, reject all non-directory
1353 * tokens; else reject all non-routerdescriptor tokens.
1355 static int
1356 tokenize_string(const char *start, const char *end, smartlist_t *out,
1357 int is_dir)
1359 const char **s;
1360 directory_token_t *tok = NULL;
1361 where_syntax where = is_dir ? DIR_ONLY : RTR_ONLY;
1362 s = &start;
1363 while (*s < end && (!tok || tok->tp != _EOF)) {
1364 tok = get_next_token(s, where);
1365 if (tok->tp == _ERR) {
1366 log_fn(LOG_WARN, "parse error: %s", tok->error);
1367 return -1;
1369 smartlist_add(out, tok);
1370 *s = eat_whitespace(*s);
1373 return 0;
1376 /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
1377 * NULL if no such keyword is found.
1379 static directory_token_t *
1380 find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
1382 SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
1383 return NULL;
1386 /** Return a newly allocated smartlist of all accept or reject tokens in
1387 * <b>s</b>.
1389 static smartlist_t *
1390 find_all_exitpolicy(smartlist_t *s)
1392 smartlist_t *out = smartlist_create();
1393 SMARTLIST_FOREACH(s, directory_token_t *, t,
1394 if (t->tp == K_ACCEPT || t->tp == K_REJECT)
1395 smartlist_add(out,t));
1396 return out;
1399 /** Compute the SHA digest of the substring of <b>s</b> taken from the first
1400 * occurrence of <b>start_str</b> through the first newline after the first
1401 * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
1402 * <b>digest</b>; return 0 on success.
1404 * If no such substring exists, return -1.
1406 static int router_get_hash_impl(const char *s, char *digest,
1407 const char *start_str,
1408 const char *end_str)
1410 char *start, *end;
1411 start = strstr(s, start_str);
1412 if (!start) {
1413 log_fn(LOG_WARN,"couldn't find \"%s\"",start_str);
1414 return -1;
1416 if (start != s && *(start-1) != '\n') {
1417 log_fn(LOG_WARN, "first occurrence of \"%s\" is not at the start of a line",
1418 start_str);
1419 return -1;
1421 end = strstr(start+strlen(start_str), end_str);
1422 if (!end) {
1423 log_fn(LOG_WARN,"couldn't find \"%s\"",end_str);
1424 return -1;
1426 end = strchr(end+strlen(end_str), '\n');
1427 if (!end) {
1428 log_fn(LOG_WARN,"couldn't find EOL");
1429 return -1;
1431 ++end;
1433 if (crypto_digest(digest, start, end-start)) {
1434 log_fn(LOG_WARN,"couldn't compute digest");
1435 return -1;
1438 return 0;
1441 /** Parse the Tor version of the platform string <b>platform</b>,
1442 * and compare it to the version in <b>cutoff</b>. Return 1 if
1443 * the router is at least as new as the cutoff, else return 0.
1445 int tor_version_as_new_as(const char *platform, const char *cutoff) {
1446 tor_version_t cutoff_version, router_version;
1447 char *s, *start;
1448 char tmp[128];
1450 if (tor_version_parse(cutoff, &cutoff_version)<0) {
1451 log_fn(LOG_WARN,"Bug: cutoff version '%s' unparseable.",cutoff);
1452 return 0;
1454 if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
1455 return 1;
1457 start = (char *)eat_whitespace(platform+3);
1458 if (!*start) return 0;
1459 s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
1460 if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
1461 return 0;
1462 strlcpy(tmp, start, s-start+1);
1464 if (tor_version_parse(tmp, &router_version)<0) {
1465 log_fn(LOG_INFO,"Router version '%s' unparseable.",tmp);
1466 return 1; /* be safe and say yes */
1469 return tor_version_compare(&router_version, &cutoff_version) >= 0;
1472 /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
1473 * Return 0 on success, -1 on failure. */
1474 int tor_version_parse(const char *s, tor_version_t *out)
1476 char *eos=NULL, *cp=NULL;
1477 /* Format is:
1478 * NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ -cvs ] ]
1480 tor_assert(s);
1481 tor_assert(out);
1483 memset(out, 0, sizeof(tor_version_t));
1485 /* Get major. */
1486 out->major = strtol(s,&eos,10);
1487 if (!eos || eos==s || *eos != '.') return -1;
1488 cp = eos+1;
1490 /* Get minor */
1491 out->minor = strtol(cp,&eos,10);
1492 if (!eos || eos==cp || *eos != '.') return -1;
1493 cp = eos+1;
1495 /* Get micro */
1496 out->micro = strtol(cp,&eos,10);
1497 if (!eos || eos==cp) return -1;
1498 if (!*eos) {
1499 out->status = VER_RELEASE;
1500 out->patchlevel = 0;
1501 out->cvs = IS_NOT_CVS;
1502 return 0;
1504 cp = eos;
1506 /* Get status */
1507 if (*cp == '.') {
1508 out->status = VER_RELEASE;
1509 ++cp;
1510 } else if (0==strncmp(cp, "pre", 3)) {
1511 out->status = VER_PRE;
1512 cp += 3;
1513 } else if (0==strncmp(cp, "rc", 2)) {
1514 out->status = VER_RC;
1515 cp += 2;
1516 } else {
1517 return -1;
1520 /* Get patchlevel */
1521 out->patchlevel = strtol(cp,&eos,10);
1522 if (!eos || eos==cp) return -1;
1523 cp = eos;
1525 /* Get cvs status and status tag. */
1526 if (*cp == '-' || *cp == '.')
1527 ++cp;
1528 strlcpy(out->status_tag, cp, sizeof(out->status_tag));
1529 if (0==strcmp(cp, "cvs")) {
1530 out->cvs = IS_CVS;
1531 } else {
1532 out->cvs = IS_NOT_CVS;
1535 return 0;
1538 /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
1539 * b. */
1540 int tor_version_compare(tor_version_t *a, tor_version_t *b)
1542 int i;
1543 tor_assert(a);
1544 tor_assert(b);
1545 if ((i = a->major - b->major))
1546 return i;
1547 else if ((i = a->minor - b->minor))
1548 return i;
1549 else if ((i = a->micro - b->micro))
1550 return i;
1551 else if ((i = a->status - b->status))
1552 return i;
1553 else if ((i = a->patchlevel - b->patchlevel))
1554 return i;
1556 if (a->major > 0 || a->minor > 0) {
1557 return strcmp(a->status_tag, b->status_tag);
1558 } else {
1559 return (a->cvs - b->cvs);