routerparse.c 43 KB

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