routerparse.c 56 KB

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