routerparse.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerparse_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file routerparse.c
  10. * \brief Code to parse and validate router descriptors and directories.
  11. **/
  12. #include "or.h"
  13. /****************************************************************************/
  14. /** Enumeration of possible token types. The ones starting with K_
  15. * correspond to directory 'keywords'. _UNRECOGNIZED is for an
  16. * unrecognized keyword; _ERR is an error in the tokenizing process,
  17. * _EOF is an end-of-file marker, and _NIL is used to encode
  18. * not-a-token.
  19. */
  20. typedef enum {
  21. K_ACCEPT,
  22. K_DIRECTORY_SIGNATURE,
  23. K_RECOMMENDED_SOFTWARE,
  24. K_REJECT,
  25. K_ROUTER,
  26. K_SIGNED_DIRECTORY,
  27. K_SIGNING_KEY,
  28. K_ONION_KEY,
  29. K_ROUTER_SIGNATURE,
  30. K_PUBLISHED,
  31. K_RUNNING_ROUTERS,
  32. K_ROUTER_STATUS,
  33. K_PLATFORM,
  34. K_OPT,
  35. K_BANDWIDTH,
  36. K_PORTS,
  37. K_CONTACT,
  38. K_NETWORK_STATUS,
  39. K_UPTIME,
  40. K_DIR_SIGNING_KEY,
  41. K_FAMILY,
  42. K_FINGERPRINT,
  43. K_HIBERNATING,
  44. K_READ_HISTORY,
  45. K_WRITE_HISTORY,
  46. K_NETWORK_STATUS_VERSION,
  47. K_DIR_SOURCE,
  48. K_DIR_OPTIONS,
  49. K_CLIENT_VERSIONS,
  50. K_SERVER_VERSIONS,
  51. K_R,
  52. K_S,
  53. K_EVENTDNS,
  54. _UNRECOGNIZED,
  55. _ERR,
  56. _EOF,
  57. _NIL
  58. } directory_keyword;
  59. /** Structure to hold a single directory token.
  60. *
  61. * We parse a directory by breaking it into "tokens", each consisting
  62. * of a keyword, a line full of arguments, and a binary object. The
  63. * arguments and object are both optional, depending on the keyword
  64. * type.
  65. */
  66. typedef struct directory_token_t {
  67. directory_keyword tp; /**< Type of the token. */
  68. int n_args; /**< Number of elements in args */
  69. char **args; /**< Array of arguments from keyword line. */
  70. char *object_type; /**< -----BEGIN [object_type]-----*/
  71. size_t object_size; /**< Bytes in object_body */
  72. char *object_body; /**< Contents of object, base64-decoded. */
  73. crypto_pk_env_t *key; /**< For public keys only. */
  74. const char *error; /**< For _ERR tokens only. */
  75. } directory_token_t;
  76. /* ********************************************************************** */
  77. /** We use a table of rules to decide how to parse each token type. */
  78. /** Rules for how many arguments a keyword can take. */
  79. typedef enum {
  80. NO_ARGS, /**< No arguments, ever. */
  81. ARGS, /**< A list of arguments separated by spaces. */
  82. CONCAT_ARGS, /**< The rest of the line, treated as a single argument. */
  83. } arg_syntax;
  84. /** Rules for whether the keyword needs an object. */
  85. typedef enum {
  86. NO_OBJ, /**< No object, ever. */
  87. NEED_OBJ, /**< Object is required. */
  88. NEED_KEY, /**< Object is required, and must be a public key. */
  89. OBJ_OK, /**< Object is optional. */
  90. } obj_syntax;
  91. /** Rules for where a keyword can appear. */
  92. typedef enum {
  93. DIR = 1, /**< Appears only in directory. */
  94. RTR = 2, /**< Appears only in router descriptor or runningrouters. */
  95. NETSTATUS = 4, /**< v2 or later ("versioned") network status. */
  96. ANYSIGNED = 7, /**< Any "full" document (that is, not a router status.) */
  97. RTRSTATUS = 8, /**< Router-status portion of a versioned network status. */
  98. ANY = 15, /**< Appears in any document type. */
  99. } where_syntax;
  100. /** Table mapping keywords to token value and to argument rules. */
  101. static struct {
  102. const char *t; directory_keyword v; arg_syntax s; obj_syntax os; int ws;
  103. } token_table[] = {
  104. { "accept", K_ACCEPT, ARGS, NO_OBJ, RTR },
  105. { "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ,
  106. DIR|NETSTATUS},
  107. { "r", K_R, ARGS, NO_OBJ, RTRSTATUS },
  108. { "s", K_S, ARGS, NO_OBJ, RTRSTATUS },
  109. { "reject", K_REJECT, ARGS, NO_OBJ, RTR },
  110. { "router", K_ROUTER, ARGS, NO_OBJ, RTR },
  111. { "recommended-software",K_RECOMMENDED_SOFTWARE,ARGS, NO_OBJ, DIR },
  112. { "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ, DIR },
  113. { "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY,RTR },
  114. { "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY,RTR },
  115. { "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ,RTR },
  116. { "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ, DIR },
  117. { "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ, DIR },
  118. { "bandwidth", K_BANDWIDTH, ARGS, NO_OBJ, RTR },
  119. { "platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ, RTR },
  120. { "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ, ANYSIGNED },
  121. { "opt", K_OPT, CONCAT_ARGS, OBJ_OK, ANY },
  122. { "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ, ANYSIGNED },
  123. { "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ, DIR },
  124. { "uptime", K_UPTIME, ARGS, NO_OBJ, RTR },
  125. { "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK,
  126. DIR|NETSTATUS},
  127. { "family", K_FAMILY, ARGS, NO_OBJ, RTR },
  128. { "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ, ANYSIGNED },
  129. { "hibernating", K_HIBERNATING, ARGS, NO_OBJ, RTR },
  130. { "read-history", K_READ_HISTORY, ARGS, NO_OBJ, RTR },
  131. { "write-history", K_WRITE_HISTORY, ARGS, NO_OBJ, RTR },
  132. { "network-status-version", K_NETWORK_STATUS_VERSION,
  133. ARGS, NO_OBJ, NETSTATUS },
  134. { "dir-source", K_DIR_SOURCE, ARGS, NO_OBJ, NETSTATUS },
  135. { "dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ, NETSTATUS },
  136. { "client-versions", K_CLIENT_VERSIONS, ARGS, NO_OBJ, NETSTATUS },
  137. { "server-versions", K_SERVER_VERSIONS, ARGS, NO_OBJ, NETSTATUS },
  138. { "eventdns", K_EVENTDNS, ARGS, NO_OBJ, RTR },
  139. { NULL, -1, NO_ARGS, NO_OBJ, ANY }
  140. };
  141. /* static function prototypes */
  142. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  143. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
  144. static addr_policy_t *router_parse_private_addr_policy_private(
  145. directory_token_t *tok);
  146. static int router_get_hash_impl(const char *s, char *digest,
  147. const char *start_str, const char *end_str);
  148. static void token_free(directory_token_t *tok);
  149. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  150. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  151. directory_keyword keyword);
  152. static int tokenize_string(const char *start, const char *end,
  153. smartlist_t *out, where_syntax where);
  154. static directory_token_t *get_next_token(const char **s, where_syntax where);
  155. static int check_directory_signature(const char *digest,
  156. directory_token_t *tok,
  157. crypto_pk_env_t *pkey,
  158. crypto_pk_env_t *declared_key,
  159. int check_authority);
  160. static crypto_pk_env_t *find_dir_signing_key(const char *str);
  161. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  162. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  163. * <b>s</b>. Return 0 on success, -1 on failure.
  164. */
  165. int
  166. router_get_dir_hash(const char *s, char *digest)
  167. {
  168. return router_get_hash_impl(s,digest,
  169. "signed-directory","\ndirectory-signature");
  170. }
  171. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  172. * <b>s</b>. Return 0 on success, -1 on failure.
  173. */
  174. int
  175. router_get_router_hash(const char *s, char *digest)
  176. {
  177. return router_get_hash_impl(s,digest,
  178. "router ","\nrouter-signature");
  179. }
  180. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  181. * string in <b>s</b>. Return 0 on success, -1 on failure.
  182. */
  183. int
  184. router_get_runningrouters_hash(const char *s, char *digest)
  185. {
  186. return router_get_hash_impl(s,digest,
  187. "network-status","\ndirectory-signature");
  188. }
  189. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  190. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  191. int
  192. router_get_networkstatus_v2_hash(const char *s, char *digest)
  193. {
  194. return router_get_hash_impl(s,digest,
  195. "network-status-version","\ndirectory-signature");
  196. }
  197. /** Helper: used to generate signatures for routers, directories and
  198. * network-status objects. Given a digest in <b>digest</b> and a secret
  199. * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
  200. * surround it with -----BEGIN/END----- pairs, and write it to the
  201. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  202. * failure.
  203. */
  204. int
  205. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  206. crypto_pk_env_t *private_key)
  207. {
  208. char signature[PK_BYTES];
  209. int i;
  210. if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
  211. log_warn(LD_BUG,"Couldn't sign digest.");
  212. return -1;
  213. }
  214. if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  215. goto truncated;
  216. i = strlen(buf);
  217. if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
  218. log_warn(LD_BUG,"couldn't base64-encode signature");
  219. tor_free(buf);
  220. return -1;
  221. }
  222. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  223. goto truncated;
  224. return 0;
  225. truncated:
  226. log_warn(LD_BUG,"tried to exceed string length.");
  227. return -1;
  228. }
  229. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  230. * <b>versionlist</b>. Else, return VS_OLD if every member of
  231. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  232. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  233. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  234. * is newer than <b>myversion.</b>. Else, return VS_NEW if every memeber of
  235. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  236. * VS_UNRECOMMENDED.
  237. *
  238. * (versionlist is a comma-separated list of version strings,
  239. * optionally prefixed with "Tor". Versions that can't be parsed are
  240. * ignored.)
  241. */
  242. version_status_t
  243. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  244. {
  245. tor_version_t mine, other;
  246. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  247. found_any_in_series = 0, r, same;
  248. version_status_t ret = VS_UNRECOMMENDED;
  249. smartlist_t *version_sl;
  250. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  251. myversion, versionlist);
  252. if (tor_version_parse(myversion, &mine)) {
  253. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  254. tor_assert(0);
  255. }
  256. version_sl = smartlist_create();
  257. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  258. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  259. if (!strcmpstart(cp, "Tor "))
  260. cp += 4;
  261. if (tor_version_parse(cp, &other)) {
  262. /* Couldn't parse other; it can't be a match. */
  263. } else {
  264. same = tor_version_same_series(&mine, &other);
  265. if (same)
  266. found_any_in_series = 1;
  267. r = tor_version_compare(&mine, &other);
  268. if (r==0) {
  269. ret = VS_RECOMMENDED;
  270. goto done;
  271. } else if (r<0) {
  272. found_newer = 1;
  273. if (same)
  274. found_newer_in_series = 1;
  275. } else if (r>0) {
  276. found_older = 1;
  277. }
  278. }
  279. });
  280. /* We didn't find the listed version. Is it new or old? */
  281. if (found_any_in_series && !found_newer_in_series) {
  282. ret = VS_NEW_IN_SERIES;
  283. } else if (found_newer && !found_older) {
  284. ret = VS_OLD;
  285. } else if (found_older && !found_newer) {
  286. ret = VS_NEW;
  287. } else {
  288. ret = VS_UNRECOMMENDED;
  289. }
  290. done:
  291. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  292. smartlist_free(version_sl);
  293. return ret;
  294. }
  295. /** Return the combined status of the current version, given that we know of
  296. * one set of networkstatuses that give us status <b>a</b>, and another that
  297. * gives us status <b>b</b>.
  298. *
  299. * For example, if one authority thinks that we're NEW, and another thinks
  300. * we're OLD, we're simply UNRECOMMENDED.
  301. *
  302. * This function does not handle calculating whether we're RECOMMENDED; that
  303. * follows a simple majority rule. This function simply calculates *why*
  304. * we're not recommended (if we're not).
  305. */
  306. version_status_t
  307. version_status_join(version_status_t a, version_status_t b)
  308. {
  309. if (a == b)
  310. return a;
  311. else if (a == VS_UNRECOMMENDED || b == VS_UNRECOMMENDED)
  312. return VS_UNRECOMMENDED;
  313. else if (a == VS_RECOMMENDED)
  314. return b;
  315. else if (b == VS_RECOMMENDED)
  316. return a;
  317. /* Okay. Neither is 'recommended' or 'unrecommended', and they differ. */
  318. else if (a == VS_OLD || b == VS_OLD)
  319. return VS_UNRECOMMENDED;
  320. /* One is VS_NEW, the other is VS_NEW_IN_SERIES */
  321. else
  322. return VS_NEW_IN_SERIES;
  323. }
  324. /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
  325. * Otherwise, return -1. If we're a directory cache, cache it.
  326. */
  327. int
  328. router_parse_directory(const char *str)
  329. {
  330. directory_token_t *tok;
  331. char digest[DIGEST_LEN];
  332. time_t published_on;
  333. int r;
  334. const char *end, *cp;
  335. smartlist_t *tokens = NULL;
  336. crypto_pk_env_t *declared_key = NULL;
  337. /* XXXX This could be simplified a lot, but it will all go away
  338. * once pre-0.1.1.8 is obsolete, and for now it's better not to
  339. * touch it. */
  340. if (router_get_dir_hash(str, digest)) {
  341. log_warn(LD_DIR, "Unable to compute digest of directory");
  342. goto err;
  343. }
  344. log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
  345. /* Check signature first, before we try to tokenize. */
  346. cp = str;
  347. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  348. cp = end;
  349. if (cp == str || !cp) {
  350. log_warn(LD_DIR, "No signature found on directory."); goto err;
  351. }
  352. ++cp;
  353. tokens = smartlist_create();
  354. if (tokenize_string(cp,strchr(cp,'\0'),tokens,DIR)) {
  355. log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
  356. }
  357. if (smartlist_len(tokens) != 1) {
  358. log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
  359. }
  360. tok=smartlist_get(tokens,0);
  361. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  362. log_warn(LD_DIR,"Expected a single directory signature"); goto err;
  363. }
  364. declared_key = find_dir_signing_key(str);
  365. if (check_directory_signature(digest, tok, NULL, declared_key, 1)<0)
  366. goto err;
  367. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  368. smartlist_free(tokens);
  369. tokens = NULL;
  370. /* Now try to parse the first part of the directory. */
  371. if ((end = strstr(str,"\nrouter "))) {
  372. ++end;
  373. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  374. ++end;
  375. } else {
  376. end = str + strlen(str);
  377. }
  378. tokens = smartlist_create();
  379. if (tokenize_string(str,end,tokens,DIR)) {
  380. log_warn(LD_DIR, "Error tokenizing directory"); goto err;
  381. }
  382. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  383. log_warn(LD_DIR, "Missing published time on directory.");
  384. goto err;
  385. }
  386. tor_assert(tok->n_args == 1);
  387. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  388. goto err;
  389. }
  390. /* Now that we know the signature is okay, and we have a
  391. * publication time, cache the directory. */
  392. if (get_options()->DirPort && !get_options()->V1AuthoritativeDir)
  393. dirserv_set_cached_directory(str, published_on, 0);
  394. r = 0;
  395. goto done;
  396. err:
  397. r = -1;
  398. done:
  399. if (declared_key) crypto_free_pk_env(declared_key);
  400. if (tokens) {
  401. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  402. smartlist_free(tokens);
  403. }
  404. return r;
  405. }
  406. /** Read a signed router status statement from <b>str</b>. If it's
  407. * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
  408. * cache it.*/
  409. int
  410. router_parse_runningrouters(const char *str)
  411. {
  412. char digest[DIGEST_LEN];
  413. directory_token_t *tok;
  414. time_t published_on;
  415. int r = -1;
  416. crypto_pk_env_t *declared_key = NULL;
  417. smartlist_t *tokens = NULL;
  418. if (router_get_runningrouters_hash(str, digest)) {
  419. log_warn(LD_DIR, "Unable to compute digest of running-routers");
  420. goto err;
  421. }
  422. tokens = smartlist_create();
  423. if (tokenize_string(str,str+strlen(str),tokens,DIR)) {
  424. log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
  425. }
  426. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  427. log_warn(LD_DIR, "Unrecognized keyword %s; can't parse running-routers",
  428. escaped(tok->args[0]));
  429. goto err;
  430. }
  431. tok = smartlist_get(tokens,0);
  432. if (tok->tp != K_NETWORK_STATUS) {
  433. log_warn(LD_DIR, "Network-status starts with wrong token");
  434. goto err;
  435. }
  436. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  437. log_warn(LD_DIR, "Missing published time on running-routers.");
  438. goto err;
  439. }
  440. tor_assert(tok->n_args == 1);
  441. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  442. goto err;
  443. }
  444. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  445. log_warn(LD_DIR, "Missing signature on running-routers");
  446. goto err;
  447. }
  448. declared_key = find_dir_signing_key(str);
  449. if (check_directory_signature(digest, tok, NULL, declared_key, 1) < 0)
  450. goto err;
  451. /* Now that we know the signature is okay, and we have a
  452. * publication time, cache the list. */
  453. if (get_options()->DirPort && !get_options()->V1AuthoritativeDir)
  454. dirserv_set_cached_directory(str, published_on, 1);
  455. r = 0;
  456. err:
  457. if (declared_key) crypto_free_pk_env(declared_key);
  458. if (tokens) {
  459. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  460. smartlist_free(tokens);
  461. }
  462. return r;
  463. }
  464. /** Given a directory or running-routers string in <b>str</b>, try to
  465. * find the its dir-signing-key token (if any). If this token is
  466. * present, extract and return the key. Return NULL on failure. */
  467. static crypto_pk_env_t *
  468. find_dir_signing_key(const char *str)
  469. {
  470. const char *cp;
  471. directory_token_t *tok;
  472. crypto_pk_env_t *key = NULL;
  473. /* Is there a dir-signing-key in the directory? */
  474. cp = strstr(str, "\nopt dir-signing-key");
  475. if (!cp)
  476. cp = strstr(str, "\ndir-signing-key");
  477. if (!cp)
  478. return NULL;
  479. ++cp; /* Now cp points to the start of the token. */
  480. tok = get_next_token(&cp, DIR);
  481. if (!tok) {
  482. log_warn(LD_DIR, "Unparseable dir-signing-key token");
  483. return NULL;
  484. }
  485. if (tok->tp != K_DIR_SIGNING_KEY) {
  486. log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
  487. return NULL;
  488. }
  489. if (tok->key) {
  490. key = tok->key;
  491. tok->key = NULL; /* steal reference. */
  492. } else {
  493. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  494. return NULL;
  495. }
  496. token_free(tok);
  497. return key;
  498. }
  499. /** Return true iff <b>key</b> is allowed to sign directories.
  500. */
  501. static int
  502. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  503. {
  504. char digest[DIGEST_LEN];
  505. if (!key) return 0;
  506. if (crypto_pk_get_digest(key, digest) < 0) {
  507. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  508. return 0;
  509. }
  510. if (!router_digest_is_trusted_dir(digest)) {
  511. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  512. return 0;
  513. }
  514. return 1;
  515. }
  516. /** Check whether the K_DIRECTORY_SIGNATURE token in <b>tok</b> has a
  517. * good signature for <b>digest</b>.
  518. *
  519. * If <b>declared_key</b> is set, the directory has declared what key
  520. * was used to sign it, so we will use that key only if it is an
  521. * authoritative directory signing key or if check_authority is 0.
  522. *
  523. * Otherwise, if pkey is provided, try to use it.
  524. *
  525. * (New callers should always use <b>declared_key</b> when possible;
  526. * <b>pkey</b> is only for debugging.)
  527. */
  528. static int
  529. check_directory_signature(const char *digest,
  530. directory_token_t *tok,
  531. crypto_pk_env_t *pkey,
  532. crypto_pk_env_t *declared_key,
  533. int check_authority)
  534. {
  535. char signed_digest[PK_BYTES];
  536. crypto_pk_env_t *_pkey = NULL;
  537. if (tok->n_args != 1) {
  538. log_warn(LD_DIR, "Too many or too few arguments to directory-signature");
  539. return -1;
  540. }
  541. if (declared_key) {
  542. if (!check_authority || dir_signing_key_is_trusted(declared_key))
  543. _pkey = declared_key;
  544. }
  545. if (!_pkey && pkey) {
  546. /* pkey provided for debugging purposes */
  547. _pkey = pkey;
  548. }
  549. if (!_pkey) {
  550. log_warn(LD_DIR,
  551. "Obsolete directory format (dir signing key not present) or "
  552. "signing key not trusted--rejecting.");
  553. return -1;
  554. }
  555. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  556. log_warn(LD_DIR, "Bad object type or length on directory signature");
  557. return -1;
  558. }
  559. tor_assert(_pkey);
  560. if (crypto_pk_public_checksig(_pkey, signed_digest, tok->object_body, 128)
  561. != 20) {
  562. log_warn(LD_DIR, "Error reading directory: invalid signature.");
  563. return -1;
  564. }
  565. log_debug(LD_DIR,"Signed directory hash starts %s",
  566. hex_str(signed_digest,4));
  567. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  568. log_warn(LD_DIR, "Error reading directory: signature does not match.");
  569. return -1;
  570. }
  571. return 0;
  572. }
  573. /** Given a string *<b>s</b> containing a concatenated sequence of router
  574. * descriptors, parses them and stores the result in <b>dest</b>. All routers
  575. * are marked running and valid. Advances *s to a point immediately
  576. * following the last router entry. Ignore any trailing router entries that
  577. * are not complete. Returns 0 on success and -1 on failure.
  578. * DOCDOC saved_location
  579. */
  580. int
  581. router_parse_list_from_string(const char **s, smartlist_t *dest,
  582. saved_location_t saved_location)
  583. {
  584. routerinfo_t *router;
  585. const char *end, *cp, *start;
  586. tor_assert(s);
  587. tor_assert(*s);
  588. tor_assert(dest);
  589. start = *s;
  590. while (1) {
  591. *s = eat_whitespace(*s);
  592. /* Don't start parsing the rest of *s unless it contains a router. */
  593. if (strcmpstart(*s, "router ")!=0)
  594. break;
  595. if ((end = strstr(*s+1, "\nrouter "))) {
  596. cp = end;
  597. end++;
  598. } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
  599. cp = end;
  600. end++;
  601. } else {
  602. cp = end = *s+strlen(*s);
  603. }
  604. while (cp > *s && (!*cp || TOR_ISSPACE(*cp)))
  605. --cp;
  606. /* cp now points to the last non-space character in this descriptor. */
  607. while (cp > *s && *cp != '\n')
  608. --cp;
  609. /* cp now points to the first \n before the last non-blank line in this
  610. * descriptor */
  611. if (strcmpstart(cp, "\n-----END SIGNATURE-----\n")) {
  612. log_info(LD_DIR, "Ignoring truncated router descriptor.");
  613. *s = end;
  614. continue;
  615. }
  616. router = router_parse_entry_from_string(*s, end,
  617. saved_location != SAVED_IN_CACHE);
  618. if (!router) {
  619. log_warn(LD_DIR, "Error reading router; skipping");
  620. *s = end;
  621. continue;
  622. }
  623. if (saved_location != SAVED_NOWHERE) {
  624. router->cache_info.saved_location = saved_location;
  625. router->cache_info.saved_offset = *s - start;
  626. }
  627. *s = end;
  628. smartlist_add(dest, router);
  629. }
  630. return 0;
  631. }
  632. /** Helper function: reads a single router entry from *<b>s</b> ...
  633. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  634. * returns NULL.
  635. * DOCDOC cache_copy
  636. */
  637. routerinfo_t *
  638. router_parse_entry_from_string(const char *s, const char *end,
  639. int cache_copy)
  640. {
  641. routerinfo_t *router = NULL;
  642. char signed_digest[128];
  643. char digest[128];
  644. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  645. directory_token_t *tok;
  646. int t;
  647. struct in_addr in;
  648. if (!end) {
  649. end = s + strlen(s);
  650. }
  651. /* point 'end' to a point immediately after the final newline. */
  652. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  653. --end;
  654. if (router_get_router_hash(s, digest) < 0) {
  655. log_warn(LD_DIR, "Couldn't compute router hash.");
  656. return NULL;
  657. }
  658. tokens = smartlist_create();
  659. if (tokenize_string(s,end,tokens,RTR)) {
  660. log_warn(LD_DIR, "Error tokeninzing router descriptor.");
  661. goto err;
  662. }
  663. if (smartlist_len(tokens) < 2) {
  664. log_warn(LD_DIR, "Impossibly short router descriptor.");
  665. goto err;
  666. }
  667. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  668. log_warn(LD_DIR,
  669. "Unrecognized critical keyword %s; skipping descriptor. "
  670. "(It may be from another version of Tor.)",
  671. escaped(tok->args[0]));
  672. goto err;
  673. }
  674. tok = smartlist_get(tokens,0);
  675. if (tok->tp != K_ROUTER) {
  676. log_warn(LD_DIR,"Entry does not start with \"router\"");
  677. goto err;
  678. }
  679. router = tor_malloc_zero(sizeof(routerinfo_t));
  680. router->routerlist_index = -1;
  681. if (cache_copy)
  682. router->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  683. router->cache_info.signed_descriptor_len = end-s;
  684. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  685. if (tok->n_args >= 5) {
  686. router->nickname = tor_strdup(tok->args[0]);
  687. if (!is_legal_nickname(router->nickname)) {
  688. log_warn(LD_DIR,"Router nickname is invalid");
  689. goto err;
  690. }
  691. router->address = tor_strdup(tok->args[1]);
  692. if (!tor_inet_aton(router->address, &in)) {
  693. log_warn(LD_DIR,"Router address is not an IP.");
  694. goto err;
  695. }
  696. router->addr = ntohl(in.s_addr);
  697. router->or_port =
  698. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  699. router->dir_port =
  700. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  701. } else {
  702. log_warn(LD_DIR,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
  703. goto err;
  704. }
  705. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  706. if (!tok) {
  707. log_warn(LD_DIR,"No bandwidth declared; failing.");
  708. goto err;
  709. } else {
  710. if (tok->n_args < 3) {
  711. log_warn(LD_DIR,
  712. "Not enough arguments to \"bandwidth\" in server descriptor.");
  713. goto err;
  714. }
  715. router->bandwidthrate =
  716. tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  717. router->bandwidthburst =
  718. tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  719. router->bandwidthcapacity =
  720. tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  721. }
  722. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  723. if (tok->n_args != 1) {
  724. log_warn(LD_DIR, "Unrecognized number of args on K_UPTIME; skipping.");
  725. } else {
  726. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  727. }
  728. }
  729. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  730. if (tok->n_args < 1) {
  731. log_warn(LD_DIR, "Too few args on 'hibernating' keyword. Skipping.");
  732. } else {
  733. router->is_hibernating
  734. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  735. }
  736. }
  737. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  738. log_warn(LD_DIR, "Missing published time on router descriptor"); goto err;
  739. }
  740. tor_assert(tok->n_args == 1);
  741. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  742. goto err;
  743. if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
  744. log_warn(LD_DIR, "Missing onion key"); goto err;
  745. }
  746. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  747. log_warn(LD_DIR, "Wrong size on onion key: %d bits!",
  748. (int)crypto_pk_keysize(tok->key)*8);
  749. goto err;
  750. }
  751. router->onion_pkey = tok->key;
  752. tok->key = NULL; /* Prevent free */
  753. if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
  754. log_warn(LD_DIR, "Missing identity key"); goto err;
  755. }
  756. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  757. log_warn(LD_DIR, "Wrong size on identity key: %d bits!",
  758. (int)crypto_pk_keysize(tok->key)*8);
  759. goto err;
  760. }
  761. router->identity_pkey = tok->key;
  762. tok->key = NULL; /* Prevent free */
  763. if (crypto_pk_get_digest(router->identity_pkey,
  764. router->cache_info.identity_digest)) {
  765. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  766. }
  767. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  768. /* If there's a fingerprint line, it must match the identity digest. */
  769. char d[DIGEST_LEN];
  770. if (tok->n_args < 1) {
  771. log_warn(LD_DIR, "Too few arguments to router fingerprint");
  772. goto err;
  773. }
  774. tor_strstrip(tok->args[0], " ");
  775. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  776. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  777. escaped(tok->args[0]));
  778. goto err;
  779. }
  780. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  781. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  782. tok->args[0]);
  783. goto err;
  784. }
  785. }
  786. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  787. router->platform = tor_strdup(tok->args[0]);
  788. }
  789. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  790. router->contact_info = tor_strdup(tok->args[0]);
  791. }
  792. if ((tok = find_first_by_keyword(tokens, K_EVENTDNS))) {
  793. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  794. } else if (router->platform) {
  795. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  796. router->has_old_dnsworkers = 1;
  797. }
  798. exit_policy_tokens = find_all_exitpolicy(tokens);
  799. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  800. if (router_add_exit_policy(router,t)<0) {
  801. log_warn(LD_DIR,"Error in exit policy");
  802. goto err;
  803. });
  804. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  805. int i;
  806. router->declared_family = smartlist_create();
  807. for (i=0;i<tok->n_args;++i) {
  808. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  809. log_warn(LD_DIR, "Illegal nickname %s in family line",
  810. escaped(tok->args[i]));
  811. goto err;
  812. }
  813. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  814. }
  815. }
  816. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
  817. log_warn(LD_DIR, "Missing router signature");
  818. goto err;
  819. }
  820. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  821. log_warn(LD_DIR, "Bad object type or length on router signature");
  822. goto err;
  823. }
  824. if ((t=crypto_pk_public_checksig(router->identity_pkey, signed_digest,
  825. tok->object_body, 128)) != 20) {
  826. log_warn(LD_DIR, "Invalid signature %d",t);
  827. goto err;
  828. }
  829. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  830. log_warn(LD_DIR, "Mismatched signature");
  831. goto err;
  832. }
  833. if (!router->or_port) {
  834. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  835. goto err;
  836. }
  837. if (!router->bandwidthrate) {
  838. log_warn(LD_DIR,"bandwidthrate unreadable or 0. Failing.");
  839. goto err;
  840. }
  841. if (!router->platform) {
  842. router->platform = tor_strdup("<unknown>");
  843. }
  844. goto done;
  845. err:
  846. routerinfo_free(router);
  847. router = NULL;
  848. done:
  849. if (tokens) {
  850. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  851. smartlist_free(tokens);
  852. }
  853. if (exit_policy_tokens) {
  854. smartlist_free(exit_policy_tokens);
  855. }
  856. return router;
  857. }
  858. /** Helper: given a string <b>s</b>, return the start of the next router-status
  859. * object (starting with "r " at the start of a line). If none is found,
  860. * return the start of the next directory signature. If none is found, return
  861. * the end of the string. */
  862. static INLINE const char *
  863. find_start_of_next_routerstatus(const char *s)
  864. {
  865. const char *eos = strstr(s, "\nr ");
  866. if (!eos)
  867. eos = strstr(s, "\ndirectory-signature");
  868. if (eos)
  869. return eos+1;
  870. else
  871. return s + strlen(s);
  872. }
  873. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  874. * empty smartlist at <b>tokens</b>, parse and return the first router status
  875. * object in the string, and advance *<b>s</b> to just after the end of the
  876. * router status. Return NULL and advance *<b>s</b> on error. */
  877. static routerstatus_t *
  878. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens)
  879. {
  880. const char *eos;
  881. routerstatus_t *rs = NULL;
  882. directory_token_t *tok;
  883. char timebuf[ISO_TIME_LEN+1];
  884. struct in_addr in;
  885. tor_assert(tokens);
  886. eos = find_start_of_next_routerstatus(*s);
  887. if (tokenize_string(*s, eos, tokens, RTRSTATUS)) {
  888. log_warn(LD_DIR, "Error tokenizing router status");
  889. goto err;
  890. }
  891. if (smartlist_len(tokens) < 1) {
  892. log_warn(LD_DIR, "Impossibly short router status");
  893. goto err;
  894. }
  895. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  896. log_warn(LD_DIR, "Unrecognized keyword %s in router status; skipping.",
  897. escaped(tok->args[0]));
  898. goto err;
  899. }
  900. if (!(tok = find_first_by_keyword(tokens, K_R))) {
  901. log_warn(LD_DIR, "Missing 'r' keywork in router status; skipping.");
  902. goto err;
  903. }
  904. if (tok->n_args < 8) {
  905. log_warn(LD_DIR,
  906. "Too few arguments to 'r' keywork in router status; skipping.");
  907. }
  908. rs = tor_malloc_zero(sizeof(routerstatus_t));
  909. if (!is_legal_nickname(tok->args[0])) {
  910. log_warn(LD_DIR,
  911. "Invalid nickname %s in router status; skipping.",
  912. escaped(tok->args[0]));
  913. goto err;
  914. }
  915. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  916. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  917. log_warn(LD_DIR, "Error decoding identity digest %s",
  918. escaped(tok->args[1]));
  919. goto err;
  920. }
  921. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  922. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  923. escaped(tok->args[2]));
  924. goto err;
  925. }
  926. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  927. tok->args[3], tok->args[4]) < 0 ||
  928. parse_iso_time(timebuf, &rs->published_on)<0) {
  929. log_warn(LD_DIR, "Error parsing time '%s %s'",
  930. tok->args[3], tok->args[4]);
  931. goto err;
  932. }
  933. if (tor_inet_aton(tok->args[5], &in) == 0) {
  934. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  935. escaped(tok->args[5]));
  936. goto err;
  937. }
  938. rs->addr = ntohl(in.s_addr);
  939. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  940. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  941. if ((tok = find_first_by_keyword(tokens, K_S))) {
  942. int i;
  943. for (i=0; i < tok->n_args; ++i) {
  944. if (!strcmp(tok->args[i], "Exit"))
  945. rs->is_exit = 1;
  946. else if (!strcmp(tok->args[i], "Stable"))
  947. rs->is_stable = 1;
  948. else if (!strcmp(tok->args[i], "Fast"))
  949. rs->is_fast = 1;
  950. else if (!strcmp(tok->args[i], "Running"))
  951. rs->is_running = 1;
  952. else if (!strcmp(tok->args[i], "Named"))
  953. rs->is_named = 1;
  954. else if (!strcmp(tok->args[i], "Valid"))
  955. rs->is_valid = 1;
  956. else if (!strcmp(tok->args[i], "V2Dir"))
  957. rs->is_v2_dir = 1;
  958. else if (!strcmp(tok->args[i], "Guard"))
  959. rs->is_possible_guard = 1;
  960. else if (!strcmp(tok->args[i], "BadExit"))
  961. rs->is_bad_exit = 1;
  962. }
  963. }
  964. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  965. rs->is_named = 0;
  966. goto done;
  967. err:
  968. if (rs)
  969. routerstatus_free(rs);
  970. rs = NULL;
  971. done:
  972. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  973. smartlist_clear(tokens);
  974. *s = eos;
  975. return rs;
  976. }
  977. /** Helper to sort a smartlist of pointers to routerstatus_t */
  978. static int
  979. _compare_routerstatus_entries(const void **_a, const void **_b)
  980. {
  981. const routerstatus_t *a = *_a, *b = *_b;
  982. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  983. }
  984. static void
  985. _free_duplicate_routerstatus_entry(void *e)
  986. {
  987. log_warn(LD_DIR,
  988. "Network-status has two entries for the same router. "
  989. "Dropping one.");
  990. routerstatus_free(e);
  991. }
  992. /** Given a versioned (v2 or later) network-status object in <b>s</b>, try to
  993. * parse it and return the result. Return NULL on failure. Check the
  994. * signature of the network status, but do not (yet) check the signing key for
  995. * authority.
  996. */
  997. networkstatus_t *
  998. networkstatus_parse_from_string(const char *s)
  999. {
  1000. const char *eos;
  1001. smartlist_t *tokens = smartlist_create();
  1002. networkstatus_t *ns = NULL;
  1003. char ns_digest[DIGEST_LEN];
  1004. char tmp_digest[DIGEST_LEN];
  1005. struct in_addr in;
  1006. directory_token_t *tok;
  1007. int i;
  1008. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1009. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1010. goto err;
  1011. }
  1012. eos = find_start_of_next_routerstatus(s);
  1013. if (tokenize_string(s, eos, tokens, NETSTATUS)) {
  1014. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1015. goto err;
  1016. }
  1017. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  1018. log_warn(LD_DIR, "Unrecognized keyword %s; can't parse network-status",
  1019. escaped(tok->args[0]));
  1020. goto err;
  1021. }
  1022. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1023. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1024. if (!(tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION))) {
  1025. log_warn(LD_DIR, "Couldn't find network-status-version keyword");
  1026. goto err;
  1027. }
  1028. if (!(tok = find_first_by_keyword(tokens, K_DIR_SOURCE))) {
  1029. log_warn(LD_DIR, "Couldn't find dir-source keyword");
  1030. goto err;
  1031. }
  1032. if (tok->n_args < 3) {
  1033. log_warn(LD_DIR, "Too few arguments to dir-source keyword");
  1034. goto err;
  1035. }
  1036. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1037. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1038. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1039. escaped(tok->args[1]));
  1040. goto err;
  1041. }
  1042. ns->source_addr = ntohl(in.s_addr);
  1043. ns->source_dirport =
  1044. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1045. if (ns->source_dirport == 0) {
  1046. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1047. goto err;
  1048. }
  1049. if (!(tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  1050. log_warn(LD_DIR, "Couldn't find fingerprint keyword");
  1051. goto err;
  1052. }
  1053. if (tok->n_args < 1) {
  1054. log_warn(LD_DIR, "Too few arguments to networkstatus fingerprint");
  1055. goto err;
  1056. }
  1057. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1058. strlen(tok->args[0]))) {
  1059. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1060. escaped(tok->args[0]));
  1061. goto err;
  1062. }
  1063. if ((tok = find_first_by_keyword(tokens, K_CONTACT)) && tok->n_args) {
  1064. ns->contact = tok->args[0];
  1065. tok->args[0] = NULL;
  1066. }
  1067. if (!(tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY)) || !tok->key) {
  1068. log_warn(LD_DIR, "Missing dir-signing-key");
  1069. goto err;
  1070. }
  1071. ns->signing_key = tok->key;
  1072. tok->key = NULL;
  1073. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1074. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1075. goto err;
  1076. }
  1077. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1078. log_warn(LD_DIR,
  1079. "network-status fingerprint did not match dir-signing-key");
  1080. goto err;
  1081. }
  1082. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1083. for (i=0; i < tok->n_args; ++i) {
  1084. if (!strcmp(tok->args[i], "Names"))
  1085. ns->binds_names = 1;
  1086. if (!strcmp(tok->args[i], "Versions"))
  1087. ns->recommends_versions = 1;
  1088. }
  1089. }
  1090. if (ns->recommends_versions) {
  1091. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS)) ||
  1092. tok->n_args<1) {
  1093. log_warn(LD_DIR, "Missing client-versions");
  1094. }
  1095. ns->client_versions = tok->args[0];
  1096. tok->args[0] = NULL;
  1097. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1098. tok->n_args<1) {
  1099. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1100. goto err;
  1101. }
  1102. ns->server_versions = tok->args[0];
  1103. tok->args[0] = NULL;
  1104. }
  1105. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  1106. log_warn(LD_DIR, "Missing published time on network-status.");
  1107. goto err;
  1108. }
  1109. tor_assert(tok->n_args == 1);
  1110. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1111. goto err;
  1112. }
  1113. ns->entries = smartlist_create();
  1114. s = eos;
  1115. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1116. smartlist_clear(tokens);
  1117. while (!strcmpstart(s, "r ")) {
  1118. routerstatus_t *rs;
  1119. if ((rs = routerstatus_parse_entry_from_string(&s, tokens)))
  1120. smartlist_add(ns->entries, rs);
  1121. }
  1122. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1123. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1124. _free_duplicate_routerstatus_entry);
  1125. if (tokenize_string(s, NULL, tokens, NETSTATUS)) {
  1126. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1127. goto err;
  1128. }
  1129. if (smartlist_len(tokens) < 1) {
  1130. log_warn(LD_DIR, "Too few items in network-status footer.");
  1131. goto err;
  1132. }
  1133. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1134. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1135. log_warn(LD_DIR,
  1136. "Expected network-status footer to end with a signature.");
  1137. goto err;
  1138. }
  1139. if (check_directory_signature(ns_digest, tok, NULL, ns->signing_key, 0))
  1140. goto err;
  1141. goto done;
  1142. err:
  1143. if (ns)
  1144. networkstatus_free(ns);
  1145. ns = NULL;
  1146. done:
  1147. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1148. smartlist_free(tokens);
  1149. return ns;
  1150. }
  1151. /** Parse the addr policy in the string <b>s</b> and return it. If
  1152. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1153. * ADDR_POLICY_REJECT) for items that specify no action.
  1154. */
  1155. addr_policy_t *
  1156. router_parse_addr_policy_from_string(const char *s, int assume_action)
  1157. {
  1158. directory_token_t *tok = NULL;
  1159. const char *cp;
  1160. char *tmp;
  1161. addr_policy_t *r;
  1162. size_t len, idx;
  1163. /* *s might not end with \n, so we need to extend it with one. */
  1164. len = strlen(s);
  1165. cp = tmp = tor_malloc(len+2);
  1166. for (idx = 0; idx < len; ++idx) {
  1167. tmp[idx] = TOR_TOLOWER(s[idx]);
  1168. }
  1169. tmp[len]='\n';
  1170. tmp[len+1]='\0';
  1171. while (TOR_ISSPACE(*cp))
  1172. ++cp;
  1173. if ((*cp == '*' || TOR_ISDIGIT(*cp)) && assume_action >= 0) {
  1174. char *new_str = tor_malloc(len+10);
  1175. tor_snprintf(new_str, len+10, "%s %s\n",
  1176. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", cp);
  1177. tor_free(tmp);
  1178. cp = tmp = new_str;
  1179. }
  1180. tok = get_next_token(&cp, RTR);
  1181. if (tok->tp == _ERR) {
  1182. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1183. goto err;
  1184. }
  1185. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1186. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1187. goto err;
  1188. }
  1189. /* Now that we've gotten an addr policy, add it to the router. */
  1190. r = router_parse_addr_policy(tok);
  1191. goto done;
  1192. err:
  1193. r = NULL;
  1194. done:
  1195. tor_free(tmp);
  1196. token_free(tok);
  1197. return r;
  1198. }
  1199. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1200. * <b>router</b>. Return 0 on success, -1 on failure. */
  1201. static int
  1202. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1203. {
  1204. addr_policy_t *newe, **tmpe;
  1205. newe = router_parse_addr_policy(tok);
  1206. if (!newe)
  1207. return -1;
  1208. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  1209. ;
  1210. *tmpe = newe;
  1211. return 0;
  1212. }
  1213. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  1214. * a new exit_policy_t corresponding to the token. */
  1215. static addr_policy_t *
  1216. router_parse_addr_policy(directory_token_t *tok)
  1217. {
  1218. addr_policy_t *newe;
  1219. // struct in_addr in;
  1220. char *arg;
  1221. // char *address;
  1222. // char buf[INET_NTOA_BUF_LEN];
  1223. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1224. if (tok->n_args != 1)
  1225. return NULL;
  1226. arg = tok->args[0];
  1227. if (!strcmpstart(arg,"private"))
  1228. return router_parse_private_addr_policy_private(tok);
  1229. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1230. newe->string = tor_malloc(8+strlen(arg));
  1231. /* XXX eventually, use the code from router.c:727 to generate this */
  1232. tor_snprintf(newe->string, 8+strlen(arg), "%s %s",
  1233. (tok->tp == K_REJECT) ? "reject" : "accept", arg);
  1234. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1235. : ADDR_POLICY_ACCEPT;
  1236. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1237. &newe->prt_min, &newe->prt_max))
  1238. goto policy_read_failed;
  1239. // in.s_addr = htonl(newe->addr);
  1240. // tor_inet_ntoa(&in, buf, sizeof(buf));
  1241. // address = tor_strdup(buf);
  1242. // in.s_addr = htonl(newe->msk);
  1243. // log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
  1244. // newe->policy_type == ADDR_POLICY_REJECT ? "reject" : "accept",
  1245. // address, inet_ntoa(in), newe->prt_min, newe->prt_max);
  1246. // tor_free(address);
  1247. return newe;
  1248. policy_read_failed:
  1249. tor_assert(newe->string);
  1250. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(newe->string));
  1251. tor_free(newe->string);
  1252. tor_free(newe);
  1253. return NULL;
  1254. }
  1255. /** Parse an exit policy line of the format "accept/reject private:...".
  1256. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1257. * router descriptors until earlier versions are obsolete.
  1258. */
  1259. static addr_policy_t *
  1260. router_parse_private_addr_policy_private(directory_token_t *tok)
  1261. {
  1262. /* XXXX duplicated from config.c */
  1263. static const char *private_nets[] = {
  1264. "0.0.0.0/8", "169.254.0.0/16",
  1265. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL };
  1266. char *arg;
  1267. addr_policy_t *result, **nextp;
  1268. int net;
  1269. uint16_t port_min, port_max;
  1270. arg = tok->args[0];
  1271. if (strcmpstart(arg, "private"))
  1272. return NULL;
  1273. arg += strlen("private");
  1274. arg = (char*) eat_whitespace(arg);
  1275. if (!arg || *arg != ':')
  1276. return NULL;
  1277. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1278. return NULL;
  1279. nextp = &result;
  1280. for (net = 0; private_nets[net]; ++net) {
  1281. size_t len;
  1282. *nextp = tor_malloc_zero(sizeof(addr_policy_t));
  1283. (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1284. : ADDR_POLICY_ACCEPT;
  1285. len = strlen(arg)+strlen(private_nets[net])+16;
  1286. (*nextp)->string = tor_malloc(len+1);
  1287. tor_snprintf((*nextp)->string, len, "%s %s%s",
  1288. tok->tp == K_REJECT ? "reject" : "accept",
  1289. private_nets[net], arg);
  1290. if (parse_addr_and_port_range((*nextp)->string + 7,
  1291. &(*nextp)->addr, &(*nextp)->msk,
  1292. &(*nextp)->prt_min, &(*nextp)->prt_max)) {
  1293. log_warn(LD_BUG, "Couldn't parse an address range we generated!");
  1294. return NULL;
  1295. }
  1296. nextp = &(*nextp)->next;
  1297. }
  1298. return result;
  1299. }
  1300. /** Log and exit if <b>t</b> is malformed */
  1301. void
  1302. assert_addr_policy_ok(addr_policy_t *t)
  1303. {
  1304. addr_policy_t *t2;
  1305. while (t) {
  1306. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  1307. t->policy_type == ADDR_POLICY_ACCEPT);
  1308. tor_assert(t->prt_min <= t->prt_max);
  1309. t2 = router_parse_addr_policy_from_string(t->string, -1);
  1310. tor_assert(t2);
  1311. tor_assert(t2->policy_type == t->policy_type);
  1312. tor_assert(t2->addr == t->addr);
  1313. tor_assert(t2->msk == t->msk);
  1314. tor_assert(t2->prt_min == t->prt_min);
  1315. tor_assert(t2->prt_max == t->prt_max);
  1316. tor_assert(!strcmp(t2->string, t->string));
  1317. tor_assert(t2->next == NULL);
  1318. addr_policy_free(t2);
  1319. t = t->next;
  1320. }
  1321. }
  1322. /*
  1323. * Low-level tokenizer for router descriptors and directories.
  1324. */
  1325. /** Free all resources allocated for <b>tok</b> */
  1326. static void
  1327. token_free(directory_token_t *tok)
  1328. {
  1329. int i;
  1330. tor_assert(tok);
  1331. if (tok->args) {
  1332. for (i = 0; i < tok->n_args; ++i) {
  1333. tor_free(tok->args[i]);
  1334. }
  1335. tor_free(tok->args);
  1336. }
  1337. tor_free(tok->object_type);
  1338. tor_free(tok->object_body);
  1339. if (tok->key)
  1340. crypto_free_pk_env(tok->key);
  1341. tor_free(tok);
  1342. }
  1343. /** Helper function: read the next token from *s, advance *s to the end
  1344. * of the token, and return the parsed token. If 'where' is DIR
  1345. * or RTR, reject all tokens of the wrong type.
  1346. */
  1347. static directory_token_t *
  1348. get_next_token(const char **s, where_syntax where)
  1349. {
  1350. const char *next, *obstart;
  1351. int i, done, allocated, is_opt;
  1352. directory_token_t *tok;
  1353. arg_syntax a_syn;
  1354. obj_syntax o_syn = NO_OBJ;
  1355. #define RET_ERR(msg) \
  1356. do { if (tok) token_free(tok); \
  1357. tok = tor_malloc_zero(sizeof(directory_token_t));\
  1358. tok->tp = _ERR; \
  1359. tok->error = msg; \
  1360. goto done_tokenizing; } while (0)
  1361. tok = tor_malloc_zero(sizeof(directory_token_t));
  1362. tok->tp = _ERR;
  1363. *s = eat_whitespace(*s);
  1364. if (!**s) {
  1365. tok->tp = _EOF;
  1366. return tok;
  1367. }
  1368. next = find_whitespace(*s);
  1369. if (!next) {
  1370. tok->error = "Unexpected EOF"; return tok;
  1371. }
  1372. /* It's a keyword... but which one? */
  1373. is_opt = !strncmp("opt", *s, next-*s);
  1374. if (is_opt) {
  1375. *s = eat_whitespace(next);
  1376. next = NULL;
  1377. if (**s)
  1378. next = find_whitespace(*s);
  1379. if (!**s || !next) {
  1380. RET_ERR("opt without keyword");
  1381. }
  1382. }
  1383. for (i = 0; token_table[i].t ; ++i) {
  1384. if (!strncmp(token_table[i].t, *s, next-*s)) {
  1385. /* We've found the keyword. */
  1386. tok->tp = token_table[i].v;
  1387. a_syn = token_table[i].s;
  1388. o_syn = token_table[i].os;
  1389. if (!(token_table[i].ws & where)) {
  1390. if (where == DIR) {
  1391. RET_ERR("Found an out-of-place token in a directory section");
  1392. } else if (where == RTR) {
  1393. RET_ERR("Found an out-of-place token in a router descriptor");
  1394. } else if (where == NETSTATUS) {
  1395. RET_ERR("Found an out-of-place token in a network-status header");
  1396. } else {
  1397. RET_ERR("Found an out-of-place token in a router status body");
  1398. }
  1399. }
  1400. if (a_syn == ARGS) {
  1401. /* This keyword takes multiple arguments. */
  1402. i = 0;
  1403. done = (*next == '\n');
  1404. allocated = 32;
  1405. tok->args = tor_malloc(sizeof(char*)*32);
  1406. *s = eat_whitespace_no_nl(next);
  1407. while (**s != '\n' && !done) {
  1408. next = find_whitespace(*s);
  1409. if (*next == '\n')
  1410. done = 1;
  1411. if (i == allocated) {
  1412. allocated *= 2;
  1413. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1414. }
  1415. tok->args[i++] = tor_strndup(*s,next-*s);
  1416. *s = eat_whitespace_no_nl(next+1);
  1417. }
  1418. tok->n_args = i;
  1419. } else if (a_syn == CONCAT_ARGS) {
  1420. /* The keyword takes the line as a single argument */
  1421. *s = eat_whitespace_no_nl(next);
  1422. next = strchr(*s, '\n');
  1423. if (!next)
  1424. RET_ERR("Unexpected EOF");
  1425. tok->args = tor_malloc(sizeof(char*));
  1426. tok->args[0] = tor_strndup(*s,next-*s);
  1427. tok->n_args = 1;
  1428. *s = eat_whitespace_no_nl(next+1);
  1429. } else {
  1430. /* The keyword takes no arguments. */
  1431. tor_assert(a_syn == NO_ARGS);
  1432. *s = eat_whitespace_no_nl(next);
  1433. if (**s != '\n') {
  1434. RET_ERR("Unexpected arguments");
  1435. }
  1436. tok->n_args = 0;
  1437. *s = eat_whitespace_no_nl(*s+1);
  1438. }
  1439. break;
  1440. }
  1441. }
  1442. if (tok->tp == _ERR) {
  1443. if (is_opt) {
  1444. tok->tp = K_OPT;
  1445. *s = eat_whitespace_no_nl(next);
  1446. next = strchr(*s,'\n');
  1447. if (!next)
  1448. RET_ERR("Unexpected EOF");
  1449. tok->args = tor_malloc(sizeof(char*));
  1450. tok->args[0] = tor_strndup(*s,next-*s);
  1451. tok->n_args = 1;
  1452. *s = eat_whitespace_no_nl(next+1);
  1453. o_syn = OBJ_OK;
  1454. } else {
  1455. tok->tp = _UNRECOGNIZED;
  1456. next = strchr(*s, '\n');
  1457. if (!next) {
  1458. RET_ERR("Unexpected EOF");
  1459. }
  1460. tok->args = tor_malloc(sizeof(char*));
  1461. tok->args[0] = tor_strndup(*s,next-*s);
  1462. tok->n_args = 1;
  1463. *s = next+1;
  1464. o_syn = OBJ_OK;
  1465. }
  1466. }
  1467. *s = eat_whitespace(*s);
  1468. if (strcmpstart(*s, "-----BEGIN ")) {
  1469. goto done_tokenizing;
  1470. }
  1471. obstart = *s;
  1472. *s += 11; /* length of "-----BEGIN ". */
  1473. next = strchr(*s, '\n');
  1474. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  1475. RET_ERR("Malformed object: bad begin line");
  1476. }
  1477. tok->object_type = tor_strndup(*s, next-*s-5);
  1478. *s = next+1;
  1479. next = strstr(*s, "-----END ");
  1480. if (!next) {
  1481. RET_ERR("Malformed object: missing end line");
  1482. }
  1483. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1484. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  1485. RET_ERR("Malformed object: mismatched end line");
  1486. next = strchr(next,'\n')+1;
  1487. tok->key = crypto_new_pk_env();
  1488. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1489. RET_ERR("Couldn't parse public key.");
  1490. *s = next;
  1491. } else {
  1492. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1493. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1494. if (i<0) {
  1495. RET_ERR("Malformed object: bad base64-encoded data");
  1496. }
  1497. tok->object_size = i;
  1498. *s = next + 9; /* length of "-----END ". */
  1499. i = strlen(tok->object_type);
  1500. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  1501. RET_ERR("Malformed object: mismatched end tag");
  1502. }
  1503. *s += i+6;
  1504. }
  1505. switch (o_syn)
  1506. {
  1507. case NO_OBJ:
  1508. if (tok->object_body)
  1509. RET_ERR("Unexpected object for keyword");
  1510. if (tok->key)
  1511. RET_ERR("Unexpected public key for keyword");
  1512. break;
  1513. case NEED_OBJ:
  1514. if (!tok->object_body)
  1515. RET_ERR("Missing object for keyword");
  1516. break;
  1517. case NEED_KEY:
  1518. if (!tok->key)
  1519. RET_ERR("Missing public key for keyword");
  1520. break;
  1521. case OBJ_OK:
  1522. break;
  1523. }
  1524. done_tokenizing:
  1525. return tok;
  1526. #undef RET_ERR
  1527. }
  1528. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1529. * them to <b>out</b>. If <b>is_dir</b> is true, reject all non-directory
  1530. * tokens; else reject all non-routerdescriptor tokens.
  1531. */
  1532. static int
  1533. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1534. where_syntax where)
  1535. {
  1536. const char **s;
  1537. directory_token_t *tok = NULL;
  1538. s = &start;
  1539. if (!end)
  1540. end = start+strlen(start);
  1541. while (*s < end && (!tok || tok->tp != _EOF)) {
  1542. tok = get_next_token(s, where);
  1543. if (tok->tp == _ERR) {
  1544. log_warn(LD_DIR, "parse error: %s", tok->error);
  1545. return -1;
  1546. }
  1547. smartlist_add(out, tok);
  1548. *s = eat_whitespace(*s);
  1549. }
  1550. return 0;
  1551. }
  1552. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1553. * NULL if no such keyword is found.
  1554. */
  1555. static directory_token_t *
  1556. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1557. {
  1558. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1559. return NULL;
  1560. }
  1561. /** Return a newly allocated smartlist of all accept or reject tokens in
  1562. * <b>s</b>.
  1563. */
  1564. static smartlist_t *
  1565. find_all_exitpolicy(smartlist_t *s)
  1566. {
  1567. smartlist_t *out = smartlist_create();
  1568. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1569. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1570. smartlist_add(out,t));
  1571. return out;
  1572. }
  1573. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  1574. * occurrence of <b>start_str</b> through the first newline after the first
  1575. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1576. * <b>digest</b>; return 0 on success.
  1577. *
  1578. * If no such substring exists, return -1.
  1579. */
  1580. static int
  1581. router_get_hash_impl(const char *s, char *digest,
  1582. const char *start_str,
  1583. const char *end_str)
  1584. {
  1585. char *start, *end;
  1586. start = strstr(s, start_str);
  1587. if (!start) {
  1588. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  1589. return -1;
  1590. }
  1591. if (start != s && *(start-1) != '\n') {
  1592. log_warn(LD_DIR,
  1593. "first occurrence of \"%s\" is not at the start of a line",
  1594. start_str);
  1595. return -1;
  1596. }
  1597. end = strstr(start+strlen(start_str), end_str);
  1598. if (!end) {
  1599. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  1600. return -1;
  1601. }
  1602. end = strchr(end+strlen(end_str), '\n');
  1603. if (!end) {
  1604. log_warn(LD_DIR,"couldn't find EOL");
  1605. return -1;
  1606. }
  1607. ++end;
  1608. if (crypto_digest(digest, start, end-start)) {
  1609. log_warn(LD_BUG,"couldn't compute digest");
  1610. return -1;
  1611. }
  1612. return 0;
  1613. }
  1614. /** Parse the Tor version of the platform string <b>platform</b>,
  1615. * and compare it to the version in <b>cutoff</b>. Return 1 if
  1616. * the router is at least as new as the cutoff, else return 0.
  1617. */
  1618. int
  1619. tor_version_as_new_as(const char *platform, const char *cutoff)
  1620. {
  1621. tor_version_t cutoff_version, router_version;
  1622. char *s, *start;
  1623. char tmp[128];
  1624. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  1625. log_warn(LD_DIR,"Bug: cutoff version '%s' unparseable.",cutoff);
  1626. return 0;
  1627. }
  1628. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  1629. return 1;
  1630. start = (char *)eat_whitespace(platform+3);
  1631. if (!*start) return 0;
  1632. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  1633. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  1634. return 0;
  1635. strlcpy(tmp, start, s-start+1);
  1636. if (tor_version_parse(tmp, &router_version)<0) {
  1637. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  1638. return 1; /* be safe and say yes */
  1639. }
  1640. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  1641. }
  1642. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  1643. * Return 0 on success, -1 on failure. */
  1644. int
  1645. tor_version_parse(const char *s, tor_version_t *out)
  1646. {
  1647. char *eos=NULL, *cp=NULL;
  1648. /* Format is:
  1649. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  1650. */
  1651. tor_assert(s);
  1652. tor_assert(out);
  1653. memset(out, 0, sizeof(tor_version_t));
  1654. if (!strcasecmpstart(s, "Tor "))
  1655. s += 4;
  1656. /* Get major. */
  1657. out->major = strtol(s,&eos,10);
  1658. if (!eos || eos==s || *eos != '.') return -1;
  1659. cp = eos+1;
  1660. /* Get minor */
  1661. out->minor = strtol(cp,&eos,10);
  1662. if (!eos || eos==cp || *eos != '.') return -1;
  1663. cp = eos+1;
  1664. /* Get micro */
  1665. out->micro = strtol(cp,&eos,10);
  1666. if (!eos || eos==cp) return -1;
  1667. if (!*eos) {
  1668. out->status = VER_RELEASE;
  1669. out->patchlevel = 0;
  1670. return 0;
  1671. }
  1672. cp = eos;
  1673. /* Get status */
  1674. if (*cp == '.') {
  1675. out->status = VER_RELEASE;
  1676. ++cp;
  1677. } else if (0==strncmp(cp, "pre", 3)) {
  1678. out->status = VER_PRE;
  1679. cp += 3;
  1680. } else if (0==strncmp(cp, "rc", 2)) {
  1681. out->status = VER_RC;
  1682. cp += 2;
  1683. } else {
  1684. return -1;
  1685. }
  1686. /* Get patchlevel */
  1687. out->patchlevel = strtol(cp,&eos,10);
  1688. if (!eos || eos==cp) return -1;
  1689. cp = eos;
  1690. /* Get status tag. */
  1691. if (*cp == '-' || *cp == '.')
  1692. ++cp;
  1693. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  1694. return 0;
  1695. }
  1696. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  1697. * b. */
  1698. int
  1699. tor_version_compare(tor_version_t *a, tor_version_t *b)
  1700. {
  1701. int i;
  1702. tor_assert(a);
  1703. tor_assert(b);
  1704. if ((i = a->major - b->major))
  1705. return i;
  1706. else if ((i = a->minor - b->minor))
  1707. return i;
  1708. else if ((i = a->micro - b->micro))
  1709. return i;
  1710. else if ((i = a->status - b->status))
  1711. return i;
  1712. else if ((i = a->patchlevel - b->patchlevel))
  1713. return i;
  1714. return strcmp(a->status_tag, b->status_tag);
  1715. }
  1716. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  1717. */
  1718. static int
  1719. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  1720. {
  1721. tor_assert(a);
  1722. tor_assert(b);
  1723. return ((a->major == b->major) &&
  1724. (a->minor == b->minor) &&
  1725. (a->micro == b->micro));
  1726. }
  1727. /** Helper: Given pointers to two strings describing tor versions, return -1
  1728. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  1729. * Used to sort a list of versions. */
  1730. static int
  1731. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  1732. {
  1733. const char *a = *_a, *b = *_b;
  1734. int ca, cb;
  1735. tor_version_t va, vb;
  1736. ca = tor_version_parse(a, &va);
  1737. cb = tor_version_parse(b, &vb);
  1738. /* If they both parse, compare them. */
  1739. if (!ca && !cb)
  1740. return tor_version_compare(&va,&vb);
  1741. /* If one parses, it comes first. */
  1742. if (!ca && cb)
  1743. return -1;
  1744. if (ca && !cb)
  1745. return 1;
  1746. /* If neither parses, compare strings. Also, the directory server admin
  1747. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  1748. return strcmp(a,b);
  1749. }
  1750. /** Sort a list of string-representations of versions in ascending order. */
  1751. void
  1752. sort_version_list(smartlist_t *versions, int remove_duplicates)
  1753. {
  1754. smartlist_sort(versions, _compare_tor_version_str_ptr);
  1755. if (remove_duplicates)
  1756. smartlist_uniq(versions, _compare_tor_version_str_ptr, NULL);
  1757. }