routerparse.c 59 KB

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