routerparse.c 56 KB

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