routerparse.c 46 KB

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