routerparse.c 55 KB

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