routerparse.c 59 KB

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