routerparse.c 56 KB

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