routerparse.c 59 KB

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