routerparse.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947
  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 {
  493. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  494. return NULL;
  495. }
  496. token_free(tok);
  497. return key;
  498. }
  499. /** Return true iff <b>key</b> is allowed to sign directories.
  500. */
  501. static int
  502. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  503. {
  504. char digest[DIGEST_LEN];
  505. if (!key) return 0;
  506. if (crypto_pk_get_digest(key, digest) < 0) {
  507. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  508. return 0;
  509. }
  510. if (!router_digest_is_trusted_dir(digest)) {
  511. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  512. return 0;
  513. }
  514. return 1;
  515. }
  516. /** Check whether the K_DIRECTORY_SIGNATURE token in <b>tok</b> has a
  517. * good signature for <b>digest</b>.
  518. *
  519. * If <b>declared_key</b> is set, the directory has declared what key
  520. * was used to sign it, so we will use that key only if it is an
  521. * authoritative directory signing key or if check_authority is 0.
  522. *
  523. * Otherwise, if pkey is provided, try to use it.
  524. *
  525. * (New callers should always use <b>declared_key</b> when possible;
  526. * <b>pkey</b> is only for debugging.)
  527. */
  528. static int
  529. check_directory_signature(const char *digest,
  530. directory_token_t *tok,
  531. crypto_pk_env_t *pkey,
  532. crypto_pk_env_t *declared_key,
  533. int check_authority)
  534. {
  535. char signed_digest[PK_BYTES];
  536. crypto_pk_env_t *_pkey = NULL;
  537. if (tok->n_args != 1) {
  538. log_warn(LD_DIR, "Too many or too few arguments to directory-signature");
  539. return -1;
  540. }
  541. if (declared_key) {
  542. if (!check_authority || dir_signing_key_is_trusted(declared_key))
  543. _pkey = declared_key;
  544. }
  545. if (!_pkey && pkey) {
  546. /* pkey provided for debugging purposes */
  547. _pkey = pkey;
  548. }
  549. if (!_pkey) {
  550. log_warn(LD_DIR,
  551. "Obsolete directory format (dir signing key not present) or "
  552. "signing key not trusted--rejecting.");
  553. return -1;
  554. }
  555. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  556. log_warn(LD_DIR, "Bad object type or length on directory signature");
  557. return -1;
  558. }
  559. tor_assert(_pkey);
  560. if (crypto_pk_public_checksig(_pkey, signed_digest, tok->object_body, 128)
  561. != 20) {
  562. log_warn(LD_DIR, "Error reading directory: invalid signature.");
  563. return -1;
  564. }
  565. log_debug(LD_DIR,"Signed directory hash starts %s",
  566. hex_str(signed_digest,4));
  567. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  568. log_warn(LD_DIR, "Error reading directory: signature does not match.");
  569. return -1;
  570. }
  571. return 0;
  572. }
  573. /** Given a string *<b>s</b> containing a concatenated sequence of router
  574. * descriptors, parses them and stores the result in <b>dest</b>. All routers
  575. * are marked running and valid. Advances *s to a point immediately
  576. * following the last router entry. Ignore any trailing router entries that
  577. * are not complete. Returns 0 on success and -1 on failure.
  578. */
  579. int
  580. router_parse_list_from_string(const char **s, smartlist_t *dest,
  581. int from_cache)
  582. {
  583. routerinfo_t *router;
  584. const char *end, *cp, *start;
  585. tor_assert(s);
  586. tor_assert(*s);
  587. tor_assert(dest);
  588. start = *s;
  589. while (1) {
  590. *s = eat_whitespace(*s);
  591. /* Don't start parsing the rest of *s unless it contains a router. */
  592. if (strcmpstart(*s, "router ")!=0)
  593. break;
  594. if ((end = strstr(*s+1, "\nrouter "))) {
  595. cp = end;
  596. end++;
  597. } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
  598. cp = end;
  599. end++;
  600. } else {
  601. cp = end = *s+strlen(*s);
  602. }
  603. while (cp > *s && (!*cp || TOR_ISSPACE(*cp)))
  604. --cp;
  605. /* cp now points to the last non-space character in this descriptor. */
  606. while (cp > *s && *cp != '\n')
  607. --cp;
  608. /* cp now points to the first \n before the last non-blank line in this
  609. * descriptor */
  610. if (strcmpstart(cp, "\n-----END SIGNATURE-----\n")) {
  611. log_info(LD_DIR, "Ignoring truncated router descriptor.");
  612. *s = end;
  613. continue;
  614. }
  615. router = router_parse_entry_from_string(*s, end);
  616. *s = end;
  617. if (!router) {
  618. log_warn(LD_DIR, "Error reading router; skipping");
  619. continue;
  620. }
  621. if (from_cache) {
  622. router->cache_info.saved_location = SAVED_IN_CACHE;
  623. router->cache_info.saved_offset = *s - start;
  624. }
  625. smartlist_add(dest, router);
  626. }
  627. return 0;
  628. }
  629. /** Helper function: reads a single router entry from *<b>s</b> ...
  630. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  631. * returns NULL.
  632. */
  633. routerinfo_t *
  634. router_parse_entry_from_string(const char *s, const char *end)
  635. {
  636. routerinfo_t *router = NULL;
  637. char signed_digest[128];
  638. char digest[128];
  639. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  640. directory_token_t *tok;
  641. int t;
  642. struct in_addr in;
  643. if (!end) {
  644. end = s + strlen(s);
  645. }
  646. /* point 'end' to a point immediately after the final newline. */
  647. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  648. --end;
  649. if (router_get_router_hash(s, digest) < 0) {
  650. log_warn(LD_DIR, "Couldn't compute router hash.");
  651. return NULL;
  652. }
  653. tokens = smartlist_create();
  654. if (tokenize_string(s,end,tokens,RTR)) {
  655. log_warn(LD_DIR, "Error tokeninzing router descriptor.");
  656. goto err;
  657. }
  658. if (smartlist_len(tokens) < 2) {
  659. log_warn(LD_DIR, "Impossibly short router descriptor.");
  660. goto err;
  661. }
  662. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  663. log_warn(LD_DIR,
  664. "Unrecognized critical keyword %s; skipping descriptor. "
  665. "(It may be from another version of Tor.)",
  666. escaped(tok->args[0]));
  667. goto err;
  668. }
  669. tok = smartlist_get(tokens,0);
  670. if (tok->tp != K_ROUTER) {
  671. log_warn(LD_DIR,"Entry does not start with \"router\"");
  672. goto err;
  673. }
  674. router = tor_malloc_zero(sizeof(routerinfo_t));
  675. router->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  676. router->cache_info.signed_descriptor_len = end-s;
  677. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  678. if (tok->n_args >= 5) {
  679. router->nickname = tor_strdup(tok->args[0]);
  680. if (!is_legal_nickname(router->nickname)) {
  681. log_warn(LD_DIR,"Router nickname is invalid");
  682. goto err;
  683. }
  684. router->address = tor_strdup(tok->args[1]);
  685. if (!tor_inet_aton(router->address, &in)) {
  686. log_warn(LD_DIR,"Router address is not an IP.");
  687. goto err;
  688. }
  689. router->addr = ntohl(in.s_addr);
  690. router->or_port =
  691. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  692. router->dir_port =
  693. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  694. } else {
  695. log_warn(LD_DIR,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
  696. goto err;
  697. }
  698. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  699. if (!tok) {
  700. log_warn(LD_DIR,"No bandwidth declared; failing.");
  701. goto err;
  702. } else {
  703. if (tok->n_args < 3) {
  704. log_warn(LD_DIR,
  705. "Not enough arguments to \"bandwidth\" in server descriptor.");
  706. goto err;
  707. }
  708. router->bandwidthrate =
  709. tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  710. router->bandwidthburst =
  711. tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  712. router->bandwidthcapacity =
  713. tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  714. }
  715. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  716. if (tok->n_args != 1) {
  717. log_warn(LD_DIR, "Unrecognized number of args on K_UPTIME; skipping.");
  718. } else {
  719. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  720. }
  721. }
  722. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  723. if (tok->n_args < 1) {
  724. log_warn(LD_DIR, "Too few args on 'hibernating' keyword. Skipping.");
  725. } else {
  726. router->is_hibernating
  727. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  728. }
  729. }
  730. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  731. log_warn(LD_DIR, "Missing published time"); goto err;
  732. }
  733. tor_assert(tok->n_args == 1);
  734. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  735. goto err;
  736. if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
  737. log_warn(LD_DIR, "Missing onion key"); goto err;
  738. }
  739. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  740. log_warn(LD_DIR, "Wrong size on onion key: %d bits!",
  741. (int)crypto_pk_keysize(tok->key)*8);
  742. goto err;
  743. }
  744. router->onion_pkey = tok->key;
  745. tok->key = NULL; /* Prevent free */
  746. if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
  747. log_warn(LD_DIR, "Missing identity key"); goto err;
  748. }
  749. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  750. log_warn(LD_DIR, "Wrong size on identity key: %d bits!",
  751. (int)crypto_pk_keysize(tok->key)*8);
  752. goto err;
  753. }
  754. router->identity_pkey = tok->key;
  755. tok->key = NULL; /* Prevent free */
  756. if (crypto_pk_get_digest(router->identity_pkey,
  757. router->cache_info.identity_digest)) {
  758. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  759. }
  760. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  761. /* If there's a fingerprint line, it must match the identity digest. */
  762. char d[DIGEST_LEN];
  763. if (tok->n_args < 1) {
  764. log_warn(LD_DIR, "Too few arguments to fingerprint");
  765. goto err;
  766. }
  767. tor_strstrip(tok->args[0], " ");
  768. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  769. log_warn(LD_DIR, "Couldn't decode fingerprint %s",
  770. escaped(tok->args[0]));
  771. goto err;
  772. }
  773. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  774. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  775. tok->args[0]);
  776. goto err;
  777. }
  778. }
  779. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  780. router->platform = tor_strdup(tok->args[0]);
  781. }
  782. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  783. router->contact_info = tor_strdup(tok->args[0]);
  784. }
  785. exit_policy_tokens = find_all_exitpolicy(tokens);
  786. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  787. if (router_add_exit_policy(router,t)<0) {
  788. log_warn(LD_DIR,"Error in exit policy");
  789. goto err;
  790. });
  791. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  792. int i;
  793. router->declared_family = smartlist_create();
  794. for (i=0;i<tok->n_args;++i) {
  795. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  796. log_warn(LD_DIR, "Illegal nickname %s in family line",
  797. escaped(tok->args[i]));
  798. goto err;
  799. }
  800. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  801. }
  802. }
  803. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
  804. log_warn(LD_DIR, "Missing router signature");
  805. goto err;
  806. }
  807. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  808. log_warn(LD_DIR, "Bad object type or length on router signature");
  809. goto err;
  810. }
  811. if ((t=crypto_pk_public_checksig(router->identity_pkey, signed_digest,
  812. tok->object_body, 128)) != 20) {
  813. log_warn(LD_DIR, "Invalid signature %d",t);
  814. goto err;
  815. }
  816. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  817. log_warn(LD_DIR, "Mismatched signature");
  818. goto err;
  819. }
  820. if (!router->or_port) {
  821. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  822. goto err;
  823. }
  824. if (!router->bandwidthrate) {
  825. log_warn(LD_DIR,"bandwidthrate unreadable or 0. Failing.");
  826. goto err;
  827. }
  828. if (!router->platform) {
  829. router->platform = tor_strdup("<unknown>");
  830. }
  831. goto done;
  832. err:
  833. routerinfo_free(router);
  834. router = NULL;
  835. done:
  836. if (tokens) {
  837. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  838. smartlist_free(tokens);
  839. }
  840. if (exit_policy_tokens) {
  841. smartlist_free(exit_policy_tokens);
  842. }
  843. return router;
  844. }
  845. /** Helper: given a string <b>s</b>, return the start of the next router-status
  846. * object (starting with "r " at the start of a line). If none is found,
  847. * return the start of the next directory signature. If none is found, return
  848. * the end of the string. */
  849. static INLINE const char *
  850. find_start_of_next_routerstatus(const char *s)
  851. {
  852. const char *eos = strstr(s, "\nr ");
  853. if (!eos)
  854. eos = strstr(s, "\ndirectory-signature");
  855. if (eos)
  856. return eos+1;
  857. else
  858. return s + strlen(s);
  859. }
  860. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  861. * empty smartlist at <b>tokens</b>, parse and return the first router status
  862. * object in the string, and advance *<b>s</b> to just after the end of the
  863. * router status. Return NULL and advance *<b>s</b> on error. */
  864. static routerstatus_t *
  865. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens)
  866. {
  867. const char *eos;
  868. routerstatus_t *rs = NULL;
  869. directory_token_t *tok;
  870. char timebuf[ISO_TIME_LEN+1];
  871. struct in_addr in;
  872. tor_assert(tokens);
  873. eos = find_start_of_next_routerstatus(*s);
  874. if (tokenize_string(*s, eos, tokens, RTRSTATUS)) {
  875. log_warn(LD_DIR, "Error tokenizing router status");
  876. goto err;
  877. }
  878. if (smartlist_len(tokens) < 1) {
  879. log_warn(LD_DIR, "Impossibly short router status");
  880. goto err;
  881. }
  882. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  883. log_warn(LD_DIR, "Unrecognized keyword %s in router status; skipping.",
  884. escaped(tok->args[0]));
  885. goto err;
  886. }
  887. if (!(tok = find_first_by_keyword(tokens, K_R))) {
  888. log_warn(LD_DIR, "Missing 'r' keywork in router status; skipping.");
  889. goto err;
  890. }
  891. if (tok->n_args < 8) {
  892. log_warn(LD_DIR,
  893. "Too few arguments to 'r' keywork in router status; skipping.");
  894. }
  895. rs = tor_malloc_zero(sizeof(routerstatus_t));
  896. if (!is_legal_nickname(tok->args[0])) {
  897. log_warn(LD_DIR,
  898. "Invalid nickname %s in router status; skipping.",
  899. escaped(tok->args[0]));
  900. goto err;
  901. }
  902. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  903. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  904. log_warn(LD_DIR, "Error decoding digest %s", escaped(tok->args[1]));
  905. goto err;
  906. }
  907. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  908. log_warn(LD_DIR, "Error decoding digest %s", escaped(tok->args[2]));
  909. goto err;
  910. }
  911. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  912. tok->args[3], tok->args[4]) < 0 ||
  913. parse_iso_time(timebuf, &rs->published_on)<0) {
  914. log_warn(LD_DIR, "Error parsing time '%s %s'",
  915. tok->args[3], tok->args[4]);
  916. goto err;
  917. }
  918. if (tor_inet_aton(tok->args[5], &in) == 0) {
  919. log_warn(LD_DIR, "Error parsing address %s", escaped(tok->args[5]));
  920. goto err;
  921. }
  922. rs->addr = ntohl(in.s_addr);
  923. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  924. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  925. if ((tok = find_first_by_keyword(tokens, K_S))) {
  926. int i;
  927. for (i=0; i < tok->n_args; ++i) {
  928. if (!strcmp(tok->args[i], "Exit"))
  929. rs->is_exit = 1;
  930. else if (!strcmp(tok->args[i], "Stable"))
  931. rs->is_stable = 1;
  932. else if (!strcmp(tok->args[i], "Fast"))
  933. rs->is_fast = 1;
  934. else if (!strcmp(tok->args[i], "Running"))
  935. rs->is_running = 1;
  936. else if (!strcmp(tok->args[i], "Named"))
  937. rs->is_named = 1;
  938. else if (!strcmp(tok->args[i], "Valid"))
  939. rs->is_valid = 1;
  940. else if (!strcmp(tok->args[i], "V2Dir"))
  941. rs->is_v2_dir = 1;
  942. else if (!strcmp(tok->args[i], "Guard"))
  943. rs->is_possible_guard = 1;
  944. }
  945. }
  946. goto done;
  947. err:
  948. if (rs)
  949. routerstatus_free(rs);
  950. rs = NULL;
  951. done:
  952. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  953. smartlist_clear(tokens);
  954. *s = eos;
  955. return rs;
  956. }
  957. /** Helper to sort a smartlist of pointers to routerstatus_t */
  958. static int
  959. _compare_routerstatus_entries(const void **_a, const void **_b)
  960. {
  961. const routerstatus_t *a = *_a, *b = *_b;
  962. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  963. }
  964. /** Given a versioned (v2 or later) network-status object in <b>s</b>, try to
  965. * parse it and return the result. Return NULL on failure. Check the
  966. * signature of the network status, but do not (yet) check the signing key for
  967. * authority.
  968. */
  969. networkstatus_t *
  970. networkstatus_parse_from_string(const char *s)
  971. {
  972. const char *eos;
  973. smartlist_t *tokens = smartlist_create();
  974. networkstatus_t *ns = NULL;
  975. char ns_digest[DIGEST_LEN];
  976. char tmp_digest[DIGEST_LEN];
  977. struct in_addr in;
  978. directory_token_t *tok;
  979. int i;
  980. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  981. log_warn(LD_DIR, "Unable to compute digest of network-status");
  982. goto err;
  983. }
  984. eos = find_start_of_next_routerstatus(s);
  985. if (tokenize_string(s, eos, tokens, NETSTATUS)) {
  986. log_warn(LD_DIR, "Error tokenizing network-status header.");
  987. goto err;
  988. }
  989. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  990. log_warn(LD_DIR, "Unrecognized keyword %s; can't parse network-status",
  991. escaped(tok->args[0]));
  992. goto err;
  993. }
  994. ns = tor_malloc_zero(sizeof(networkstatus_t));
  995. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  996. if (!(tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION))) {
  997. log_warn(LD_DIR, "Couldn't find network-status-version keyword");
  998. goto err;
  999. }
  1000. if (!(tok = find_first_by_keyword(tokens, K_DIR_SOURCE))) {
  1001. log_warn(LD_DIR, "Couldn't find dir-source keyword");
  1002. goto err;
  1003. }
  1004. if (tok->n_args < 3) {
  1005. log_warn(LD_DIR, "Too few arguments to dir-source keyword");
  1006. goto err;
  1007. }
  1008. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1009. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1010. log_warn(LD_DIR, "Error parsing address %s", escaped(tok->args[1]));
  1011. goto err;
  1012. }
  1013. ns->source_addr = ntohl(in.s_addr);
  1014. ns->source_dirport =
  1015. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1016. if (ns->source_dirport == 0) {
  1017. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1018. goto err;
  1019. }
  1020. if (!(tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  1021. log_warn(LD_DIR, "Couldn't find fingerprint keyword");
  1022. goto err;
  1023. }
  1024. if (tok->n_args < 1) {
  1025. log_warn(LD_DIR, "Too few arguments to fingerprint");
  1026. goto err;
  1027. }
  1028. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1029. strlen(tok->args[0]))) {
  1030. log_warn(LD_DIR, "Couldn't decode fingerprint %s", escaped(tok->args[0]));
  1031. goto err;
  1032. }
  1033. if ((tok = find_first_by_keyword(tokens, K_CONTACT)) && tok->n_args) {
  1034. ns->contact = tok->args[0];
  1035. tok->args[0] = NULL;
  1036. }
  1037. if (!(tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY)) || !tok->key) {
  1038. log_warn(LD_DIR, "Missing dir-signing-key");
  1039. goto err;
  1040. }
  1041. ns->signing_key = tok->key;
  1042. tok->key = NULL;
  1043. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1044. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1045. goto err;
  1046. }
  1047. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1048. log_warn(LD_DIR,
  1049. "network-status fingerprint did not match dir-signing-key");
  1050. goto err;
  1051. }
  1052. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1053. for (i=0; i < tok->n_args; ++i) {
  1054. if (!strcmp(tok->args[i], "Names"))
  1055. ns->binds_names = 1;
  1056. if (!strcmp(tok->args[i], "Versions"))
  1057. ns->recommends_versions = 1;
  1058. }
  1059. }
  1060. if (ns->recommends_versions) {
  1061. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS)) ||
  1062. tok->n_args<1) {
  1063. log_warn(LD_DIR, "Missing client-versions");
  1064. }
  1065. ns->client_versions = tok->args[0];
  1066. tok->args[0] = NULL;
  1067. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1068. tok->n_args<1) {
  1069. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1070. goto err;
  1071. }
  1072. ns->server_versions = tok->args[0];
  1073. tok->args[0] = NULL;
  1074. }
  1075. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  1076. log_warn(LD_DIR, "Missing published time on directory.");
  1077. goto err;
  1078. }
  1079. tor_assert(tok->n_args == 1);
  1080. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1081. goto err;
  1082. }
  1083. ns->entries = smartlist_create();
  1084. s = eos;
  1085. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1086. smartlist_clear(tokens);
  1087. while (!strcmpstart(s, "r ")) {
  1088. routerstatus_t *rs;
  1089. if ((rs = routerstatus_parse_entry_from_string(&s, tokens)))
  1090. smartlist_add(ns->entries, rs);
  1091. }
  1092. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1093. /* Kill duplicate entries. */
  1094. for (i=0; i < smartlist_len(ns->entries)-1; ++i) {
  1095. routerstatus_t *rs1 = smartlist_get(ns->entries, i);
  1096. routerstatus_t *rs2 = smartlist_get(ns->entries, i+1);
  1097. if (!memcmp(rs1->identity_digest,
  1098. rs2->identity_digest, DIGEST_LEN)) {
  1099. log_warn(LD_DIR,
  1100. "Network-status has two entries for the same router. "
  1101. "Dropping one.");
  1102. smartlist_del_keeporder(ns->entries, i--);
  1103. routerstatus_free(rs1);
  1104. }
  1105. }
  1106. if (tokenize_string(s, NULL, tokens, NETSTATUS)) {
  1107. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1108. goto err;
  1109. }
  1110. if (smartlist_len(tokens) < 1) {
  1111. log_warn(LD_DIR, "Too few items in network-status footer.");
  1112. goto err;
  1113. }
  1114. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1115. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1116. log_warn(LD_DIR,
  1117. "Expected network-status footer to end with a signature.");
  1118. goto err;
  1119. }
  1120. if (check_directory_signature(ns_digest, tok, NULL, ns->signing_key, 0))
  1121. goto err;
  1122. goto done;
  1123. err:
  1124. if (ns)
  1125. networkstatus_free(ns);
  1126. ns = NULL;
  1127. done:
  1128. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1129. smartlist_free(tokens);
  1130. return ns;
  1131. }
  1132. /** Parse the addr policy in the string <b>s</b> and return it. If
  1133. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1134. * ADDR_POLICY_REJECT) for items that specify no action.
  1135. */
  1136. addr_policy_t *
  1137. router_parse_addr_policy_from_string(const char *s, int assume_action)
  1138. {
  1139. directory_token_t *tok = NULL;
  1140. const char *cp;
  1141. char *tmp;
  1142. addr_policy_t *r;
  1143. size_t len, idx;
  1144. /* *s might not end with \n, so we need to extend it with one. */
  1145. len = strlen(s);
  1146. cp = tmp = tor_malloc(len+2);
  1147. for (idx = 0; idx < len; ++idx) {
  1148. tmp[idx] = tolower(s[idx]);
  1149. }
  1150. tmp[len]='\n';
  1151. tmp[len+1]='\0';
  1152. while (TOR_ISSPACE(*cp))
  1153. ++cp;
  1154. if ((*cp == '*' || TOR_ISDIGIT(*cp)) && assume_action >= 0) {
  1155. char *new_str = tor_malloc(len+10);
  1156. tor_snprintf(new_str, len+10, "%s %s\n",
  1157. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", cp);
  1158. tor_free(tmp);
  1159. cp = tmp = new_str;
  1160. }
  1161. tok = get_next_token(&cp, RTR);
  1162. if (tok->tp == _ERR) {
  1163. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1164. goto err;
  1165. }
  1166. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1167. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1168. goto err;
  1169. }
  1170. /* Now that we've gotten an addr policy, add it to the router. */
  1171. r = router_parse_addr_policy(tok);
  1172. goto done;
  1173. err:
  1174. r = NULL;
  1175. done:
  1176. tor_free(tmp);
  1177. token_free(tok);
  1178. return r;
  1179. }
  1180. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1181. * <b>router</b>. Return 0 on success, -1 on failure. */
  1182. static int
  1183. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1184. {
  1185. addr_policy_t *newe, **tmpe;
  1186. newe = router_parse_addr_policy(tok);
  1187. if (!newe)
  1188. return -1;
  1189. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  1190. ;
  1191. *tmpe = newe;
  1192. return 0;
  1193. }
  1194. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  1195. * a new exit_policy_t corresponding to the token. */
  1196. static addr_policy_t *
  1197. router_parse_addr_policy(directory_token_t *tok)
  1198. {
  1199. addr_policy_t *newe;
  1200. // struct in_addr in;
  1201. char *arg;
  1202. // char *address;
  1203. // char buf[INET_NTOA_BUF_LEN];
  1204. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1205. if (tok->n_args != 1)
  1206. return NULL;
  1207. arg = tok->args[0];
  1208. if (!strcmpstart(arg,"private"))
  1209. return router_parse_private_addr_policy_private(tok);
  1210. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1211. newe->string = tor_malloc(8+strlen(arg));
  1212. /* XXX eventually, use the code from router.c:727 to generate this */
  1213. tor_snprintf(newe->string, 8+strlen(arg), "%s %s",
  1214. (tok->tp == K_REJECT) ? "reject" : "accept", arg);
  1215. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1216. : ADDR_POLICY_ACCEPT;
  1217. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1218. &newe->prt_min, &newe->prt_max))
  1219. goto policy_read_failed;
  1220. // in.s_addr = htonl(newe->addr);
  1221. // tor_inet_ntoa(&in, buf, sizeof(buf));
  1222. // address = tor_strdup(buf);
  1223. // in.s_addr = htonl(newe->msk);
  1224. // log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
  1225. // newe->policy_type == ADDR_POLICY_REJECT ? "reject" : "accept",
  1226. // address, inet_ntoa(in), newe->prt_min, newe->prt_max);
  1227. // tor_free(address);
  1228. return newe;
  1229. policy_read_failed:
  1230. tor_assert(newe->string);
  1231. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(newe->string));
  1232. tor_free(newe->string);
  1233. tor_free(newe);
  1234. return NULL;
  1235. }
  1236. /** Parse an exit policy line of the format "accept/reject private:...".
  1237. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1238. * router descriptors until earlier versions are obsolete.
  1239. */
  1240. static addr_policy_t *
  1241. router_parse_private_addr_policy_private(directory_token_t *tok)
  1242. {
  1243. /* XXXX duplicated from config.c */
  1244. static const char *private_nets[] = {
  1245. "0.0.0.0/8", "169.254.0.0/16",
  1246. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL };
  1247. char *arg;
  1248. addr_policy_t *result, **nextp;
  1249. int net;
  1250. uint16_t port_min, port_max;
  1251. arg = tok->args[0];
  1252. if (strcmpstart(arg, "private"))
  1253. return NULL;
  1254. arg += strlen("private");
  1255. arg = (char*) eat_whitespace(arg);
  1256. if (!arg || *arg != ':')
  1257. return NULL;
  1258. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1259. return NULL;
  1260. nextp = &result;
  1261. for (net = 0; private_nets[net]; ++net) {
  1262. size_t len;
  1263. *nextp = tor_malloc_zero(sizeof(addr_policy_t));
  1264. (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1265. : ADDR_POLICY_ACCEPT;
  1266. len = strlen(arg)+strlen(private_nets[net])+16;
  1267. (*nextp)->string = tor_malloc(len+1);
  1268. tor_snprintf((*nextp)->string, len, "%s %s%s",
  1269. tok->tp == K_REJECT ? "reject" : "accept",
  1270. private_nets[net], arg);
  1271. if (parse_addr_and_port_range((*nextp)->string + 7,
  1272. &(*nextp)->addr, &(*nextp)->msk,
  1273. &(*nextp)->prt_min, &(*nextp)->prt_max)) {
  1274. log_warn(LD_BUG, "Couldn't parse an address range we generated!");
  1275. return NULL;
  1276. }
  1277. nextp = &(*nextp)->next;
  1278. }
  1279. return result;
  1280. }
  1281. /** Log and exit if <b>t</b> is malformed */
  1282. void
  1283. assert_addr_policy_ok(addr_policy_t *t)
  1284. {
  1285. addr_policy_t *t2;
  1286. while (t) {
  1287. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  1288. t->policy_type == ADDR_POLICY_ACCEPT);
  1289. tor_assert(t->prt_min <= t->prt_max);
  1290. t2 = router_parse_addr_policy_from_string(t->string, -1);
  1291. tor_assert(t2);
  1292. tor_assert(t2->policy_type == t->policy_type);
  1293. tor_assert(t2->addr == t->addr);
  1294. tor_assert(t2->msk == t->msk);
  1295. tor_assert(t2->prt_min == t->prt_min);
  1296. tor_assert(t2->prt_max == t->prt_max);
  1297. tor_assert(!strcmp(t2->string, t->string));
  1298. tor_assert(t2->next == NULL);
  1299. addr_policy_free(t2);
  1300. t = t->next;
  1301. }
  1302. }
  1303. /*
  1304. * Low-level tokenizer for router descriptors and directories.
  1305. */
  1306. /** Free all resources allocated for <b>tok</b> */
  1307. static void
  1308. token_free(directory_token_t *tok)
  1309. {
  1310. int i;
  1311. tor_assert(tok);
  1312. if (tok->args) {
  1313. for (i = 0; i < tok->n_args; ++i) {
  1314. tor_free(tok->args[i]);
  1315. }
  1316. tor_free(tok->args);
  1317. }
  1318. tor_free(tok->object_type);
  1319. tor_free(tok->object_body);
  1320. if (tok->key)
  1321. crypto_free_pk_env(tok->key);
  1322. tor_free(tok);
  1323. }
  1324. /** Helper function: read the next token from *s, advance *s to the end
  1325. * of the token, and return the parsed token. If 'where' is DIR
  1326. * or RTR, reject all tokens of the wrong type.
  1327. */
  1328. static directory_token_t *
  1329. get_next_token(const char **s, where_syntax where)
  1330. {
  1331. const char *next, *obstart;
  1332. int i, done, allocated, is_opt;
  1333. directory_token_t *tok;
  1334. arg_syntax a_syn;
  1335. obj_syntax o_syn = NO_OBJ;
  1336. #define RET_ERR(msg) \
  1337. do { if (tok) token_free(tok); \
  1338. tok = tor_malloc_zero(sizeof(directory_token_t));\
  1339. tok->tp = _ERR; \
  1340. tok->error = msg; \
  1341. goto done_tokenizing; } while (0)
  1342. tok = tor_malloc_zero(sizeof(directory_token_t));
  1343. tok->tp = _ERR;
  1344. *s = eat_whitespace(*s);
  1345. if (!**s) {
  1346. tok->tp = _EOF;
  1347. return tok;
  1348. }
  1349. next = find_whitespace(*s);
  1350. if (!next) {
  1351. tok->error = "Unexpected EOF"; return tok;
  1352. }
  1353. /* It's a keyword... but which one? */
  1354. is_opt = !strncmp("opt", *s, next-*s);
  1355. if (is_opt) {
  1356. *s = eat_whitespace(next);
  1357. next = NULL;
  1358. if (**s)
  1359. next = find_whitespace(*s);
  1360. if (!**s || !next) {
  1361. RET_ERR("opt without keyword");
  1362. }
  1363. }
  1364. for (i = 0; token_table[i].t ; ++i) {
  1365. if (!strncmp(token_table[i].t, *s, next-*s)) {
  1366. /* We've found the keyword. */
  1367. tok->tp = token_table[i].v;
  1368. a_syn = token_table[i].s;
  1369. o_syn = token_table[i].os;
  1370. if (!(token_table[i].ws & where)) {
  1371. if (where == DIR) {
  1372. RET_ERR("Found an out-of-place token in a directory section");
  1373. } else if (where == RTR) {
  1374. RET_ERR("Found an out-of-place token in a router descriptor");
  1375. } else if (where == NETSTATUS) {
  1376. RET_ERR("Found an out-of-place token in a network-status header");
  1377. } else {
  1378. RET_ERR("Found an out-of-place token in a router status body");
  1379. }
  1380. }
  1381. if (a_syn == ARGS) {
  1382. /* This keyword takes multiple arguments. */
  1383. i = 0;
  1384. done = (*next == '\n');
  1385. allocated = 32;
  1386. tok->args = tor_malloc(sizeof(char*)*32);
  1387. *s = eat_whitespace_no_nl(next);
  1388. while (**s != '\n' && !done) {
  1389. next = find_whitespace(*s);
  1390. if (*next == '\n')
  1391. done = 1;
  1392. if (i == allocated) {
  1393. allocated *= 2;
  1394. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1395. }
  1396. tok->args[i++] = tor_strndup(*s,next-*s);
  1397. *s = eat_whitespace_no_nl(next+1);
  1398. }
  1399. tok->n_args = i;
  1400. } else if (a_syn == CONCAT_ARGS) {
  1401. /* The keyword takes the line as a single argument */
  1402. *s = eat_whitespace_no_nl(next);
  1403. next = strchr(*s, '\n');
  1404. if (!next)
  1405. RET_ERR("Unexpected EOF");
  1406. tok->args = tor_malloc(sizeof(char*));
  1407. tok->args[0] = tor_strndup(*s,next-*s);
  1408. tok->n_args = 1;
  1409. *s = eat_whitespace_no_nl(next+1);
  1410. } else {
  1411. /* The keyword takes no arguments. */
  1412. tor_assert(a_syn == NO_ARGS);
  1413. *s = eat_whitespace_no_nl(next);
  1414. if (**s != '\n') {
  1415. RET_ERR("Unexpected arguments");
  1416. }
  1417. tok->n_args = 0;
  1418. *s = eat_whitespace_no_nl(*s+1);
  1419. }
  1420. break;
  1421. }
  1422. }
  1423. if (tok->tp == _ERR) {
  1424. if (is_opt) {
  1425. tok->tp = K_OPT;
  1426. *s = eat_whitespace_no_nl(next);
  1427. next = strchr(*s,'\n');
  1428. if (!next)
  1429. RET_ERR("Unexpected EOF");
  1430. tok->args = tor_malloc(sizeof(char*));
  1431. tok->args[0] = tor_strndup(*s,next-*s);
  1432. tok->n_args = 1;
  1433. *s = eat_whitespace_no_nl(next+1);
  1434. o_syn = OBJ_OK;
  1435. } else {
  1436. tok->tp = _UNRECOGNIZED;
  1437. next = strchr(*s, '\n');
  1438. if (!next) {
  1439. RET_ERR("Unexpected EOF");
  1440. }
  1441. tok->args = tor_malloc(sizeof(char*));
  1442. tok->args[0] = tor_strndup(*s,next-*s);
  1443. tok->n_args = 1;
  1444. *s = next+1;
  1445. o_syn = OBJ_OK;
  1446. }
  1447. }
  1448. *s = eat_whitespace(*s);
  1449. if (strcmpstart(*s, "-----BEGIN ")) {
  1450. goto done_tokenizing;
  1451. }
  1452. obstart = *s;
  1453. *s += 11; /* length of "-----BEGIN ". */
  1454. next = strchr(*s, '\n');
  1455. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  1456. RET_ERR("Malformed object: bad begin line");
  1457. }
  1458. tok->object_type = tor_strndup(*s, next-*s-5);
  1459. *s = next+1;
  1460. next = strstr(*s, "-----END ");
  1461. if (!next) {
  1462. RET_ERR("Malformed object: missing end line");
  1463. }
  1464. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1465. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  1466. RET_ERR("Malformed object: mismatched end line");
  1467. next = strchr(next,'\n')+1;
  1468. tok->key = crypto_new_pk_env();
  1469. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1470. RET_ERR("Couldn't parse public key.");
  1471. *s = next;
  1472. } else {
  1473. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1474. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1475. if (i<0) {
  1476. RET_ERR("Malformed object: bad base64-encoded data");
  1477. }
  1478. tok->object_size = i;
  1479. *s = next + 9; /* length of "-----END ". */
  1480. i = strlen(tok->object_type);
  1481. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  1482. RET_ERR("Malformed object: mismatched end tag");
  1483. }
  1484. *s += i+6;
  1485. }
  1486. switch (o_syn)
  1487. {
  1488. case NO_OBJ:
  1489. if (tok->object_body)
  1490. RET_ERR("Unexpected object for keyword");
  1491. if (tok->key)
  1492. RET_ERR("Unexpected public key for keyword");
  1493. break;
  1494. case NEED_OBJ:
  1495. if (!tok->object_body)
  1496. RET_ERR("Missing object for keyword");
  1497. break;
  1498. case NEED_KEY:
  1499. if (!tok->key)
  1500. RET_ERR("Missing public key for keyword");
  1501. break;
  1502. case OBJ_OK:
  1503. break;
  1504. }
  1505. done_tokenizing:
  1506. return tok;
  1507. #undef RET_ERR
  1508. }
  1509. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1510. * them to <b>out</b>. If <b>is_dir</b> is true, reject all non-directory
  1511. * tokens; else reject all non-routerdescriptor tokens.
  1512. */
  1513. static int
  1514. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1515. where_syntax where)
  1516. {
  1517. const char **s;
  1518. directory_token_t *tok = NULL;
  1519. s = &start;
  1520. if (!end)
  1521. end = start+strlen(start);
  1522. while (*s < end && (!tok || tok->tp != _EOF)) {
  1523. tok = get_next_token(s, where);
  1524. if (tok->tp == _ERR) {
  1525. log_warn(LD_DIR, "parse error: %s", tok->error);
  1526. return -1;
  1527. }
  1528. smartlist_add(out, tok);
  1529. *s = eat_whitespace(*s);
  1530. }
  1531. return 0;
  1532. }
  1533. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1534. * NULL if no such keyword is found.
  1535. */
  1536. static directory_token_t *
  1537. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1538. {
  1539. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1540. return NULL;
  1541. }
  1542. /** Return a newly allocated smartlist of all accept or reject tokens in
  1543. * <b>s</b>.
  1544. */
  1545. static smartlist_t *
  1546. find_all_exitpolicy(smartlist_t *s)
  1547. {
  1548. smartlist_t *out = smartlist_create();
  1549. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1550. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1551. smartlist_add(out,t));
  1552. return out;
  1553. }
  1554. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  1555. * occurrence of <b>start_str</b> through the first newline after the first
  1556. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1557. * <b>digest</b>; return 0 on success.
  1558. *
  1559. * If no such substring exists, return -1.
  1560. */
  1561. static int
  1562. router_get_hash_impl(const char *s, char *digest,
  1563. const char *start_str,
  1564. const char *end_str)
  1565. {
  1566. char *start, *end;
  1567. start = strstr(s, start_str);
  1568. if (!start) {
  1569. log_warn(LD_DIR,"couldn't find \"%s\"",start_str);
  1570. return -1;
  1571. }
  1572. if (start != s && *(start-1) != '\n') {
  1573. log_warn(LD_DIR,
  1574. "first occurrence of \"%s\" is not at the start of a line",
  1575. start_str);
  1576. return -1;
  1577. }
  1578. end = strstr(start+strlen(start_str), end_str);
  1579. if (!end) {
  1580. log_warn(LD_DIR,"couldn't find \"%s\"",end_str);
  1581. return -1;
  1582. }
  1583. end = strchr(end+strlen(end_str), '\n');
  1584. if (!end) {
  1585. log_warn(LD_DIR,"couldn't find EOL");
  1586. return -1;
  1587. }
  1588. ++end;
  1589. if (crypto_digest(digest, start, end-start)) {
  1590. log_warn(LD_DIR,"couldn't compute digest");
  1591. return -1;
  1592. }
  1593. return 0;
  1594. }
  1595. /** Parse the Tor version of the platform string <b>platform</b>,
  1596. * and compare it to the version in <b>cutoff</b>. Return 1 if
  1597. * the router is at least as new as the cutoff, else return 0.
  1598. */
  1599. int
  1600. tor_version_as_new_as(const char *platform, const char *cutoff)
  1601. {
  1602. tor_version_t cutoff_version, router_version;
  1603. char *s, *start;
  1604. char tmp[128];
  1605. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  1606. log_warn(LD_DIR,"Bug: cutoff version '%s' unparseable.",cutoff);
  1607. return 0;
  1608. }
  1609. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  1610. return 1;
  1611. start = (char *)eat_whitespace(platform+3);
  1612. if (!*start) return 0;
  1613. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  1614. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  1615. return 0;
  1616. strlcpy(tmp, start, s-start+1);
  1617. if (tor_version_parse(tmp, &router_version)<0) {
  1618. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  1619. return 1; /* be safe and say yes */
  1620. }
  1621. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  1622. }
  1623. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  1624. * Return 0 on success, -1 on failure. */
  1625. int
  1626. tor_version_parse(const char *s, tor_version_t *out)
  1627. {
  1628. char *eos=NULL, *cp=NULL;
  1629. /* Format is:
  1630. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ -cvs ] ]
  1631. */
  1632. tor_assert(s);
  1633. tor_assert(out);
  1634. memset(out, 0, sizeof(tor_version_t));
  1635. if (!strcasecmpstart(s, "Tor "))
  1636. s += 4;
  1637. /* Get major. */
  1638. out->major = strtol(s,&eos,10);
  1639. if (!eos || eos==s || *eos != '.') return -1;
  1640. cp = eos+1;
  1641. /* Get minor */
  1642. out->minor = strtol(cp,&eos,10);
  1643. if (!eos || eos==cp || *eos != '.') return -1;
  1644. cp = eos+1;
  1645. /* Get micro */
  1646. out->micro = strtol(cp,&eos,10);
  1647. if (!eos || eos==cp) return -1;
  1648. if (!*eos) {
  1649. out->status = VER_RELEASE;
  1650. out->patchlevel = 0;
  1651. out->cvs = IS_NOT_CVS;
  1652. return 0;
  1653. }
  1654. cp = eos;
  1655. /* Get status */
  1656. if (*cp == '.') {
  1657. out->status = VER_RELEASE;
  1658. ++cp;
  1659. } else if (0==strncmp(cp, "pre", 3)) {
  1660. out->status = VER_PRE;
  1661. cp += 3;
  1662. } else if (0==strncmp(cp, "rc", 2)) {
  1663. out->status = VER_RC;
  1664. cp += 2;
  1665. } else {
  1666. return -1;
  1667. }
  1668. /* Get patchlevel */
  1669. out->patchlevel = strtol(cp,&eos,10);
  1670. if (!eos || eos==cp) return -1;
  1671. cp = eos;
  1672. /* Get cvs status and status tag. */
  1673. if (*cp == '-' || *cp == '.')
  1674. ++cp;
  1675. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  1676. if (0==strcmp(cp, "cvs")) {
  1677. out->cvs = IS_CVS;
  1678. } else {
  1679. out->cvs = IS_NOT_CVS;
  1680. }
  1681. return 0;
  1682. }
  1683. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  1684. * b. */
  1685. int
  1686. tor_version_compare(tor_version_t *a, tor_version_t *b)
  1687. {
  1688. int i;
  1689. tor_assert(a);
  1690. tor_assert(b);
  1691. if ((i = a->major - b->major))
  1692. return i;
  1693. else if ((i = a->minor - b->minor))
  1694. return i;
  1695. else if ((i = a->micro - b->micro))
  1696. return i;
  1697. else if ((i = a->status - b->status))
  1698. return i;
  1699. else if ((i = a->patchlevel - b->patchlevel))
  1700. return i;
  1701. if (a->major > 0 || a->minor > 0) {
  1702. return strcmp(a->status_tag, b->status_tag);
  1703. } else {
  1704. return (a->cvs - b->cvs);
  1705. }
  1706. }
  1707. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  1708. */
  1709. static int
  1710. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  1711. {
  1712. tor_assert(a);
  1713. tor_assert(b);
  1714. return ((a->major == b->major) &&
  1715. (a->minor == b->minor) &&
  1716. (a->micro == b->micro));
  1717. }
  1718. /** Helper: Given pointers to two strings describing tor versions, return -1
  1719. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  1720. * Used to sort a list of versions. */
  1721. static int
  1722. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  1723. {
  1724. const char *a = *_a, *b = *_b;
  1725. int ca, cb;
  1726. tor_version_t va, vb;
  1727. ca = tor_version_parse(a, &va);
  1728. cb = tor_version_parse(b, &vb);
  1729. /* If they both parse, compare them. */
  1730. if (!ca && !cb)
  1731. return tor_version_compare(&va,&vb);
  1732. /* If one parses, it comes first. */
  1733. if (!ca && cb)
  1734. return -1;
  1735. if (ca && !cb)
  1736. return 1;
  1737. /* If neither parses, compare strings. Also, the directory server admin
  1738. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  1739. return strcmp(a,b);
  1740. }
  1741. /** Sort a list of string-representations of versions in ascending order. */
  1742. void
  1743. sort_version_list(smartlist_t *versions, int remove_duplicates)
  1744. {
  1745. int i;
  1746. smartlist_sort(versions, _compare_tor_version_str_ptr);
  1747. if (!remove_duplicates)
  1748. return;
  1749. for (i = 1; i < smartlist_len(versions); ++i) {
  1750. const void *a, *b;
  1751. a = smartlist_get(versions, i-1);
  1752. b = smartlist_get(versions, i);
  1753. /* use version_cmp so we catch multiple representations of the same
  1754. * version */
  1755. if (_compare_tor_version_str_ptr(&a,&b) == 0) {
  1756. tor_free(smartlist_get(versions, i));
  1757. smartlist_del_keeporder(versions, i--);
  1758. }
  1759. }
  1760. }