routerparse.c 49 KB

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