routerparse.c 56 KB

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