routerparse.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. /* Copyright 2001-2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file routerparse.c
  6. *
  7. * \brief Code to parse and validate router descriptors and directories.
  8. **/
  9. #include "or.h"
  10. /****************************************************************************/
  11. extern or_options_t options; /* command-line and config-file options */
  12. /** Enumeration of possible token types. The ones starting with K_
  13. * correspond to directory 'keywords'. _UNRECOGNIZED is for an
  14. * unrecognized keyword; _ERR is an error in the tokenizing process,
  15. * _EOF is an end-of-file marker, and _NIL is used to encode
  16. * not-a-token.
  17. */
  18. typedef enum {
  19. K_ACCEPT,
  20. K_DIRECTORY_SIGNATURE,
  21. K_RECOMMENDED_SOFTWARE,
  22. K_REJECT,
  23. K_ROUTER,
  24. K_SIGNED_DIRECTORY,
  25. K_SIGNING_KEY,
  26. K_ONION_KEY,
  27. K_ROUTER_SIGNATURE,
  28. K_PUBLISHED,
  29. K_RUNNING_ROUTERS,
  30. K_PLATFORM,
  31. K_OPT,
  32. K_BANDWIDTH,
  33. K_PORTS,
  34. K_DIRCACHEPORT,
  35. K_CONTACT,
  36. K_NETWORK_STATUS,
  37. K_UPTIME,
  38. K_DIR_SIGNING_KEY,
  39. K_FAMILY,
  40. _UNRECOGNIZED,
  41. _ERR,
  42. _EOF,
  43. _NIL
  44. } directory_keyword;
  45. /** Structure to hold a single directory token.
  46. *
  47. * We parse a directory by breaking it into "tokens", each consisting
  48. * of a keyword, a line full of arguments, and a binary object. The
  49. * arguments and object are both optional, depending on the keyword
  50. * type.
  51. */
  52. typedef struct directory_token_t {
  53. directory_keyword tp; /**< Type of the token. */
  54. int n_args; /**< Number of elements in args */
  55. char **args; /**< Array of arguments from keyword line. */
  56. char *object_type; /**< -----BEGIN [object_type]-----*/
  57. size_t object_size; /**< Bytes in object_body */
  58. char *object_body; /**< Contents of object, base64-decoded. */
  59. crypto_pk_env_t *key; /**< For public keys only. */
  60. char *error; /**< For _ERR tokens only. */
  61. } directory_token_t;
  62. /* ********************************************************************** */
  63. /** We use a table of rules to decide how to parse each token type. */
  64. /** Rules for how many arguments a keyword can take. */
  65. typedef enum {
  66. NO_ARGS, /**< (1) no arguments, ever */
  67. ARGS, /**< (2) a list of arguments separated by spaces */
  68. CONCAT_ARGS, /**< or (3) the rest of the line, treated as a single argument. */
  69. } arg_syntax;
  70. /** Rules for whether the keyword needs an object. */
  71. typedef enum {
  72. NO_OBJ, /**< (1) no object, ever */
  73. NEED_OBJ, /**< (2) object is required */
  74. NEED_KEY, /**< (3) object is required, and must be a public key. */
  75. OBJ_OK, /**< or (4) object is optional. */
  76. } obj_syntax;
  77. /** Rules for where a keyword can appear. */
  78. typedef enum {
  79. ANY = 0, /**< Appears in router descriptor or in directory sections. */
  80. DIR_ONLY, /**< Appears only in directory. */
  81. RTR_ONLY, /**< Appears only in router descriptor or runningrouters */
  82. } where_syntax;
  83. /** Table mapping keywords to token value and to argument rules. */
  84. static struct {
  85. char *t; int v; arg_syntax s; obj_syntax os; where_syntax ws;
  86. } token_table[] = {
  87. { "accept", K_ACCEPT, ARGS, NO_OBJ, RTR_ONLY },
  88. { "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ,DIR_ONLY},
  89. { "reject", K_REJECT, ARGS, NO_OBJ, RTR_ONLY },
  90. { "router", K_ROUTER, ARGS, NO_OBJ, RTR_ONLY },
  91. { "recommended-software",K_RECOMMENDED_SOFTWARE,ARGS, NO_OBJ, DIR_ONLY },
  92. { "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ, DIR_ONLY },
  93. { "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
  94. { "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
  95. { "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ,RTR_ONLY },
  96. { "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ, DIR_ONLY },
  97. { "ports", K_PORTS, ARGS, NO_OBJ, RTR_ONLY },
  98. { "bandwidth", K_BANDWIDTH, ARGS, NO_OBJ, RTR_ONLY },
  99. { "platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ, RTR_ONLY },
  100. { "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ, ANY },
  101. { "opt", K_OPT, CONCAT_ARGS, OBJ_OK, ANY },
  102. { "dircacheport", K_DIRCACHEPORT, ARGS, NO_OBJ, RTR_ONLY },
  103. { "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ, ANY },
  104. { "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ, DIR_ONLY },
  105. { "uptime", K_UPTIME, ARGS, NO_OBJ, RTR_ONLY },
  106. { "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK, DIR_ONLY },
  107. { "family", K_FAMILY, ARGS, NO_OBJ, RTR_ONLY },
  108. { NULL, -1, NO_ARGS, NO_OBJ, ANY }
  109. };
  110. /* static function prototypes */
  111. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  112. static struct exit_policy_t *router_parse_exit_policy(directory_token_t *tok);
  113. static int router_get_hash_impl(const char *s, char *digest,
  114. const char *start_str, const char *end_str);
  115. static void token_free(directory_token_t *tok);
  116. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  117. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  118. directory_keyword keyword);
  119. static int tokenize_string(const char *start, const char *end,
  120. smartlist_t *out, int is_dir);
  121. static directory_token_t *get_next_token(const char **s, where_syntax where);
  122. static int check_directory_signature(const char *digest,
  123. directory_token_t *tok,
  124. crypto_pk_env_t *pkey,
  125. crypto_pk_env_t *declared_key);
  126. static crypto_pk_env_t *find_dir_signing_key(const char *str);
  127. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  128. * <b>s</b>. Return 0 on success, nonzero on failure.
  129. */
  130. int router_get_dir_hash(const char *s, char *digest)
  131. {
  132. return router_get_hash_impl(s,digest,
  133. "signed-directory","\ndirectory-signature");
  134. }
  135. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  136. * <b>s</b>. Return 0 on success, nonzero on failure.
  137. */
  138. int router_get_router_hash(const char *s, char *digest)
  139. {
  140. return router_get_hash_impl(s,digest,
  141. "router ","\nrouter-signature");
  142. }
  143. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  144. * string in <b>s</b>. Return 0 on success, nonzero on failure.
  145. */
  146. int router_get_runningrouters_hash(const char *s, char *digest)
  147. {
  148. return router_get_hash_impl(s,digest,
  149. "network-status","\ndirectory-signature");
  150. }
  151. /**
  152. * Find the first instance of "recommended-software ...\n" at the start of
  153. * a line; return a newly allocated string containing the "..." portion.
  154. * Return NULL if no such instance was found.
  155. */
  156. static char *
  157. get_recommended_software_from_directory(const char *str)
  158. {
  159. #define REC "recommended-software "
  160. const char *cp = str, *eol;
  161. size_t len = strlen(REC);
  162. cp = str;
  163. if (strcmpstart(str, REC)==0) {
  164. cp += len;
  165. } else {
  166. cp = strstr(str, "\n"REC);
  167. if (!cp)
  168. return NULL;
  169. cp += len+1;
  170. }
  171. eol = strchr(cp, '\n');
  172. if (!eol)
  173. return NULL;
  174. return tor_strndup(cp, eol-cp);
  175. #undef REC
  176. }
  177. /** Return 1 if <b>myversion</b> is not in <b>versionlist</b>, and if at least
  178. * one version of Tor on <b>versionlist</b> is newer than <b>myversion</b>.
  179. * Otherwise return 0.
  180. * (versionlist is a comma-separated list of version strings,
  181. * optionally prefixed with "Tor". Versions that can't be parsed are
  182. * ignored.) */
  183. /* static */ int is_obsolete_version(const char *myversion,
  184. const char *versionlist) {
  185. const char *vl;
  186. tor_version_t mine, other;
  187. int found_newer = 0, r, ret;
  188. static int warned_too_new=0;
  189. smartlist_t *version_sl;
  190. vl = versionlist;
  191. log_fn(LOG_DEBUG,"checking '%s' in '%s'.", myversion, versionlist);
  192. if (tor_version_parse(myversion, &mine)) {
  193. log_fn(LOG_ERR, "I couldn't parse my own version (%s)", myversion);
  194. tor_assert(0);
  195. }
  196. version_sl = smartlist_create();
  197. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  198. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  199. if (!strcmpstart(cp, "Tor "))
  200. cp += 4;
  201. if (tor_version_parse(cp, &other)) {
  202. /* Couldn't parse other; it can't be a match. */
  203. } else {
  204. r = tor_version_compare(&mine, &other);
  205. if (r==0) {
  206. ret = 0;
  207. goto done;
  208. } else if (r<0) {
  209. found_newer = 1;
  210. }
  211. }
  212. });
  213. if (!found_newer) {
  214. if (!warned_too_new) {
  215. log_fn(LOG_WARN, "This version of Tor (%s) is newer than any on the recommended list (%s)",
  216. myversion, versionlist);
  217. warned_too_new=1;
  218. }
  219. ret = 0;
  220. } else {
  221. ret = 1;
  222. }
  223. done:
  224. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  225. smartlist_free(version_sl);
  226. return ret;
  227. }
  228. /* Return 0 if myversion is supported; else log a message and return
  229. * -1 (or exit if ignoreversions is false) */
  230. int check_software_version_against_directory(const char *directory,
  231. int ignoreversion)
  232. {
  233. char *v;
  234. v = get_recommended_software_from_directory(directory);
  235. if (!v) {
  236. log_fn(LOG_WARN, "No recommended-versions string found in directory");
  237. return -1;
  238. }
  239. if (!is_obsolete_version(VERSION, v)) {
  240. tor_free(v);
  241. return 0;
  242. }
  243. log(ignoreversion ? LOG_WARN : LOG_ERR,
  244. "You are running Tor version %s, which will not work with this network.\n"
  245. "Please use %s%s.",
  246. VERSION, strchr(v,',') ? "one of " : "", v);
  247. tor_free(v);
  248. if(ignoreversion) {
  249. log(LOG_WARN, "IgnoreVersion is set. If it breaks, we told you so.");
  250. return -1;
  251. } else {
  252. fflush(0);
  253. tor_cleanup();
  254. exit(0);
  255. return -1; /* never reached */
  256. }
  257. }
  258. /** Parse a directory from <b>str</b> and, when done, store the
  259. * resulting routerlist in *<b>dest</b>, freeing the old value if necessary.
  260. * If <b>pkey</b> is provided, we check the directory signature with pkey.
  261. */
  262. int /* Should be static; exposed for unit tests */
  263. router_parse_routerlist_from_directory(const char *str,
  264. routerlist_t **dest,
  265. crypto_pk_env_t *pkey,
  266. int check_version)
  267. {
  268. directory_token_t *tok;
  269. char digest[DIGEST_LEN];
  270. routerlist_t *new_dir = NULL;
  271. char *versions = NULL;
  272. smartlist_t *good_nickname_list = NULL;
  273. time_t published_on;
  274. int i, r;
  275. const char *end, *cp;
  276. smartlist_t *tokens = NULL;
  277. char dirnickname[MAX_NICKNAME_LEN+1];
  278. crypto_pk_env_t *declared_key = NULL;
  279. if (router_get_dir_hash(str, digest)) {
  280. log_fn(LOG_WARN, "Unable to compute digest of directory");
  281. goto err;
  282. }
  283. log_fn(LOG_DEBUG,"Received directory hashes to %s",hex_str(digest,4));
  284. /* Check signature first, before we try to tokenize. */
  285. cp = str;
  286. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  287. cp = end;
  288. if (cp == str || !cp) {
  289. log_fn(LOG_WARN, "No signature found on directory."); goto err;
  290. }
  291. ++cp;
  292. tokens = smartlist_create();
  293. if (tokenize_string(cp,strchr(cp,'\0'),tokens,1)) {
  294. log_fn(LOG_WARN, "Error tokenizing directory signature"); goto err;
  295. }
  296. if (smartlist_len(tokens) != 1) {
  297. log_fn(LOG_WARN, "Unexpected number of tokens in signature"); goto err;
  298. }
  299. tok=smartlist_get(tokens,0);
  300. if(tok->tp != K_DIRECTORY_SIGNATURE) {
  301. log_fn(LOG_WARN,"Expected a single directory signature"); goto err;
  302. }
  303. declared_key = find_dir_signing_key(str);
  304. if (check_directory_signature(digest, tok, pkey, declared_key)<0)
  305. goto err;
  306. /* now we know tok->n_args == 1, so it's safe to access tok->args[0] */
  307. strlcpy(dirnickname, tok->args[0], sizeof(dirnickname));
  308. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  309. smartlist_free(tokens);
  310. tokens = NULL;
  311. /* Now that we know the signature is okay, check the version. */
  312. if (check_version)
  313. check_software_version_against_directory(str, options.IgnoreVersion);
  314. /* Now try to parse the first part of the directory. */
  315. if ((end = strstr(str,"\nrouter "))) {
  316. ++end;
  317. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  318. ++end;
  319. } else {
  320. end = str + strlen(str);
  321. }
  322. tokens = smartlist_create();
  323. if (tokenize_string(str,end,tokens,1)) {
  324. log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  325. }
  326. if (smartlist_len(tokens) < 1) {
  327. log_fn(LOG_WARN, "Impossibly short directory header"); goto err;
  328. }
  329. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  330. log_fn(LOG_WARN, "Unrecognized keyword \"%s\" in directory header; can't parse directory.",
  331. tok->args[0]);
  332. goto err;
  333. }
  334. tok = smartlist_get(tokens,0);
  335. if (tok->tp != K_SIGNED_DIRECTORY) {
  336. log_fn(LOG_WARN, "Directory doesn't start with signed-directory.");
  337. goto err;
  338. }
  339. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  340. log_fn(LOG_WARN, "Missing published time on directory.");
  341. goto err;
  342. }
  343. tor_assert(tok->n_args == 1);
  344. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  345. goto err;
  346. }
  347. if (!(tok = find_first_by_keyword(tokens, K_RECOMMENDED_SOFTWARE))) {
  348. log_fn(LOG_WARN, "Missing recommended-software line from directory.");
  349. goto err;
  350. }
  351. if (tok->n_args != 1) {
  352. log_fn(LOG_WARN, "Invalid recommended-software line"); goto err;
  353. }
  354. versions = tor_strdup(tok->args[0]);
  355. if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
  356. log_fn(LOG_WARN, "Missing running-routers line from directory.");
  357. goto err;
  358. }
  359. good_nickname_list = smartlist_create();
  360. for (i=0; i<tok->n_args; ++i) {
  361. smartlist_add(good_nickname_list, tok->args[i]);
  362. }
  363. tok->n_args = 0; /* Don't free the strings in good_nickname_list yet. */
  364. /* Read the router list from s, advancing s up past the end of the last
  365. * router. */
  366. str = end;
  367. if (router_parse_list_from_string(&str, &new_dir,
  368. good_nickname_list, published_on)) {
  369. log_fn(LOG_WARN, "Error reading routers from directory");
  370. goto err;
  371. }
  372. new_dir->software_versions = versions; versions = NULL;
  373. new_dir->published_on = published_on;
  374. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  375. smartlist_free(tokens);
  376. tokens = NULL;
  377. /* Determine if my routerinfo is considered verified. */
  378. {
  379. static int have_warned_about_unverified_status = 0;
  380. routerinfo_t *me = router_get_my_routerinfo();
  381. if(me) {
  382. if(router_update_status_from_smartlist(me, published_on,
  383. good_nickname_list)==1 &&
  384. me->is_verified == 0 && !have_warned_about_unverified_status) {
  385. log_fn(LOG_WARN,"Dirserver %s lists your server as unverified. Please consider sending your identity fingerprint to the tor-ops.", dirnickname);
  386. have_warned_about_unverified_status = 1;
  387. }
  388. }
  389. }
  390. if (*dest)
  391. routerlist_free(*dest);
  392. *dest = new_dir;
  393. r = 0;
  394. goto done;
  395. err:
  396. r = -1;
  397. if (new_dir)
  398. routerlist_free(new_dir);
  399. tor_free(versions);
  400. done:
  401. if (declared_key) crypto_free_pk_env(declared_key);
  402. if (tokens) {
  403. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  404. smartlist_free(tokens);
  405. }
  406. if (good_nickname_list) {
  407. SMARTLIST_FOREACH(good_nickname_list, char *, n, tor_free(n));
  408. smartlist_free(good_nickname_list);
  409. }
  410. return r;
  411. }
  412. running_routers_t *
  413. router_parse_runningrouters(const char *str)
  414. {
  415. char digest[DIGEST_LEN];
  416. running_routers_t *new_list = NULL;
  417. directory_token_t *tok;
  418. time_t published_on;
  419. int i;
  420. crypto_pk_env_t *declared_key = NULL;
  421. smartlist_t *tokens = NULL;
  422. if (router_get_runningrouters_hash(str, digest)) {
  423. log_fn(LOG_WARN, "Unable to compute digest of directory");
  424. goto err;
  425. }
  426. tokens = smartlist_create();
  427. if (tokenize_string(str,str+strlen(str),tokens,1)) {
  428. log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  429. }
  430. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  431. log_fn(LOG_WARN, "Unrecognized keyword \"%s\"; can't parse running-routers",
  432. tok->args[0]);
  433. goto err;
  434. }
  435. tok = smartlist_get(tokens,0);
  436. if (tok->tp != K_NETWORK_STATUS) {
  437. log_fn(LOG_WARN, "Network-status starts with wrong token");
  438. goto err;
  439. }
  440. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  441. log_fn(LOG_WARN, "Missing published time on directory.");
  442. goto err;
  443. }
  444. tor_assert(tok->n_args == 1);
  445. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  446. goto err;
  447. }
  448. if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
  449. log_fn(LOG_WARN, "Missing running-routers line from directory.");
  450. goto err;
  451. }
  452. new_list = tor_malloc_zero(sizeof(running_routers_t));
  453. new_list->published_on = published_on;
  454. new_list->running_routers = smartlist_create();
  455. for (i=0;i<tok->n_args;++i) {
  456. smartlist_add(new_list->running_routers, tok->args[i]);
  457. }
  458. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  459. log_fn(LOG_WARN, "Missing signature on directory");
  460. goto err;
  461. }
  462. declared_key = find_dir_signing_key(str);
  463. if (check_directory_signature(digest, tok, NULL, declared_key) < 0)
  464. goto err;
  465. goto done;
  466. err:
  467. running_routers_free(new_list);
  468. new_list = NULL;
  469. done:
  470. if (declared_key) crypto_free_pk_env(declared_key);
  471. if (tokens) {
  472. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  473. smartlist_free(tokens);
  474. }
  475. return new_list;
  476. }
  477. /** Given a directory or running-routers string in <b>str</b>, try to
  478. * find the its dir-signing-key token (if any). If this token is
  479. * present, extract and return the key. Return NULL on failure. */
  480. static crypto_pk_env_t *find_dir_signing_key(const char *str)
  481. {
  482. const char *cp;
  483. directory_token_t *tok;
  484. crypto_pk_env_t *key = NULL;
  485. /* Is there a dir-signing-key in the directory? */
  486. cp = strstr(str, "\nopt dir-signing-key");
  487. if (!cp)
  488. cp = strstr(str, "\ndir-signing-key");
  489. if (!cp)
  490. return NULL;
  491. ++cp; /* Now cp points to the start of the token. */
  492. tok = get_next_token(&cp, DIR_ONLY);
  493. if (!tok) {
  494. log_fn(LOG_WARN, "Unparseable dir-signing-key token");
  495. return NULL;
  496. }
  497. if (tok->tp != K_DIR_SIGNING_KEY) {
  498. log_fn(LOG_WARN, "Dir-signing-key token did not parse as expected");
  499. return NULL;
  500. }
  501. if (tok->key) {
  502. key = tok->key;
  503. tok->key = NULL; /* steal reference. */
  504. } else if (tok->n_args >= 1) {
  505. key = crypto_pk_DER64_decode_public_key(tok->args[0]);
  506. if (!key) {
  507. log_fn(LOG_WARN, "Unparseable dir-signing-key argument");
  508. return NULL;
  509. }
  510. } else {
  511. log_fn(LOG_WARN, "Dir-signing-key token contained no key");
  512. return NULL;
  513. }
  514. token_free(tok);
  515. return key;
  516. }
  517. /** Return true iff <b>key</b> is allowed to sign directories.
  518. */
  519. static int dir_signing_key_is_trusted(crypto_pk_env_t *key)
  520. {
  521. char digest[DIGEST_LEN];
  522. if (!key) return 0;
  523. if (crypto_pk_get_digest(key, digest) < 0) {
  524. log_fn(LOG_WARN, "Error computing dir-signing-key digest");
  525. return 0;
  526. }
  527. if(!router_digest_is_trusted_dir(digest)) {
  528. log_fn(LOG_WARN, "Listed dir-signing-key is not trusted");
  529. return 0;
  530. }
  531. return 1;
  532. }
  533. /** Check whether the K_DIRECTORY_SIGNATURE token in <b>tok</b> has a
  534. * good signature for <b>digest</b>.
  535. *
  536. * If <b>declared_key</b> is set, the directory has declared what key
  537. * was used to sign it, so we will use that key only if it is an
  538. * authoritative directory signing key.
  539. *
  540. * Otherwise, try to look up the router whose nickname is given in the
  541. * directory-signature token. If this fails, or the named router is
  542. * not authoritative, try to use pkey.
  543. *
  544. * (New callers should always use <b>declared_key</b> when possible;
  545. * <b>pkey is only for debugging.)
  546. */
  547. static int check_directory_signature(const char *digest,
  548. directory_token_t *tok,
  549. crypto_pk_env_t *pkey,
  550. crypto_pk_env_t *declared_key)
  551. {
  552. char signed_digest[PK_BYTES];
  553. routerinfo_t *r;
  554. crypto_pk_env_t *_pkey = NULL;
  555. if (tok->n_args != 1) {
  556. log_fn(LOG_WARN, "Too many or too few arguments to directory-signature");
  557. return -1;
  558. }
  559. if (declared_key) {
  560. if (dir_signing_key_is_trusted(declared_key))
  561. _pkey = declared_key;
  562. }
  563. if (!_pkey) {
  564. log_fn(LOG_WARN, "Processing directory in old (before 0.0.9pre3) format--this may fail.");
  565. r = router_get_by_nickname(tok->args[0]);
  566. log_fn(LOG_DEBUG, "Got directory signed (allegedly) by %s", tok->args[0]);
  567. if (r && r->is_trusted_dir) {
  568. _pkey = r->identity_pkey;
  569. } else if (!r && pkey) {
  570. /* pkey provided for debugging purposes. */
  571. _pkey = pkey;
  572. } else if (!r) {
  573. log_fn(LOG_WARN, "No server descriptor loaded for signer %s",
  574. tok->args[0]);
  575. return -1;
  576. } else if (r && !r->is_trusted_dir) {
  577. log_fn(LOG_WARN, "Directory was signed by non-trusted server %s",
  578. tok->args[0]);
  579. return -1;
  580. }
  581. }
  582. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  583. log_fn(LOG_WARN, "Bad object type or length on directory signature");
  584. return -1;
  585. }
  586. tor_assert(_pkey);
  587. if (crypto_pk_public_checksig(_pkey, tok->object_body, 128, signed_digest)
  588. != 20) {
  589. log_fn(LOG_WARN, "Error reading directory: invalid signature.");
  590. return -1;
  591. }
  592. log_fn(LOG_DEBUG,"Signed directory hash starts %s", hex_str(signed_digest,4));
  593. if (memcmp(digest, signed_digest, 20)) {
  594. log_fn(LOG_WARN, "Error reading directory: signature does not match.");
  595. return -1;
  596. }
  597. return 0;
  598. }
  599. /** Given a string *<b>s</b> containing a concatenated sequence of router
  600. * descriptors, parses them and stores the result in *<b>dest</b>. If
  601. * good_nickname_list is provided, then routers are marked as
  602. * running/nonrunning and verified/unverified based on their status in the
  603. * list. Otherwise, all routers are marked running and verified. Advances
  604. * *s to a point immediately following the last router entry. Returns 0 on
  605. * success and -1 on failure.
  606. */
  607. int
  608. router_parse_list_from_string(const char **s, routerlist_t **dest,
  609. smartlist_t *good_nickname_list,
  610. time_t published_on)
  611. {
  612. routerinfo_t *router;
  613. smartlist_t *routers;
  614. const char *end;
  615. tor_assert(s && *s);
  616. routers = smartlist_create();
  617. while (1) {
  618. *s = eat_whitespace(*s);
  619. /* Don't start parsing the rest of *s unless it contains a router. */
  620. if (strcmpstart(*s, "router ")!=0)
  621. break;
  622. if ((end = strstr(*s+1, "\nrouter "))) {
  623. end++;
  624. } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
  625. end++;
  626. } else {
  627. end = *s+strlen(*s);
  628. }
  629. router = router_parse_entry_from_string(*s, end);
  630. *s = end;
  631. if (!router) {
  632. log_fn(LOG_WARN, "Error reading router; skipping");
  633. continue;
  634. }
  635. if (good_nickname_list) {
  636. router_update_status_from_smartlist(router, published_on,
  637. good_nickname_list);
  638. } else {
  639. router->is_running = 1; /* start out assuming all dirservers are up */
  640. router->is_verified = 1;
  641. router->status_set_at = time(NULL);
  642. }
  643. smartlist_add(routers, router);
  644. log_fn(LOG_DEBUG,"just added router #%d.",smartlist_len(routers));
  645. }
  646. if (*dest)
  647. routerlist_free(*dest);
  648. *dest = tor_malloc(sizeof(routerlist_t));
  649. (*dest)->routers = routers;
  650. (*dest)->software_versions = NULL;
  651. return 0;
  652. }
  653. /** Helper function: reads a single router entry from *<b>s</b> ...
  654. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  655. * returns NULL.
  656. */
  657. routerinfo_t *router_parse_entry_from_string(const char *s,
  658. const char *end) {
  659. routerinfo_t *router = NULL;
  660. char signed_digest[128];
  661. char digest[128];
  662. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  663. directory_token_t *tok;
  664. int t;
  665. int ports_set, bw_set;
  666. if (!end) {
  667. end = s + strlen(s);
  668. }
  669. if (router_get_router_hash(s, digest) < 0) {
  670. log_fn(LOG_WARN, "Couldn't compute router hash.");
  671. return NULL;
  672. }
  673. tokens = smartlist_create();
  674. if (tokenize_string(s,end,tokens,0)) {
  675. log_fn(LOG_WARN, "Error tokeninzing router descriptor."); goto err;
  676. }
  677. if (smartlist_len(tokens) < 2) {
  678. log_fn(LOG_WARN, "Impossibly short router descriptor.");
  679. goto err;
  680. }
  681. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  682. log_fn(LOG_WARN, "Unrecognized keyword \"%s\"; skipping descriptor.",
  683. tok->args[0]);
  684. goto err;
  685. }
  686. tok = smartlist_get(tokens,0);
  687. if (tok->tp != K_ROUTER) {
  688. log_fn(LOG_WARN,"Entry does not start with \"router\"");
  689. goto err;
  690. }
  691. router = tor_malloc_zero(sizeof(routerinfo_t));
  692. router->onion_pkey = router->identity_pkey = NULL;
  693. router->declared_family = NULL;
  694. ports_set = bw_set = 0;
  695. if (tok->n_args == 2 || tok->n_args == 5 || tok->n_args == 6) {
  696. router->nickname = tor_strdup(tok->args[0]);
  697. if (!is_legal_nickname(router->nickname)) {
  698. log_fn(LOG_WARN,"Router nickname is invalid");
  699. goto err;
  700. }
  701. router->address = tor_strdup(tok->args[1]);
  702. router->addr = 0;
  703. if (tok->n_args >= 5) {
  704. router->or_port = (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  705. router->socks_port = (uint16_t) tor_parse_long(tok->args[3],10,0,65535,NULL,NULL);
  706. router->dir_port = (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  707. ports_set = 1;
  708. }
  709. } else {
  710. log_fn(LOG_WARN,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
  711. goto err;
  712. }
  713. tok = find_first_by_keyword(tokens, K_PORTS);
  714. if (tok && ports_set) {
  715. log_fn(LOG_WARN,"Redundant ports line");
  716. goto err;
  717. } else if (tok) {
  718. if (tok->n_args != 3) {
  719. log_fn(LOG_WARN,"Wrong # of arguments to \"ports\"");
  720. goto err;
  721. }
  722. router->or_port = (uint16_t) tor_parse_long(tok->args[0],10,0,65535,NULL,NULL);
  723. router->socks_port = (uint16_t) tor_parse_long(tok->args[1],10,0,65535,NULL,NULL);
  724. router->dir_port = (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  725. ports_set = 1;
  726. }
  727. tok = find_first_by_keyword(tokens, K_DIRCACHEPORT);
  728. if (tok) {
  729. if (router->dir_port)
  730. log_fn(LOG_WARN,"Redundant dircacheport line");
  731. if (tok->n_args != 1) {
  732. log_fn(LOG_WARN,"Wrong # of arguments to \"dircacheport\"");
  733. goto err;
  734. }
  735. router->dir_port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,NULL,NULL);
  736. }
  737. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  738. if (tok && bw_set) {
  739. log_fn(LOG_WARN,"Redundant bandwidth line");
  740. goto err;
  741. } else if (tok) {
  742. /* XXX set this to "< 3" once 0.0.7 is obsolete */
  743. if (tok->n_args < 2) {
  744. log_fn(LOG_WARN,"Not enough arguments to \"bandwidth\"");
  745. goto err;
  746. }
  747. router->bandwidthrate = tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  748. router->bandwidthburst = tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  749. if(tok->n_args > 2)
  750. router->bandwidthcapacity = tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  751. bw_set = 1;
  752. }
  753. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  754. if (tok->n_args != 1) {
  755. log_fn(LOG_WARN, "Unrecognized number of args on K_UPTIME; skipping.");
  756. } else {
  757. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  758. }
  759. }
  760. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  761. log_fn(LOG_WARN, "Missing published time"); goto err;
  762. }
  763. tor_assert(tok->n_args == 1);
  764. if (parse_iso_time(tok->args[0], &router->published_on) < 0)
  765. goto err;
  766. if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
  767. log_fn(LOG_WARN, "Missing onion key"); goto err;
  768. }
  769. /* XXX Check key length */
  770. router->onion_pkey = tok->key;
  771. tok->key = NULL; /* Prevent free */
  772. if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
  773. log_fn(LOG_WARN, "Missing identity key"); goto err;
  774. }
  775. /* XXX Check key length */
  776. router->identity_pkey = tok->key;
  777. tok->key = NULL; /* Prevent free */
  778. if (crypto_pk_get_digest(router->identity_pkey,router->identity_digest)){
  779. log_fn(LOG_WARN, "Couldn't calculate key digest"); goto err;
  780. }
  781. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  782. router->platform = tor_strdup(tok->args[0]);
  783. }
  784. exit_policy_tokens = find_all_exitpolicy(tokens);
  785. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  786. if (router_add_exit_policy(router,t)<0) {
  787. log_fn(LOG_WARN,"Error in exit policy"); goto err;}
  788. );
  789. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  790. int i;
  791. router->declared_family = smartlist_create();
  792. for (i=0;i<tok->n_args;++i) {
  793. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  794. log_fn(LOG_WARN, "Illegal nickname %s in family line", tok->args[i]);
  795. goto err;
  796. }
  797. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  798. }
  799. }
  800. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
  801. log_fn(LOG_WARN, "Missing router signature"); goto err;
  802. }
  803. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  804. log_fn(LOG_WARN, "Bad object type or length on router signature");
  805. goto err;
  806. }
  807. if ((t=crypto_pk_public_checksig(router->identity_pkey, tok->object_body,
  808. 128, signed_digest)) != 20) {
  809. log_fn(LOG_WARN, "Invalid signature %d",t); goto err;
  810. }
  811. if (memcmp(digest, signed_digest, 20)) {
  812. log_fn(LOG_WARN, "Mismatched signature"); goto err;
  813. }
  814. if (!ports_set) {
  815. log_fn(LOG_WARN,"No ports declared; failing."); goto err;
  816. }
  817. if (!bw_set) {
  818. log_fn(LOG_WARN,"No bandwidth declared; failing."); goto err;
  819. }
  820. if(!router->or_port) {
  821. log_fn(LOG_WARN,"or_port unreadable or 0. Failing.");
  822. goto err;
  823. }
  824. if (!router->bandwidthrate) {
  825. log_fn(LOG_WARN,"bandwidthrate unreadable or 0. Failing.");
  826. goto err;
  827. }
  828. if (!router->platform) {
  829. router->platform = tor_strdup("<unknown>");
  830. }
  831. log_fn(LOG_DEBUG,"or_port %d, socks_port %d, dir_port %d, bandwidthrate %u, bandwidthburst %u.",
  832. router->or_port, router->socks_port, router->dir_port,
  833. (unsigned) router->bandwidthrate, (unsigned) router->bandwidthburst);
  834. goto done;
  835. return router;
  836. err:
  837. routerinfo_free(router);
  838. router = NULL;
  839. done:
  840. if (tokens) {
  841. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  842. smartlist_free(tokens);
  843. }
  844. if (exit_policy_tokens) {
  845. smartlist_free(exit_policy_tokens);
  846. }
  847. return router;
  848. }
  849. /** Parse the exit policy in the string <b>s</b> and return it.
  850. */
  851. struct exit_policy_t *
  852. router_parse_exit_policy_from_string(const char *s)
  853. {
  854. directory_token_t *tok = NULL;
  855. const char *cp;
  856. char *tmp;
  857. struct exit_policy_t *r;
  858. size_t len, idx;
  859. /* *s might not end with \n, so we need to extend it with one. */
  860. len = strlen(s);
  861. cp = tmp = tor_malloc(len+2);
  862. for (idx = 0; idx < len; ++idx) {
  863. tmp[idx] = tolower(s[idx]);
  864. }
  865. tmp[len]='\n';
  866. tmp[len+1]='\0';
  867. tok = get_next_token(&cp, RTR_ONLY);
  868. if (tok->tp == _ERR) {
  869. log_fn(LOG_WARN, "Error reading exit policy: %s", tok->error);
  870. goto err;
  871. }
  872. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  873. log_fn(LOG_WARN, "Expected 'accept' or 'reject'.");
  874. goto err;
  875. }
  876. /* Now that we've gotten an exit policy, add it to the router. */
  877. r = router_parse_exit_policy(tok);
  878. goto done;
  879. err:
  880. r = NULL;
  881. done:
  882. tor_free(tmp);
  883. token_free(tok);
  884. return r;
  885. }
  886. int router_add_exit_policy_from_string(routerinfo_t *router, const char *s)
  887. {
  888. struct exit_policy_t *newe, *tmpe;
  889. newe = router_parse_exit_policy_from_string(s);
  890. if (!newe)
  891. return -1;
  892. for (tmpe = router->exit_policy; tmpe; tmpe=tmpe->next)
  893. ;
  894. tmpe->next = newe;
  895. return 0;
  896. }
  897. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok)
  898. {
  899. struct exit_policy_t *newe, **tmpe;
  900. newe = router_parse_exit_policy(tok);
  901. if (!newe)
  902. return -1;
  903. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  904. ;
  905. *tmpe = newe;
  906. return 0;
  907. }
  908. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  909. * a new exit_policy_t corresponding to the token. */
  910. static struct exit_policy_t *
  911. router_parse_exit_policy(directory_token_t *tok) {
  912. struct exit_policy_t*newe;
  913. struct in_addr in;
  914. char *arg, *address, *mask, *port, *endptr;
  915. int bits;
  916. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  917. if (tok->n_args != 1)
  918. return NULL;
  919. arg = tok->args[0];
  920. newe = tor_malloc_zero(sizeof(struct exit_policy_t));
  921. newe->string = tor_malloc(8+strlen(arg));
  922. if (tok->tp == K_REJECT) {
  923. strcpy(newe->string, "reject ");
  924. newe->policy_type = EXIT_POLICY_REJECT;
  925. } else {
  926. strcpy(newe->string, "accept ");
  927. newe->policy_type = EXIT_POLICY_ACCEPT;
  928. }
  929. strcat(newe->string, arg); /* can't overflow */
  930. address = arg;
  931. mask = strchr(arg,'/');
  932. port = strchr(mask?mask:arg,':');
  933. /* Break 'arg' into separate strings. 'arg' was already strdup'd by
  934. * _router_get_next_token, so it's safe to modify.
  935. */
  936. if (mask)
  937. *mask++ = 0;
  938. if (port)
  939. *port++ = 0;
  940. if (strcmp(address, "*") == 0) {
  941. newe->addr = 0;
  942. } else if (tor_inet_aton(address, &in) != 0) {
  943. newe->addr = ntohl(in.s_addr);
  944. } else {
  945. log_fn(LOG_WARN, "Malformed IP %s in exit policy; rejecting.",
  946. address);
  947. goto policy_read_failed;
  948. }
  949. if (!mask) {
  950. if (strcmp(address, "*") == 0)
  951. newe->msk = 0;
  952. else
  953. newe->msk = 0xFFFFFFFFu;
  954. } else {
  955. endptr = NULL;
  956. bits = (int) strtol(mask, &endptr, 10);
  957. if (!*endptr) {
  958. /* strtol handled the whole mask. */
  959. if (bits < 0 || bits > 32) {
  960. log_fn(LOG_WARN, "Bad number of mask bits on exit policy; rejecting.");
  961. goto policy_read_failed;
  962. }
  963. newe->msk = ~((1<<(32-bits))-1);
  964. } else if (tor_inet_aton(mask, &in) != 0) {
  965. newe->msk = ntohl(in.s_addr);
  966. } else {
  967. log_fn(LOG_WARN, "Malformed mask %s on exit policy; rejecting.",
  968. mask);
  969. goto policy_read_failed;
  970. }
  971. }
  972. if (!port || strcmp(port, "*") == 0) {
  973. newe->prt_min = 0;
  974. newe->prt_max = 65535;
  975. } else {
  976. endptr = NULL;
  977. newe->prt_min = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  978. NULL, &endptr);
  979. if (*endptr == '-') {
  980. port = endptr+1;
  981. endptr = NULL;
  982. newe->prt_max = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  983. &endptr);
  984. if (*endptr || !newe->prt_max) {
  985. log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
  986. port);
  987. }
  988. } else if (*endptr || !newe->prt_min) {
  989. log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
  990. port);
  991. goto policy_read_failed;
  992. } else {
  993. newe->prt_max = newe->prt_min;
  994. }
  995. if (newe->prt_min > newe->prt_max) {
  996. log_fn(LOG_WARN,"Insane port range on exit policy; rejecting.");
  997. goto policy_read_failed;
  998. }
  999. }
  1000. in.s_addr = htonl(newe->addr);
  1001. address = tor_strdup(inet_ntoa(in));
  1002. in.s_addr = htonl(newe->msk);
  1003. log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
  1004. newe->policy_type == EXIT_POLICY_REJECT ? "reject" : "accept",
  1005. address, inet_ntoa(in), newe->prt_min, newe->prt_max);
  1006. tor_free(address);
  1007. newe->next = NULL;
  1008. return newe;
  1009. policy_read_failed:
  1010. tor_assert(newe->string);
  1011. log_fn(LOG_WARN,"Couldn't parse line '%s'. Dropping", newe->string);
  1012. tor_free(newe->string);
  1013. tor_free(newe);
  1014. return NULL;
  1015. }
  1016. /*
  1017. * Low-level tokenizer for router descriptors and directories.
  1018. */
  1019. /** Free all resources allocated for <b>tok</b> */
  1020. static void
  1021. token_free(directory_token_t *tok)
  1022. {
  1023. int i;
  1024. tor_assert(tok);
  1025. if (tok->args) {
  1026. for (i = 0; i < tok->n_args; ++i) {
  1027. tor_free(tok->args[i]);
  1028. }
  1029. tor_free(tok->args);
  1030. }
  1031. tor_free(tok->object_type);
  1032. tor_free(tok->object_body);
  1033. if (tok->key)
  1034. crypto_free_pk_env(tok->key);
  1035. tor_free(tok);
  1036. }
  1037. /** Helper function: read the next token from *s, advance *s to the end
  1038. * of the token, and return the parsed token. If 'where' is DIR_ONLY
  1039. * or RTR_ONLY, reject all tokens of the wrong type.
  1040. */
  1041. static directory_token_t *
  1042. get_next_token(const char **s, where_syntax where) {
  1043. const char *next, *obstart;
  1044. int i, done, allocated, is_opt;
  1045. directory_token_t *tok;
  1046. arg_syntax a_syn;
  1047. obj_syntax o_syn = NO_OBJ;
  1048. #define RET_ERR(msg) \
  1049. do { if (tok) token_free(tok); \
  1050. tok = tor_malloc_zero(sizeof(directory_token_t));\
  1051. tok->tp = _ERR; \
  1052. tok->error = msg; \
  1053. goto done_tokenizing; } while (0)
  1054. tok = tor_malloc_zero(sizeof(directory_token_t));
  1055. tok->tp = _ERR;
  1056. *s = eat_whitespace(*s);
  1057. if (!**s) {
  1058. tok->tp = _EOF;
  1059. return tok;
  1060. }
  1061. next = find_whitespace(*s);
  1062. if (!next) {
  1063. tok->error = "Unexpected EOF"; return tok;
  1064. }
  1065. /* It's a keyword... but which one? */
  1066. is_opt = !strncmp("opt", *s, next-*s);
  1067. if (is_opt) {
  1068. *s = eat_whitespace(next);
  1069. next = NULL;
  1070. if (**s)
  1071. next = find_whitespace(*s);
  1072. if (!**s || !next) {
  1073. RET_ERR("opt without keyword");
  1074. }
  1075. }
  1076. for (i = 0; token_table[i].t ; ++i) {
  1077. if (!strncmp(token_table[i].t, *s, next-*s)) {
  1078. /* We've found the keyword. */
  1079. tok->tp = token_table[i].v;
  1080. a_syn = token_table[i].s;
  1081. o_syn = token_table[i].os;
  1082. if (token_table[i].ws != ANY && token_table[i].ws != where) {
  1083. if (where == DIR_ONLY) {
  1084. RET_ERR("Found a router-only token in a directory section");
  1085. } else {
  1086. RET_ERR("Found a directory-only token in a router descriptor");
  1087. }
  1088. }
  1089. if (a_syn == ARGS) {
  1090. /* This keyword takes multiple arguments. */
  1091. i = 0;
  1092. done = (*next == '\n');
  1093. allocated = 32;
  1094. tok->args = tor_malloc(sizeof(char*)*32);
  1095. *s = eat_whitespace_no_nl(next);
  1096. while (**s != '\n' && !done) {
  1097. next = find_whitespace(*s);
  1098. if (*next == '\n')
  1099. done = 1;
  1100. if (i == allocated) {
  1101. allocated *= 2;
  1102. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1103. }
  1104. tok->args[i++] = tor_strndup(*s,next-*s);
  1105. *s = eat_whitespace_no_nl(next+1);
  1106. }
  1107. tok->n_args = i;
  1108. } else if (a_syn == CONCAT_ARGS) {
  1109. /* The keyword takes the line as a single argument */
  1110. *s = eat_whitespace_no_nl(next);
  1111. next = strchr(*s, '\n');
  1112. if (!next)
  1113. RET_ERR("Unexpected EOF");
  1114. tok->args = tor_malloc(sizeof(char*));
  1115. tok->args[0] = tor_strndup(*s,next-*s);
  1116. tok->n_args = 1;
  1117. *s = eat_whitespace_no_nl(next+1);
  1118. } else {
  1119. /* The keyword takes no arguments. */
  1120. tor_assert(a_syn == NO_ARGS);
  1121. *s = eat_whitespace_no_nl(next);
  1122. if (**s != '\n') {
  1123. RET_ERR("Unexpected arguments");
  1124. }
  1125. tok->n_args = 0;
  1126. *s = eat_whitespace_no_nl(*s+1);
  1127. }
  1128. break;
  1129. }
  1130. }
  1131. if (tok->tp == _ERR) {
  1132. if (is_opt) {
  1133. tok->tp = K_OPT;
  1134. *s = eat_whitespace_no_nl(next);
  1135. next = strchr(*s,'\n');
  1136. if (!next)
  1137. RET_ERR("Unexpected EOF");
  1138. tok->args = tor_malloc(sizeof(char*));
  1139. tok->args[0] = tor_strndup(*s,next-*s);
  1140. tok->n_args = 1;
  1141. *s = eat_whitespace_no_nl(next+1);
  1142. o_syn = OBJ_OK;
  1143. } else {
  1144. tok->tp = _UNRECOGNIZED;
  1145. next = strchr(*s, '\n');
  1146. if (!next) {
  1147. RET_ERR("Unexpected EOF");
  1148. }
  1149. tok->args = tor_malloc(sizeof(char*));
  1150. tok->args[0] = tor_strndup(*s,next-*s);
  1151. tok->n_args = 1;
  1152. *s = next+1;
  1153. o_syn = OBJ_OK;
  1154. }
  1155. }
  1156. *s = eat_whitespace(*s);
  1157. if (strcmpstart(*s, "-----BEGIN ")) {
  1158. goto done_tokenizing;
  1159. }
  1160. obstart = *s;
  1161. *s += 11; /* length of "-----BEGIN ". */
  1162. next = strchr(*s, '\n');
  1163. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  1164. RET_ERR("Malformed object: bad begin line");
  1165. }
  1166. tok->object_type = tor_strndup(*s, next-*s-5);
  1167. *s = next+1;
  1168. next = strstr(*s, "-----END ");
  1169. if (!next) {
  1170. RET_ERR("Malformed object: missing end line");
  1171. }
  1172. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1173. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  1174. RET_ERR("Malformed object: mismatched end line");
  1175. next = strchr(next,'\n')+1;
  1176. tok->key = crypto_new_pk_env();
  1177. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1178. RET_ERR("Couldn't parse public key.");
  1179. *s = next;
  1180. } else {
  1181. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1182. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1183. if (i<0) {
  1184. RET_ERR("Malformed object: bad base64-encoded data");
  1185. }
  1186. tok->object_size = i;
  1187. *s = next + 9; /* length of "-----END ". */
  1188. i = strlen(tok->object_type);
  1189. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  1190. RET_ERR("Malformed object: mismatched end tag");
  1191. }
  1192. *s += i+6;
  1193. }
  1194. switch(o_syn)
  1195. {
  1196. case NO_OBJ:
  1197. if (tok->object_body)
  1198. RET_ERR("Unexpected object for keyword");
  1199. if (tok->key)
  1200. RET_ERR("Unexpected public key for keyword");
  1201. break;
  1202. case NEED_OBJ:
  1203. if (!tok->object_body)
  1204. RET_ERR("Missing object for keyword");
  1205. break;
  1206. case NEED_KEY:
  1207. if (!tok->key)
  1208. RET_ERR("Missing public key for keyword");
  1209. break;
  1210. case OBJ_OK:
  1211. break;
  1212. }
  1213. done_tokenizing:
  1214. #if 0
  1215. for (i = 0; token_table[i].t ; ++i) {
  1216. if (token_table[i].v == tok->tp) {
  1217. fputs(token_table[i].t, stdout);
  1218. break;
  1219. i = -1;
  1220. }
  1221. }
  1222. if (i) {
  1223. if (tok->tp == _UNRECOGNIZED) fputs("UNRECOGNIZED", stdout);
  1224. if (tok->tp == _ERR) fputs("ERR",stdout);
  1225. if (tok->tp == _EOF) fputs("EOF",stdout);
  1226. if (tok->tp == _NIL) fputs("_NIL",stdout);
  1227. }
  1228. for(i = 0; i < tok->n_args; ++i) {
  1229. fprintf(stdout," \"%s\"", tok->args[i]);
  1230. }
  1231. if (tok->error) { fprintf(stdout," *%s*", tok->error); }
  1232. fputs("\n",stdout);
  1233. #endif
  1234. return tok;
  1235. #undef RET_ERR
  1236. }
  1237. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1238. * them to <b>out</b>. If <b>is_dir</b> is true, reject all non-directory
  1239. * tokens; else reject all non-routerdescriptor tokens.
  1240. */
  1241. static int
  1242. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1243. int is_dir)
  1244. {
  1245. const char **s;
  1246. directory_token_t *tok = NULL;
  1247. where_syntax where = is_dir ? DIR_ONLY : RTR_ONLY;
  1248. s = &start;
  1249. while (*s < end && (!tok || tok->tp != _EOF)) {
  1250. tok = get_next_token(s, where);
  1251. if (tok->tp == _ERR) {
  1252. log_fn(LOG_WARN, "parse error: %s", tok->error);
  1253. return -1;
  1254. }
  1255. smartlist_add(out, tok);
  1256. *s = eat_whitespace(*s);
  1257. }
  1258. return 0;
  1259. }
  1260. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1261. * NULL if no such keyword is found.
  1262. */
  1263. static directory_token_t *
  1264. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1265. {
  1266. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1267. return NULL;
  1268. }
  1269. /** Return a newly allocated smartlist of all accept or reject tokens in
  1270. * <b>s</b>.
  1271. */
  1272. static smartlist_t *
  1273. find_all_exitpolicy(smartlist_t *s)
  1274. {
  1275. smartlist_t *out = smartlist_create();
  1276. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1277. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1278. smartlist_add(out,t));
  1279. return out;
  1280. }
  1281. /** Compute the SHA digest of the substring of <b>s</b> taken from the first
  1282. * occurrence of <b>start_str</b> through the first newline after the first
  1283. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1284. * <b>digest</b>; return 0 on success.
  1285. *
  1286. * If no such substring exists, return -1.
  1287. */
  1288. static int router_get_hash_impl(const char *s, char *digest,
  1289. const char *start_str,
  1290. const char *end_str)
  1291. {
  1292. char *start, *end;
  1293. start = strstr(s, start_str);
  1294. if (!start) {
  1295. log_fn(LOG_WARN,"couldn't find \"%s\"",start_str);
  1296. return -1;
  1297. }
  1298. if (start != s && *(start-1) != '\n') {
  1299. log_fn(LOG_WARN, "first occurrence of \"%s\" is not at the start of a line",
  1300. start_str);
  1301. return -1;
  1302. }
  1303. end = strstr(start+strlen(start_str), end_str);
  1304. if (!end) {
  1305. log_fn(LOG_WARN,"couldn't find \"%s\"",end_str);
  1306. return -1;
  1307. }
  1308. end = strchr(end+strlen(end_str), '\n');
  1309. if (!end) {
  1310. log_fn(LOG_WARN,"couldn't find EOL");
  1311. return -1;
  1312. }
  1313. ++end;
  1314. if (crypto_digest(start, end-start, digest)) {
  1315. log_fn(LOG_WARN,"couldn't compute digest");
  1316. return -1;
  1317. }
  1318. return 0;
  1319. }
  1320. /** Parse the Tor version of the platform string <b>platform</b>,
  1321. * and compare it to the version in <b>cutoff</b>. Return 1 if
  1322. * the router is at least as new as the cutoff, else return 0.
  1323. */
  1324. int tor_version_as_new_as(const char *platform, const char *cutoff) {
  1325. tor_version_t cutoff_version, router_version;
  1326. char *s, *start;
  1327. char tmp[128];
  1328. if(tor_version_parse(cutoff, &cutoff_version)<0) {
  1329. log_fn(LOG_WARN,"Bug: cutoff version '%s' unparsable.",cutoff);
  1330. return 0;
  1331. }
  1332. if(strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  1333. return 1;
  1334. start = (char *)eat_whitespace(platform+3);
  1335. if (!*start) return 0;
  1336. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  1337. if((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  1338. return 0;
  1339. strlcpy(tmp, start, s-start+1);
  1340. if(tor_version_parse(tmp, &router_version)<0) {
  1341. log_fn(LOG_INFO,"Router version '%s' unparsable.",tmp);
  1342. return 1; /* be safe and say yes */
  1343. }
  1344. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  1345. }
  1346. /** DOCDOC */
  1347. int tor_version_parse(const char *s, tor_version_t *out)
  1348. {
  1349. char *eos=NULL, *cp=NULL;
  1350. /* Format is:
  1351. * NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ -cvs ] ]
  1352. */
  1353. tor_assert(s && out);
  1354. memset(out, 0, sizeof(tor_version_t));
  1355. /* Get major. */
  1356. out->major = strtol(s,&eos,10);
  1357. if (!eos || eos==s || *eos != '.') return -1;
  1358. cp = eos+1;
  1359. /* Get minor */
  1360. out->minor = strtol(cp,&eos,10);
  1361. if (!eos || eos==cp || *eos != '.') return -1;
  1362. cp = eos+1;
  1363. /* Get micro */
  1364. out->micro = strtol(cp,&eos,10);
  1365. if (!eos || eos==cp) return -1;
  1366. if (!*eos) {
  1367. out->status = VER_RELEASE;
  1368. out->patchlevel = 0;
  1369. out->cvs = IS_NOT_CVS;
  1370. return 0;
  1371. }
  1372. cp = eos;
  1373. /* Get status */
  1374. if (*cp == '.') {
  1375. out->status = VER_RELEASE;
  1376. ++cp;
  1377. } else if (0==strncmp(cp, "pre", 3)) {
  1378. out->status = VER_PRE;
  1379. cp += 3;
  1380. } else if (0==strncmp(cp, "rc", 2)) {
  1381. out->status = VER_RC;
  1382. cp += 2;
  1383. } else {
  1384. return -1;
  1385. }
  1386. /* Get patchlevel */
  1387. out->patchlevel = strtol(cp,&eos,10);
  1388. if (!eos || eos==cp) return -1;
  1389. cp = eos;
  1390. /* Get cvs status. */
  1391. if (!*eos) {
  1392. out->cvs = IS_NOT_CVS;
  1393. } else if (0==strcmp(cp, "-cvs")) {
  1394. out->cvs = IS_CVS;
  1395. } else {
  1396. return -1;
  1397. }
  1398. return 0;
  1399. }
  1400. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  1401. * b. */
  1402. int tor_version_compare(tor_version_t *a, tor_version_t *b)
  1403. {
  1404. int i;
  1405. tor_assert(a && b);
  1406. if ((i = a->major - b->major))
  1407. return i;
  1408. else if ((i = a->minor - b->minor))
  1409. return i;
  1410. else if ((i = a->micro - b->micro))
  1411. return i;
  1412. else if ((i = a->status - b->status))
  1413. return i;
  1414. else if ((i = a->patchlevel - b->patchlevel))
  1415. return i;
  1416. else if ((i = a->cvs - b->cvs))
  1417. return i;
  1418. else
  1419. return 0;
  1420. }
  1421. /*
  1422. Local Variables:
  1423. mode:c
  1424. indent-tabs-mode:nil
  1425. c-basic-offset:2
  1426. End:
  1427. */