routerparse.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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. char dirnickname[MAX_NICKNAME_LEN+1];
  305. if (router_get_dir_hash(str, digest)) {
  306. log_fn(LOG_WARN, "Unable to compute digest of directory");
  307. goto err;
  308. }
  309. log_fn(LOG_DEBUG,"Received directory hashes to %s",hex_str(digest,4));
  310. /* Check signature first, before we try to tokenize. */
  311. cp = str;
  312. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  313. cp = end;
  314. if (cp == str || !cp) {
  315. log_fn(LOG_WARN, "No signature found on directory."); goto err;
  316. }
  317. ++cp;
  318. tokens = smartlist_create();
  319. if (tokenize_string(cp,strchr(cp,'\0'),tokens,1)) {
  320. log_fn(LOG_WARN, "Error tokenizing directory signature"); goto err;
  321. }
  322. if (smartlist_len(tokens) != 1) {
  323. log_fn(LOG_WARN, "Unexpected number of tokens in signature"); goto err;
  324. }
  325. tok=smartlist_get(tokens,0);
  326. if(tok->tp != K_DIRECTORY_SIGNATURE) {
  327. log_fn(LOG_WARN,"Expected a single directory signature"); goto err;
  328. }
  329. if (check_directory_signature(digest, tok, pkey)<0) {
  330. goto err;
  331. }
  332. /* now we know tok->n_args == 1, so it's safe to access tok->args[0] */
  333. strlcpy(dirnickname, tok->args[0], sizeof(dirnickname));
  334. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  335. smartlist_free(tokens);
  336. tokens = NULL;
  337. /* Now that we know the signature is okay, check the version. */
  338. check_software_version_against_directory(str, options.IgnoreVersion);
  339. /* Now try to parse the first part of the directory. */
  340. if ((end = strstr(str,"\nrouter "))) {
  341. ++end;
  342. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  343. ++end;
  344. } else {
  345. end = str + strlen(str);
  346. }
  347. tokens = smartlist_create();
  348. if (tokenize_string(str,end,tokens,1)) {
  349. log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  350. }
  351. if (smartlist_len(tokens) < 1) {
  352. log_fn(LOG_WARN, "Impossibly short directory header"); goto err;
  353. }
  354. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  355. log_fn(LOG_WARN, "Unrecognized keyword in \"%s\"; can't parse directory.",
  356. tok->args[0]);
  357. goto err;
  358. }
  359. tok = smartlist_get(tokens,0);
  360. if (tok->tp != K_SIGNED_DIRECTORY) {
  361. log_fn(LOG_WARN, "Directory doesn't start with signed-directory.");
  362. goto err;
  363. }
  364. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  365. log_fn(LOG_WARN, "Missing published time on directory.");
  366. goto err;
  367. }
  368. tor_assert(tok->n_args == 1);
  369. if (parse_time(tok->args[0], &published_on) < 0) {
  370. goto err;
  371. }
  372. if (!(tok = find_first_by_keyword(tokens, K_RECOMMENDED_SOFTWARE))) {
  373. log_fn(LOG_WARN, "Missing recommended-software line from directory.");
  374. goto err;
  375. }
  376. if (tok->n_args != 1) {
  377. log_fn(LOG_WARN, "Invalid recommended-software line"); goto err;
  378. }
  379. versions = tor_strdup(tok->args[0]);
  380. if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
  381. log_fn(LOG_WARN, "Missing running-routers line from directory.");
  382. goto err;
  383. }
  384. good_nickname_list = smartlist_create();
  385. for (i=0; i<tok->n_args; ++i) {
  386. smartlist_add(good_nickname_list, tok->args[i]);
  387. }
  388. tok->n_args = 0; /* Don't free the strings in good_nickname_lst yet. */
  389. /* Read the router list from s, advancing s up past the end of the last
  390. * router. */
  391. str = end;
  392. if (router_parse_list_from_string(&str, &new_dir,
  393. good_nickname_list, published_on)) {
  394. log_fn(LOG_WARN, "Error reading routers from directory");
  395. goto err;
  396. }
  397. new_dir->software_versions = versions; versions = NULL;
  398. new_dir->published_on = published_on;
  399. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  400. smartlist_free(tokens);
  401. tokens = NULL;
  402. /* Determine if my routerinfo is considered verified. */
  403. {
  404. static int have_warned_about_unverified_status = 0;
  405. routerinfo_t *me = router_get_my_routerinfo();
  406. if(me) {
  407. router_update_status_from_smartlist(me, published_on,
  408. good_nickname_list);
  409. if(me->is_verified == 0 && !have_warned_about_unverified_status) {
  410. log_fn(LOG_WARN,"Dirserver %s lists your server as unverified. Please consider sending your identity fingerprint to the tor-ops.", dirnickname);
  411. /* XXX008 can we print the name of the dirserver above? how to get it */
  412. have_warned_about_unverified_status = 1;
  413. }
  414. }
  415. }
  416. if (*dest)
  417. routerlist_free(*dest);
  418. *dest = new_dir;
  419. r = 0;
  420. goto done;
  421. err:
  422. r = -1;
  423. if (new_dir)
  424. routerlist_free(new_dir);
  425. tor_free(versions);
  426. done:
  427. if (tokens) {
  428. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  429. smartlist_free(tokens);
  430. }
  431. if (good_nickname_list) {
  432. SMARTLIST_FOREACH(good_nickname_list, char *, n, tor_free(n));
  433. smartlist_free(good_nickname_list);
  434. }
  435. return r;
  436. }
  437. running_routers_t *
  438. router_parse_runningrouters(const char *str)
  439. {
  440. char digest[DIGEST_LEN];
  441. running_routers_t *new_list = NULL;
  442. directory_token_t *tok;
  443. time_t published_on;
  444. int i;
  445. smartlist_t *tokens = NULL;
  446. if (router_get_runningrouters_hash(str, digest)) {
  447. log_fn(LOG_WARN, "Unable to compute digest of directory");
  448. goto err;
  449. }
  450. tokens = smartlist_create();
  451. if (tokenize_string(str,str+strlen(str),tokens,1)) {
  452. log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  453. }
  454. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  455. log_fn(LOG_WARN, "Unrecognized keyword in \"%s\"; can't parse directory.",
  456. tok->args[0]);
  457. goto err;
  458. }
  459. tok = smartlist_get(tokens,0);
  460. if (tok->tp != K_NETWORK_STATUS) {
  461. log_fn(LOG_WARN, "Network-status starts with wrong token");
  462. goto err;
  463. }
  464. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  465. log_fn(LOG_WARN, "Missing published time on directory.");
  466. goto err;
  467. }
  468. tor_assert(tok->n_args == 1);
  469. if (parse_time(tok->args[0], &published_on) < 0) {
  470. goto err;
  471. }
  472. if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
  473. log_fn(LOG_WARN, "Missing running-routers line from directory.");
  474. goto err;
  475. }
  476. new_list = tor_malloc_zero(sizeof(running_routers_t));
  477. new_list->published_on = published_on;
  478. new_list->running_routers = smartlist_create();
  479. for (i=0;i<tok->n_args;++i) {
  480. smartlist_add(new_list->running_routers, tok->args[i]);
  481. }
  482. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  483. log_fn(LOG_WARN, "Missing signature on directory");
  484. goto err;
  485. }
  486. if (check_directory_signature(digest, tok, NULL)<0) {
  487. goto err;
  488. }
  489. goto done;
  490. err:
  491. running_routers_free(new_list);
  492. new_list = NULL;
  493. done:
  494. if (tokens) {
  495. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  496. smartlist_free(tokens);
  497. }
  498. return new_list;
  499. }
  500. static int check_directory_signature(const char *digest,
  501. directory_token_t *tok,
  502. crypto_pk_env_t *pkey)
  503. {
  504. char signed_digest[PK_BYTES];
  505. if (tok->n_args == 1) {
  506. routerinfo_t *r = router_get_by_nickname(tok->args[0]);
  507. log_fn(LOG_DEBUG, "Got directory signed by %s", tok->args[0]);
  508. if (r && r->is_trusted_dir) {
  509. pkey = r->identity_pkey;
  510. } else if (!r && pkey) {
  511. /* pkey provided for debugging purposes. */
  512. } else if (!r) {
  513. log_fn(LOG_WARN, "Directory was signed by unrecognized server %s",
  514. tok->args[0]);
  515. return -1;
  516. } else if (r && !r->is_trusted_dir) {
  517. log_fn(LOG_WARN, "Directory was signed by non-trusted server %s",
  518. tok->args[0]);
  519. return -1;
  520. }
  521. } else if (tok->n_args > 1) {
  522. /* XXX008 Nick: shouldn't we check for <1 too? */
  523. log_fn(LOG_WARN, "Too many arguments to directory-signature");
  524. return -1;
  525. }
  526. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  527. log_fn(LOG_WARN, "Bad object type or length on directory signature");
  528. return -1;
  529. }
  530. if (pkey) {
  531. if (crypto_pk_public_checksig(pkey, tok->object_body, 128, signed_digest)
  532. != 20) {
  533. log_fn(LOG_WARN, "Error reading directory: invalid signature.");
  534. return -1;
  535. }
  536. log_fn(LOG_DEBUG,"Signed directory hash starts %s", hex_str(signed_digest,4));
  537. if (memcmp(digest, signed_digest, 20)) {
  538. log_fn(LOG_WARN, "Error reading directory: signature does not match.");
  539. return -1;
  540. }
  541. } else {
  542. /* XXXX008 freak out, unless testing. */
  543. }
  544. return 0;
  545. }
  546. /** Given a string *<b>s</b> containing a concatenated sequence of router
  547. * descriptors, parses them and stores the result in *<b>dest</b>. If
  548. * good_nickname_list is provided, then routers are marked as
  549. * running/nonrunning and verified/unverified based on their status in the
  550. * list. Otherwise, all routers are marked running and verified. Advances
  551. * *s to a point immediately following the last router entry. Returns 0 on
  552. * success and -1 on failure.
  553. */
  554. int
  555. router_parse_list_from_string(const char **s, routerlist_t **dest,
  556. smartlist_t *good_nickname_list,
  557. time_t published_on)
  558. {
  559. routerinfo_t *router;
  560. smartlist_t *routers;
  561. const char *end;
  562. tor_assert(s && *s);
  563. routers = smartlist_create();
  564. while (1) {
  565. *s = eat_whitespace(*s);
  566. /* Don't start parsing the rest of *s unless it contains a router. */
  567. if (strncmp(*s, "router ", 7)!=0)
  568. break;
  569. if ((end = strstr(*s+1, "\nrouter "))) {
  570. end++;
  571. } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
  572. end++;
  573. } else {
  574. end = *s+strlen(*s);
  575. }
  576. router = router_parse_entry_from_string(*s, end);
  577. *s = end;
  578. if (!router) {
  579. log_fn(LOG_WARN, "Error reading router; skipping");
  580. continue;
  581. }
  582. if (good_nickname_list) {
  583. router_update_status_from_smartlist(router, published_on,
  584. good_nickname_list);
  585. } else {
  586. router->is_running = 1; /* start out assuming all dirservers are up */
  587. router->is_verified = 1;
  588. router->status_set_at = time(NULL);
  589. }
  590. smartlist_add(routers, router);
  591. log_fn(LOG_DEBUG,"just added router #%d.",smartlist_len(routers));
  592. }
  593. if (*dest)
  594. routerlist_free(*dest);
  595. *dest = tor_malloc(sizeof(routerlist_t));
  596. (*dest)->routers = routers;
  597. (*dest)->software_versions = NULL;
  598. return 0;
  599. }
  600. /** Helper function: reads a single router entry from *<b>s</b> ...
  601. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  602. * returns NULL.
  603. */
  604. routerinfo_t *router_parse_entry_from_string(const char *s,
  605. const char *end) {
  606. routerinfo_t *router = NULL;
  607. char signed_digest[128];
  608. char digest[128];
  609. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  610. directory_token_t *tok;
  611. int t;
  612. int ports_set, bw_set;
  613. if (!end) {
  614. end = s + strlen(s);
  615. }
  616. if (router_get_router_hash(s, digest) < 0) {
  617. log_fn(LOG_WARN, "Couldn't compute router hash.");
  618. return NULL;
  619. }
  620. tokens = smartlist_create();
  621. if (tokenize_string(s,end,tokens,0)) {
  622. log_fn(LOG_WARN, "Error tokeninzing router descriptor."); goto err;
  623. }
  624. if (smartlist_len(tokens) < 2) {
  625. log_fn(LOG_WARN, "Impossibly short router descriptor.");
  626. goto err;
  627. }
  628. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  629. log_fn(LOG_WARN, "Unrecognized keyword in \"%s\"; skipping descriptor.",
  630. tok->args[0]);
  631. goto err;
  632. }
  633. tok = smartlist_get(tokens,0);
  634. if (tok->tp != K_ROUTER) {
  635. log_fn(LOG_WARN,"Entry does not start with \"router\"");
  636. goto err;
  637. }
  638. router = tor_malloc_zero(sizeof(routerinfo_t));
  639. router->onion_pkey = router->identity_pkey = NULL;
  640. ports_set = bw_set = 0;
  641. if (tok->n_args == 2 || tok->n_args == 5 || tok->n_args == 6) {
  642. router->nickname = tor_strdup(tok->args[0]);
  643. if (strlen(router->nickname) > MAX_NICKNAME_LEN) {
  644. log_fn(LOG_WARN,"Router nickname too long.");
  645. goto err;
  646. }
  647. if (strspn(router->nickname, LEGAL_NICKNAME_CHARACTERS) !=
  648. strlen(router->nickname)) {
  649. log_fn(LOG_WARN, "Router nickname contains illegal characters.");
  650. goto err;
  651. }
  652. router->address = tor_strdup(tok->args[1]);
  653. router->addr = 0;
  654. if (tok->n_args >= 5) {
  655. router->or_port = atoi(tok->args[2]);
  656. router->socks_port = atoi(tok->args[3]);
  657. router->dir_port = atoi(tok->args[4]);
  658. ports_set = 1;
  659. }
  660. } else {
  661. log_fn(LOG_WARN,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
  662. goto err;
  663. }
  664. tok = find_first_by_keyword(tokens, K_PORTS);
  665. if (tok && ports_set) {
  666. log_fn(LOG_WARN,"Redundant ports line");
  667. goto err;
  668. } else if (tok) {
  669. if (tok->n_args != 3) {
  670. log_fn(LOG_WARN,"Wrong # of arguments to \"ports\"");
  671. goto err;
  672. }
  673. router->or_port = atoi(tok->args[0]);
  674. router->socks_port = atoi(tok->args[1]);
  675. router->dir_port = atoi(tok->args[2]);
  676. ports_set = 1;
  677. }
  678. tok = find_first_by_keyword(tokens, K_DIRCACHEPORT);
  679. if (tok) {
  680. if (router->dir_port)
  681. log_fn(LOG_WARN,"Redundant dircacheport line");
  682. if (tok->n_args != 1) {
  683. log_fn(LOG_WARN,"Wrong # of arguments to \"dircacheport\"");
  684. goto err;
  685. }
  686. router->dir_port = atoi(tok->args[0]);
  687. }
  688. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  689. if (tok && bw_set) {
  690. log_fn(LOG_WARN,"Redundant bandwidth line");
  691. goto err;
  692. } else if (tok) {
  693. /* XXX set this to "< 3" once 0.0.7 is obsolete */
  694. if (tok->n_args < 2) {
  695. log_fn(LOG_WARN,"Not enough arguments to \"bandwidth\"");
  696. goto err;
  697. }
  698. router->bandwidthrate = atoi(tok->args[0]);
  699. router->bandwidthburst = atoi(tok->args[1]);
  700. if(tok->n_args > 2)
  701. router->advertisedbandwidth = atoi(tok->args[2]);
  702. bw_set = 1;
  703. }
  704. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  705. log_fn(LOG_WARN, "Missing published time"); goto err;
  706. }
  707. tor_assert(tok->n_args == 1);
  708. if (parse_time(tok->args[0], &router->published_on) < 0)
  709. goto err;
  710. if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
  711. log_fn(LOG_WARN, "Missing onion key"); goto err;
  712. }
  713. /* XXX Check key length */
  714. router->onion_pkey = tok->key;
  715. tok->key = NULL; /* Prevent free */
  716. if ((tok = find_first_by_keyword(tokens, K_LINK_KEY))) {
  717. log_fn(LOG_INFO, "Skipping obsolete link-key");
  718. }
  719. if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
  720. log_fn(LOG_WARN, "Missing identity key"); goto err;
  721. }
  722. /* XXX Check key length */
  723. router->identity_pkey = tok->key;
  724. tok->key = NULL; /* Prevent free */
  725. if (crypto_pk_get_digest(router->identity_pkey,router->identity_digest)){
  726. log_fn(LOG_WARN, "Couldn't calculate key digest"); goto err;
  727. }
  728. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  729. router->platform = tor_strdup(tok->args[0]);
  730. }
  731. exit_policy_tokens = find_all_exitpolicy(tokens);
  732. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  733. if (router_add_exit_policy(router,t)<0) {
  734. log_fn(LOG_WARN,"Error in exit policy"); goto err;}
  735. );
  736. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
  737. log_fn(LOG_WARN, "Missing router signature"); goto err;
  738. }
  739. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  740. log_fn(LOG_WARN, "Bad object type or length on router signature");
  741. goto err;
  742. }
  743. if ((t=crypto_pk_public_checksig(router->identity_pkey, tok->object_body,
  744. 128, signed_digest)) != 20) {
  745. log_fn(LOG_WARN, "Invalid signature %d",t); goto err;
  746. }
  747. if (memcmp(digest, signed_digest, 20)) {
  748. log_fn(LOG_WARN, "Mismatched signature"); goto err;
  749. }
  750. if (!ports_set) {
  751. log_fn(LOG_WARN,"No ports declared; failing."); goto err;
  752. }
  753. if (!bw_set) {
  754. log_fn(LOG_WARN,"No bandwidth declared; failing."); goto err;
  755. }
  756. if(!router->or_port) {
  757. log_fn(LOG_WARN,"or_port unreadable or 0. Failing.");
  758. goto err;
  759. }
  760. if (!router->bandwidthrate) {
  761. log_fn(LOG_WARN,"bandwidthrate unreadable or 0. Failing.");
  762. goto err;
  763. }
  764. if (!router->platform) {
  765. router->platform = tor_strdup("<unknown>");
  766. }
  767. log_fn(LOG_DEBUG,"or_port %d, socks_port %d, dir_port %d, bandwidthrate %u, bandwidthburst %u.",
  768. router->or_port, router->socks_port, router->dir_port,
  769. (unsigned) router->bandwidthrate, (unsigned) router->bandwidthburst);
  770. goto done;
  771. return router;
  772. err:
  773. routerinfo_free(router);
  774. router = NULL;
  775. done:
  776. if (tokens) {
  777. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  778. smartlist_free(tokens);
  779. }
  780. if (exit_policy_tokens) {
  781. smartlist_free(exit_policy_tokens);
  782. }
  783. return router;
  784. }
  785. /** Parse the exit policy in the string <b>s</b> and return it.
  786. */
  787. struct exit_policy_t *
  788. router_parse_exit_policy_from_string(const char *s)
  789. {
  790. directory_token_t *tok = NULL;
  791. const char *cp;
  792. char *tmp;
  793. struct exit_policy_t *r;
  794. int len, idx;
  795. /* *s might not end with \n, so we need to extend it with one. */
  796. len = strlen(s);
  797. cp = tmp = tor_malloc(len+2);
  798. for (idx = 0; idx < len; ++idx) {
  799. tmp[idx] = tolower(s[idx]);
  800. }
  801. tmp[len]='\n';
  802. tmp[len+1]='\0';
  803. tok = get_next_token(&cp, RTR_ONLY);
  804. if (tok->tp == _ERR) {
  805. log_fn(LOG_WARN, "Error reading exit policy: %s", tok->error);
  806. goto err;
  807. }
  808. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  809. log_fn(LOG_WARN, "Expected 'accept' or 'reject'.");
  810. goto err;
  811. }
  812. /* Now that we've gotten an exit policy, add it to the router. */
  813. r = router_parse_exit_policy(tok);
  814. goto done;
  815. err:
  816. r = NULL;
  817. done:
  818. free(tmp);
  819. token_free(tok);
  820. return r;
  821. }
  822. int router_add_exit_policy_from_string(routerinfo_t *router, const char *s)
  823. {
  824. struct exit_policy_t *newe, *tmpe;
  825. newe = router_parse_exit_policy_from_string(s);
  826. if (!newe)
  827. return -1;
  828. for (tmpe = router->exit_policy; tmpe; tmpe=tmpe->next)
  829. ;
  830. tmpe->next = newe;
  831. return 0;
  832. }
  833. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok)
  834. {
  835. struct exit_policy_t *newe, **tmpe;
  836. newe = router_parse_exit_policy(tok);
  837. if (!newe)
  838. return -1;
  839. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  840. ;
  841. *tmpe = newe;
  842. return 0;
  843. }
  844. /** Given a K_ACCEPT or K_REJECT token and a router, create a new exit_policy_t
  845. * corresponding to the token, and add it to <b>router</b> */
  846. static struct exit_policy_t *
  847. router_parse_exit_policy(directory_token_t *tok) {
  848. struct exit_policy_t*newe;
  849. struct in_addr in;
  850. char *arg, *address, *mask, *port, *endptr;
  851. int bits;
  852. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  853. if (tok->n_args != 1)
  854. return NULL;
  855. arg = tok->args[0];
  856. newe = tor_malloc_zero(sizeof(struct exit_policy_t));
  857. newe->string = tor_malloc(8+strlen(arg));
  858. if (tok->tp == K_REJECT) {
  859. strcpy(newe->string, "reject ");
  860. newe->policy_type = EXIT_POLICY_REJECT;
  861. } else {
  862. strcpy(newe->string, "accept ");
  863. newe->policy_type = EXIT_POLICY_ACCEPT;
  864. }
  865. strcat(newe->string, arg); /* can't overflow */
  866. address = arg;
  867. mask = strchr(arg,'/');
  868. port = strchr(mask?mask:arg,':');
  869. /* Break 'arg' into separate strings. 'arg' was already strdup'd by
  870. * _router_get_next_token, so it's safe to modify.
  871. */
  872. if (mask)
  873. *mask++ = 0;
  874. if (port)
  875. *port++ = 0;
  876. if (strcmp(address, "*") == 0) {
  877. newe->addr = 0;
  878. } else if (tor_inet_aton(address, &in) != 0) {
  879. newe->addr = ntohl(in.s_addr);
  880. } else {
  881. log_fn(LOG_WARN, "Malformed IP %s in exit policy; rejecting.",
  882. address);
  883. goto policy_read_failed;
  884. }
  885. if (!mask) {
  886. if (strcmp(address, "*") == 0)
  887. newe->msk = 0;
  888. else
  889. newe->msk = 0xFFFFFFFFu;
  890. } else {
  891. endptr = NULL;
  892. bits = (int) strtol(mask, &endptr, 10);
  893. if (!*endptr) {
  894. /* strtol handled the whole mask. */
  895. newe->msk = ~((1<<(32-bits))-1);
  896. } else if (tor_inet_aton(mask, &in) != 0) {
  897. newe->msk = ntohl(in.s_addr);
  898. } else {
  899. log_fn(LOG_WARN, "Malformed mask %s on exit policy; rejecting.",
  900. mask);
  901. goto policy_read_failed;
  902. }
  903. }
  904. if (!port || strcmp(port, "*") == 0) {
  905. newe->prt_min = 0;
  906. newe->prt_max = 65535;
  907. } else {
  908. endptr = NULL;
  909. newe->prt_min = (uint16_t) strtol(port, &endptr, 10);
  910. if (*endptr == '-') {
  911. port = endptr+1;
  912. endptr = NULL;
  913. newe->prt_max = (uint16_t) strtol(port, &endptr, 10);
  914. if (*endptr) {
  915. log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
  916. port);
  917. }
  918. } else if (*endptr) {
  919. log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
  920. port);
  921. goto policy_read_failed;
  922. } else {
  923. newe->prt_max = newe->prt_min;
  924. }
  925. }
  926. in.s_addr = htonl(newe->addr);
  927. address = tor_strdup(inet_ntoa(in));
  928. in.s_addr = htonl(newe->msk);
  929. log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
  930. newe->policy_type == EXIT_POLICY_REJECT ? "reject" : "accept",
  931. address, inet_ntoa(in), newe->prt_min, newe->prt_max);
  932. tor_free(address);
  933. newe->next = NULL;
  934. return newe;
  935. policy_read_failed:
  936. tor_assert(newe->string);
  937. log_fn(LOG_WARN,"Couldn't parse line '%s'. Dropping", newe->string);
  938. tor_free(newe->string);
  939. free(newe);
  940. return NULL;
  941. }
  942. /*
  943. * Low-level tokenizer for router descriptors and directories.
  944. */
  945. /** Free all resources allocated for <b>tok</b> */
  946. static void
  947. token_free(directory_token_t *tok)
  948. {
  949. int i;
  950. tor_assert(tok);
  951. if (tok->args) {
  952. for (i = 0; i < tok->n_args; ++i) {
  953. tor_free(tok->args[i]);
  954. }
  955. tor_free(tok->args);
  956. }
  957. tor_free(tok->object_type);
  958. tor_free(tok->object_body);
  959. if (tok->key)
  960. crypto_free_pk_env(tok->key);
  961. tor_free(tok);
  962. }
  963. /** Helper function: read the next token from *s, advance *s to the end
  964. * of the token, and return the parsed token. If 'where' is DIR_ONLY
  965. * or RTR_ONLY, reject all tokens of the wrong type.
  966. */
  967. static directory_token_t *
  968. get_next_token(const char **s, where_syntax where) {
  969. const char *next, *obstart;
  970. int i, done, allocated, is_opt;
  971. directory_token_t *tok;
  972. arg_syntax a_syn;
  973. obj_syntax o_syn = NO_OBJ;
  974. #define RET_ERR(msg) \
  975. do { if (tok) token_free(tok); \
  976. tok = tor_malloc_zero(sizeof(directory_token_t));\
  977. tok->tp = _ERR; \
  978. tok->error = msg; \
  979. goto done_tokenizing; } while (0)
  980. tok = tor_malloc_zero(sizeof(directory_token_t));
  981. tok->tp = _ERR;
  982. *s = eat_whitespace(*s);
  983. if (!**s) {
  984. tok->tp = _EOF;
  985. return tok;
  986. }
  987. next = find_whitespace(*s);
  988. if (!next) {
  989. tok->error = "Unexpected EOF"; return tok;
  990. }
  991. /* It's a keyword... but which one? */
  992. is_opt = !strncmp("opt", *s, next-*s);
  993. if (is_opt) {
  994. *s = eat_whitespace(next);
  995. next = NULL;
  996. if (**s)
  997. next = find_whitespace(*s);
  998. if (!**s || !next) {
  999. RET_ERR("opt without keyword");
  1000. }
  1001. }
  1002. for (i = 0; token_table[i].t ; ++i) {
  1003. if (!strncmp(token_table[i].t, *s, next-*s)) {
  1004. /* We've found the keyword. */
  1005. tok->tp = token_table[i].v;
  1006. a_syn = token_table[i].s;
  1007. o_syn = token_table[i].os;
  1008. if (token_table[i].ws != ANY && token_table[i].ws != where) {
  1009. if (where == DIR_ONLY) {
  1010. RET_ERR("Found a router-only token in a directory section");
  1011. } else {
  1012. RET_ERR("Found a directory-only token in a router descriptor");
  1013. }
  1014. }
  1015. if (a_syn == ARGS) {
  1016. /* This keyword takes multiple arguments. */
  1017. i = 0;
  1018. done = (*next == '\n');
  1019. allocated = 32;
  1020. tok->args = tor_malloc(sizeof(char*)*32);
  1021. *s = eat_whitespace_no_nl(next);
  1022. while (**s != '\n' && !done) {
  1023. next = find_whitespace(*s);
  1024. if (*next == '\n')
  1025. done = 1;
  1026. if (i == allocated) {
  1027. allocated *= 2;
  1028. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1029. }
  1030. tok->args[i++] = tor_strndup(*s,next-*s);
  1031. *s = eat_whitespace_no_nl(next+1);
  1032. }
  1033. tok->n_args = i;
  1034. } else if (a_syn == CONCAT_ARGS) {
  1035. /* The keyword takes the line as a single argument */
  1036. *s = eat_whitespace_no_nl(next);
  1037. next = strchr(*s, '\n');
  1038. if (!next)
  1039. RET_ERR("Unexpected EOF");
  1040. tok->args = tor_malloc(sizeof(char*));
  1041. tok->args[0] = tor_strndup(*s,next-*s);
  1042. tok->n_args = 1;
  1043. *s = eat_whitespace_no_nl(next+1);
  1044. } else {
  1045. /* The keyword takes no arguments. */
  1046. tor_assert(a_syn == NO_ARGS);
  1047. *s = eat_whitespace_no_nl(next);
  1048. if (**s != '\n') {
  1049. RET_ERR("Unexpected arguments");
  1050. }
  1051. tok->n_args = 0;
  1052. *s = eat_whitespace_no_nl(*s+1);
  1053. }
  1054. break;
  1055. }
  1056. }
  1057. if (tok->tp == _ERR) {
  1058. if (is_opt) {
  1059. tok->tp = K_OPT;
  1060. *s = eat_whitespace_no_nl(next);
  1061. next = strchr(*s,'\n');
  1062. if (!next)
  1063. RET_ERR("Unexpected EOF");
  1064. tok->args = tor_malloc(sizeof(char*));
  1065. tok->args[0] = tor_strndup(*s,next-*s);
  1066. tok->n_args = 1;
  1067. *s = eat_whitespace_no_nl(next+1);
  1068. a_syn = OBJ_OK;
  1069. } else {
  1070. tok->tp = _UNRECOGNIZED;
  1071. next = strchr(*s, '\n');
  1072. if (!next) {
  1073. RET_ERR("Unexpected EOF");
  1074. }
  1075. tok->args = tor_malloc(sizeof(char*));
  1076. tok->args[0] = tor_strndup(*s,next-*s);
  1077. tok->n_args = 1;
  1078. *s = next+1;
  1079. o_syn = OBJ_OK;
  1080. }
  1081. }
  1082. *s = eat_whitespace(*s);
  1083. if (strncmp(*s, "-----BEGIN ", 11)) {
  1084. goto done_tokenizing;
  1085. }
  1086. obstart = *s;
  1087. *s += 11; /* length of "-----BEGIN ". */
  1088. next = strchr(*s, '\n');
  1089. if (next-*s < 6 || strncmp(next-5, "-----\n", 6)) {
  1090. RET_ERR("Malformed object: bad begin line");
  1091. }
  1092. tok->object_type = tor_strndup(*s, next-*s-5);
  1093. *s = next+1;
  1094. next = strstr(*s, "-----END ");
  1095. if (!next) {
  1096. RET_ERR("Malformed object: missing end line");
  1097. }
  1098. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1099. if (strncmp(next, "-----END RSA PUBLIC KEY-----\n", 29))
  1100. RET_ERR("Malformed object: mismatched end line");
  1101. next = strchr(next,'\n')+1;
  1102. tok->key = crypto_new_pk_env();
  1103. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1104. RET_ERR("Couldn't parse public key.");
  1105. *s = next;
  1106. } else {
  1107. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1108. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1109. if (i<0) {
  1110. RET_ERR("Malformed object: bad base64-encoded data");
  1111. }
  1112. tok->object_size = i;
  1113. *s = next + 9; /* length of "-----END ". */
  1114. i = strlen(tok->object_type);
  1115. if (strncmp(*s, tok->object_type, i) || strncmp(*s+i, "-----\n", 6)) {
  1116. RET_ERR("Malformed object: mismatched end tag");
  1117. }
  1118. *s += i+6;
  1119. }
  1120. switch(o_syn)
  1121. {
  1122. case NO_OBJ:
  1123. if (tok->object_body)
  1124. RET_ERR("Unexpected object for keyword");
  1125. if (tok->key)
  1126. RET_ERR("Unexpected public key for keyword");
  1127. break;
  1128. case NEED_OBJ:
  1129. if (!tok->object_body)
  1130. RET_ERR("Missing object for keyword");
  1131. break;
  1132. case NEED_KEY:
  1133. if (!tok->key)
  1134. RET_ERR("Missing publid key for keyword");
  1135. break;
  1136. case OBJ_OK:
  1137. break;
  1138. }
  1139. done_tokenizing:
  1140. #if 0
  1141. for (i = 0; token_table[i].t ; ++i) {
  1142. if (token_table[i].v == tok->tp) {
  1143. fputs(token_table[i].t, stdout);
  1144. break;
  1145. i = -1;
  1146. }
  1147. }
  1148. if (i) {
  1149. if (tok->tp == _UNRECOGNIZED) fputs("UNRECOGNIZED", stdout);
  1150. if (tok->tp == _ERR) fputs("ERR",stdout);
  1151. if (tok->tp == _EOF) fputs("EOF",stdout);
  1152. if (tok->tp == _NIL) fputs("_NIL",stdout);
  1153. }
  1154. for(i = 0; i < tok->n_args; ++i) {
  1155. fprintf(stdout," \"%s\"", tok->args[i]);
  1156. }
  1157. if (tok->error) { fprintf(stdout," *%s*", tok->error); }
  1158. fputs("\n",stdout);
  1159. #endif
  1160. return tok;
  1161. #undef RET_ERR
  1162. }
  1163. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1164. * them to <b>out</b>. If <b>is_dir</b> is true, reject all non-directory
  1165. * tokens; else reject all non-routerdescriptor tokens.
  1166. */
  1167. static int
  1168. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1169. int is_dir)
  1170. {
  1171. const char **s;
  1172. directory_token_t *tok = NULL;
  1173. where_syntax where = is_dir ? DIR_ONLY : RTR_ONLY;
  1174. s = &start;
  1175. while (*s < end && (!tok || tok->tp != _EOF)) {
  1176. tok = get_next_token(s, where);
  1177. if (tok->tp == _ERR) {
  1178. log_fn(LOG_WARN, "parse error: %s", tok->error);
  1179. return -1;
  1180. }
  1181. smartlist_add(out, tok);
  1182. *s = eat_whitespace(*s);
  1183. }
  1184. return 0;
  1185. }
  1186. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1187. * NULL if no such keyword is found.
  1188. */
  1189. static directory_token_t *
  1190. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1191. {
  1192. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1193. return NULL;
  1194. }
  1195. /** Return a newly allocated smartlist of all accept or reject tokens in
  1196. * <b>s</b>.
  1197. */
  1198. static smartlist_t *
  1199. find_all_exitpolicy(smartlist_t *s)
  1200. {
  1201. smartlist_t *out = smartlist_create();
  1202. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1203. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1204. smartlist_add(out,t));
  1205. return out;
  1206. }
  1207. /** Compute the SHA digest of the substring of <b>s</b> taken from the first
  1208. * occurrence of <b>start_str</b> through the first newline after the first
  1209. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1210. * <b>digest</b>; return 0 on success.
  1211. *
  1212. * If no such substring exists, return -1.
  1213. */
  1214. static int router_get_hash_impl(const char *s, char *digest,
  1215. const char *start_str,
  1216. const char *end_str)
  1217. {
  1218. char *start, *end;
  1219. start = strstr(s, start_str);
  1220. if (!start) {
  1221. log_fn(LOG_WARN,"couldn't find \"%s\"",start_str);
  1222. return -1;
  1223. }
  1224. if (start != s && *(start-1) != '\n') {
  1225. log_fn(LOG_WARN, "first occurance of \"%s\" is not at the start of a line",
  1226. start_str);
  1227. return -1;
  1228. }
  1229. end = strstr(start+strlen(start_str), end_str);
  1230. if (!end) {
  1231. log_fn(LOG_WARN,"couldn't find \"%s\"",end_str);
  1232. return -1;
  1233. }
  1234. end = strchr(end, '\n');
  1235. if (!end) {
  1236. log_fn(LOG_WARN,"couldn't find EOL");
  1237. return -1;
  1238. }
  1239. ++end;
  1240. if (crypto_digest(start, end-start, digest)) {
  1241. log_fn(LOG_WARN,"couldn't compute digest");
  1242. return -1;
  1243. }
  1244. return 0;
  1245. }
  1246. int tor_version_parse(const char *s, tor_version_t *out)
  1247. {
  1248. char *eos=NULL, *cp=NULL;
  1249. /* Format is:
  1250. * NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ -cvs ] ]
  1251. */
  1252. tor_assert(s && out);
  1253. memset(out, 0, sizeof(tor_version_t));
  1254. /* Get major. */
  1255. out->major = strtol(s,&eos,10);
  1256. if (!eos || eos==s || *eos != '.') return -1;
  1257. cp = eos+1;
  1258. /* Get minor */
  1259. out->minor = strtol(cp,&eos,10);
  1260. if (!eos || eos==cp || *eos != '.') return -1;
  1261. cp = eos+1;
  1262. /* Get micro */
  1263. out->micro = strtol(cp,&eos,10);
  1264. if (!eos || eos==cp) return -1;
  1265. if (!*eos) {
  1266. out->status = VER_RELEASE;
  1267. out->patchlevel = 0;
  1268. out->cvs = IS_NOT_CVS;
  1269. return 0;
  1270. }
  1271. cp = eos;
  1272. /* Get status */
  1273. if (*cp == '.') {
  1274. out->status = VER_RELEASE;
  1275. ++cp;
  1276. } else if (0==strncmp(cp, "pre", 3)) {
  1277. out->status = VER_PRE;
  1278. cp += 3;
  1279. } else if (0==strncmp(cp, "rc", 2)) {
  1280. out->status = VER_RC;
  1281. cp += 2;
  1282. } else {
  1283. return -1;
  1284. }
  1285. /* Get patchlevel */
  1286. out->patchlevel = strtol(cp,&eos,10);
  1287. if (!eos || eos==cp) return -1;
  1288. cp = eos;
  1289. /* Get cvs status. */
  1290. if (!*eos) {
  1291. out->cvs = IS_NOT_CVS;
  1292. } else if (0==strcmp(cp, "-cvs")) {
  1293. out->cvs = IS_CVS;
  1294. } else {
  1295. return -1;
  1296. }
  1297. return 0;
  1298. }
  1299. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  1300. * b. */
  1301. int tor_version_compare(tor_version_t *a, tor_version_t *b)
  1302. {
  1303. int i;
  1304. tor_assert(a && b);
  1305. if ((i = a->major - b->major))
  1306. return i;
  1307. else if ((i = a->minor - b->minor))
  1308. return i;
  1309. else if ((i = a->micro - b->micro))
  1310. return i;
  1311. else if ((i = a->status - b->status))
  1312. return i;
  1313. else if ((i = a->patchlevel - b->patchlevel))
  1314. return i;
  1315. else if ((i = a->cvs - b->cvs))
  1316. return i;
  1317. else
  1318. return 0;
  1319. }
  1320. /*
  1321. Local Variables:
  1322. mode:c
  1323. indent-tabs-mode:nil
  1324. c-basic-offset:2
  1325. End:
  1326. */