routerparse.c 59 KB

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