protover.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. // Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. use external::c_tor_version_as_new_as;
  4. use std::str::FromStr;
  5. use std::fmt;
  6. use std::collections::{HashMap, HashSet};
  7. use std::string::String;
  8. /// The first version of Tor that included "proto" entries in its descriptors.
  9. /// Authorities should use this to decide whether to guess proto lines.
  10. const FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS: &'static str = "0.2.9.3-alpha";
  11. /// The maximum number of subprotocol version numbers we will attempt to expand
  12. /// before concluding that someone is trying to DoS us
  13. const MAX_PROTOCOLS_TO_EXPAND: u32 = 500;
  14. /// Currently supported protocols and their versions
  15. const SUPPORTED_PROTOCOLS: &'static [&'static str] = &[
  16. "Cons=1-2",
  17. "Desc=1-2",
  18. "DirCache=1-2",
  19. "HSDir=1-2",
  20. "HSIntro=3-4",
  21. "HSRend=1-2",
  22. "Link=1-4",
  23. "LinkAuth=1,3",
  24. "Microdesc=1-2",
  25. "Relay=1-2",
  26. ];
  27. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  28. #[derive(Hash, Eq, PartialEq, Debug)]
  29. pub enum Proto {
  30. Cons,
  31. Desc,
  32. DirCache,
  33. HSDir,
  34. HSIntro,
  35. HSRend,
  36. Link,
  37. LinkAuth,
  38. Microdesc,
  39. Relay,
  40. }
  41. impl fmt::Display for Proto {
  42. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  43. write!(f, "{:?}", self)
  44. }
  45. }
  46. /// Translates a string representation of a protocol into a Proto type.
  47. /// Error if the string is an unrecognized protocol name.
  48. impl FromStr for Proto {
  49. type Err = &'static str;
  50. fn from_str(s: &str) -> Result<Self, Self::Err> {
  51. match s {
  52. "Cons" => Ok(Proto::Cons),
  53. "Desc" => Ok(Proto::Desc),
  54. "DirCache" => Ok(Proto::DirCache),
  55. "HSDir" => Ok(Proto::HSDir),
  56. "HSIntro" => Ok(Proto::HSIntro),
  57. "HSRend" => Ok(Proto::HSRend),
  58. "Link" => Ok(Proto::Link),
  59. "LinkAuth" => Ok(Proto::LinkAuth),
  60. "Microdesc" => Ok(Proto::Microdesc),
  61. "Relay" => Ok(Proto::Relay),
  62. _ => Err("Not a valid protocol type"),
  63. }
  64. }
  65. }
  66. /// Get the string representation of current supported protocols
  67. ///
  68. /// # Returns
  69. ///
  70. /// A `String` whose value is the existing protocols supported by tor.
  71. /// Returned data is in the format as follows:
  72. ///
  73. /// "HSDir=1-1 LinkAuth=1"
  74. ///
  75. pub fn get_supported_protocols() -> String {
  76. SUPPORTED_PROTOCOLS.join(" ")
  77. }
  78. /// Translates a vector representation of a protocol list into a HashMap
  79. fn parse_protocols(
  80. protocols: &[&str],
  81. ) -> Result<HashMap<Proto, HashSet<u32>>, &'static str> {
  82. let mut parsed = HashMap::new();
  83. for subproto in protocols {
  84. let (name, version) = get_proto_and_vers(subproto)?;
  85. parsed.insert(name, version);
  86. }
  87. Ok(parsed)
  88. }
  89. /// Translates a string representation of a protocol list to a HashMap
  90. fn parse_protocols_from_string<'a>(
  91. protocol_string: &'a str,
  92. ) -> Result<HashMap<Proto, HashSet<u32>>, &'static str> {
  93. let protocols: &[&'a str] =
  94. &protocol_string.split(" ").collect::<Vec<&'a str>>()[..];
  95. parse_protocols(protocols)
  96. }
  97. /// Translates supported tor versions from a string into a HashMap, which is
  98. /// useful when looking up a specific subprotocol.
  99. ///
  100. /// # Returns
  101. ///
  102. /// A `Result` whose `Ok` value is a `HashMap<Proto, <u32>>` holding all
  103. /// subprotocols and versions currently supported by tor.
  104. ///
  105. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  106. /// of the error.
  107. ///
  108. fn tor_supported() -> Result<HashMap<Proto, HashSet<u32>>, &'static str> {
  109. parse_protocols(&SUPPORTED_PROTOCOLS)
  110. }
  111. /// Get the unique version numbers supported by a subprotocol.
  112. ///
  113. /// # Inputs
  114. ///
  115. /// * `version_string`, a string comprised of "[0-9,-]"
  116. ///
  117. /// # Returns
  118. ///
  119. /// A `Result` whose `Ok` value is a `HashSet<u32>` holding all of the unique
  120. /// version numbers. If there were ranges in the `version_string`, then these
  121. /// are expanded, i.e. `"1-3"` would expand to `HashSet<u32>::new([1, 2, 3])`.
  122. /// The returned HashSet is *unordered*.
  123. ///
  124. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  125. /// of the error.
  126. ///
  127. /// # Errors
  128. ///
  129. /// This function will error if:
  130. ///
  131. /// * the `version_string` is empty or contains an equals (`"="`) sign,
  132. /// * the expansion of a version range produces an error (see
  133. /// `expand_version_range`),
  134. /// * any single version number is not parseable as an `u32` in radix 10, or
  135. /// * there are greater than 2^16 version numbers to expand.
  136. ///
  137. fn get_versions(version_string: &str) -> Result<HashSet<u32>, &'static str> {
  138. if version_string.is_empty() {
  139. return Err("version string is empty");
  140. }
  141. let mut versions = HashSet::<u32>::new();
  142. for piece in version_string.split(",") {
  143. if piece.contains("-") {
  144. for p in expand_version_range(piece)? {
  145. versions.insert(p);
  146. }
  147. } else {
  148. versions.insert(u32::from_str(piece).or(
  149. Err("invalid protocol entry"),
  150. )?);
  151. }
  152. if versions.len() > MAX_PROTOCOLS_TO_EXPAND as usize {
  153. return Err("Too many versions to expand");
  154. }
  155. }
  156. Ok(versions)
  157. }
  158. /// Parse the subprotocol type and its version numbers.
  159. ///
  160. /// # Inputs
  161. ///
  162. /// * A `protocol_entry` string, comprised of a keyword, an "=" sign, and one
  163. /// or more version numbers.
  164. ///
  165. /// # Returns
  166. ///
  167. /// A `Result` whose `Ok` value is a tuple of `(Proto, HashSet<u32>)`, where the
  168. /// first element is the subprotocol type (see `protover::Proto`) and the last
  169. /// element is a(n unordered) set of unique version numbers which are supported.
  170. /// Otherwise, the `Err` value of this `Result` is a description of the error
  171. ///
  172. fn get_proto_and_vers<'a>(
  173. protocol_entry: &'a str,
  174. ) -> Result<(Proto, HashSet<u32>), &'static str> {
  175. let mut parts = protocol_entry.splitn(2, "=");
  176. let proto = match parts.next() {
  177. Some(n) => n,
  178. None => return Err("invalid protover entry"),
  179. };
  180. let vers = match parts.next() {
  181. Some(n) => n,
  182. None => return Err("invalid protover entry"),
  183. };
  184. let versions = get_versions(vers)?;
  185. let proto_name = proto.parse()?;
  186. Ok((proto_name, versions))
  187. }
  188. /// Parses a single subprotocol entry string into subprotocol and version
  189. /// parts, and then checks whether any of those versions are unsupported.
  190. /// Helper for protover::all_supported
  191. ///
  192. /// # Inputs
  193. ///
  194. /// Accepted data is in the string format as follows:
  195. ///
  196. /// "HSDir=1-1"
  197. ///
  198. /// # Returns
  199. ///
  200. /// Returns `true` if the protocol entry is well-formatted and only contains
  201. /// versions that are also supported in tor. Otherwise, returns false
  202. ///
  203. fn contains_only_supported_protocols(proto_entry: &str) -> bool {
  204. let (name, mut vers) = match get_proto_and_vers(proto_entry) {
  205. Ok(n) => n,
  206. Err(_) => return false,
  207. };
  208. let currently_supported: HashMap<Proto, HashSet<u32>> =
  209. match tor_supported() {
  210. Ok(n) => n,
  211. Err(_) => return false,
  212. };
  213. let supported_versions = match currently_supported.get(&name) {
  214. Some(n) => n,
  215. None => return false,
  216. };
  217. vers.retain(|x| !supported_versions.contains(x));
  218. vers.is_empty()
  219. }
  220. /// Determine if we support every protocol a client supports, and if not,
  221. /// determine which protocols we do not have support for.
  222. ///
  223. /// # Inputs
  224. ///
  225. /// Accepted data is in the string format as follows:
  226. ///
  227. /// "HSDir=1-1 LinkAuth=1-2"
  228. ///
  229. /// # Returns
  230. ///
  231. /// Return `true` if every protocol version is one that we support.
  232. /// Otherwise, return `false`.
  233. /// Optionally, return parameters which the client supports but which we do not
  234. ///
  235. /// # Examples
  236. /// ```
  237. /// use protover::all_supported;
  238. ///
  239. /// let (is_supported, unsupported) = all_supported("Link=1");
  240. /// assert_eq!(true, is_supported);
  241. ///
  242. /// let (is_supported, unsupported) = all_supported("Link=5-6");
  243. /// assert_eq!(false, is_supported);
  244. /// assert_eq!("Link=5-6", unsupported);
  245. ///
  246. pub fn all_supported(protocols: &str) -> (bool, String) {
  247. let unsupported = protocols
  248. .split_whitespace()
  249. .filter(|v| !contains_only_supported_protocols(v))
  250. .collect::<Vec<&str>>();
  251. (unsupported.is_empty(), unsupported.join(" "))
  252. }
  253. /// Return true iff the provided protocol list includes support for the
  254. /// indicated protocol and version.
  255. /// Otherwise, return false
  256. ///
  257. /// # Inputs
  258. ///
  259. /// * `list`, a string representation of a list of protocol entries.
  260. /// * `proto`, a `Proto` to test support for
  261. /// * `vers`, a `u32` version which we will go on to determine whether the
  262. /// specified protocol supports.
  263. ///
  264. /// # Examples
  265. /// ```
  266. /// use protover::*;
  267. ///
  268. /// let is_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  269. /// Proto::Cons,1);
  270. /// assert_eq!(true, is_supported);
  271. ///
  272. /// let is_not_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  273. /// Proto::Cons,5);
  274. /// assert_eq!(false, is_not_supported)
  275. /// ```
  276. pub fn protover_string_supports_protocol(
  277. list: &str,
  278. proto: Proto,
  279. vers: u32,
  280. ) -> bool {
  281. let supported: HashMap<Proto, HashSet<u32>>;
  282. match parse_protocols_from_string(list) {
  283. Ok(result) => supported = result,
  284. Err(_) => return false,
  285. }
  286. let supported_versions = match supported.get(&proto) {
  287. Some(n) => n,
  288. None => return false,
  289. };
  290. supported_versions.contains(&vers)
  291. }
  292. /// Fully expand a version range. For example, 1-3 expands to 1,2,3
  293. /// Helper for get_versions
  294. ///
  295. /// # Inputs
  296. ///
  297. /// `range`, a string comprised of "[0-9,-]"
  298. ///
  299. /// # Returns
  300. ///
  301. /// A `Result` whose `Ok` value a vector of unsigned integers representing the
  302. /// expanded range of supported versions by a single protocol.
  303. /// Otherwise, the `Err` value of this `Result` is a description of the error
  304. ///
  305. /// # Errors
  306. ///
  307. /// This function will error if:
  308. ///
  309. /// * the specified range is empty
  310. /// * the version range does not contain both a valid lower and upper bound.
  311. ///
  312. fn expand_version_range(range: &str) -> Result<Vec<u32>, &'static str> {
  313. if range.is_empty() {
  314. return Err("version string empty");
  315. }
  316. let mut parts = range.split("-");
  317. let lower_string = parts.next().ok_or(
  318. "cannot parse protocol range lower bound",
  319. )?;
  320. let lower = u32::from_str_radix(lower_string, 10).or(Err(
  321. "cannot parse protocol range lower bound",
  322. ))?;
  323. let higher_string = parts.next().ok_or(
  324. "cannot parse protocol range upper bound",
  325. )?;
  326. let higher = u32::from_str_radix(higher_string, 10).or(Err(
  327. "cannot parse protocol range upper bound",
  328. ))?;
  329. // We can use inclusive range syntax when it becomes stable.
  330. Ok((lower..higher + 1).collect())
  331. }
  332. /// Checks to see if there is a continuous range of integers, starting at the
  333. /// first in the list. Returns the last integer in the range if a range exists.
  334. /// Helper for compute_vote
  335. ///
  336. /// # Inputs
  337. ///
  338. /// `list`, an ordered vector of `u32` integers of "[0-9,-]" representing the
  339. /// supported versions for a single protocol.
  340. ///
  341. /// # Returns
  342. ///
  343. /// A `bool` indicating whether the list contains a range, starting at the
  344. /// first in the list, and an `u32` of the last integer in the range.
  345. ///
  346. /// For example, if given vec![1, 2, 3, 5], find_range will return true,
  347. /// as there is a continuous range, and 3, which is the last number in the
  348. /// continuous range.
  349. ///
  350. fn find_range(list: &Vec<u32>) -> (bool, u32) {
  351. if list.len() == 0 {
  352. return (false, 0);
  353. }
  354. let mut iterable = list.iter().peekable();
  355. let mut range_end = match iterable.next() {
  356. Some(n) => *n,
  357. None => return (false, 0),
  358. };
  359. let mut has_range = false;
  360. while iterable.peek().is_some() {
  361. let n = *iterable.next().unwrap();
  362. if n != range_end + 1 {
  363. break;
  364. }
  365. has_range = true;
  366. range_end = n;
  367. }
  368. (has_range, range_end)
  369. }
  370. /// Contracts a HashSet representation of supported versions into a string.
  371. /// Helper for compute_vote
  372. ///
  373. /// # Inputs
  374. ///
  375. /// `supported_set`, a set of integers of "[0-9,-]" representing the
  376. /// supported versions for a single protocol.
  377. ///
  378. /// # Returns
  379. ///
  380. /// A `String` representation of this set in ascending order.
  381. ///
  382. fn contract_protocol_list<'a>(supported_set: &'a HashSet<u32>) -> String {
  383. let mut supported: Vec<u32> = supported_set.iter()
  384. .map(|x| *x)
  385. .collect();
  386. supported.sort();
  387. let mut final_output: Vec<String> = Vec::new();
  388. while supported.len() != 0 {
  389. let (has_range, end) = find_range(&supported);
  390. let current = supported.remove(0);
  391. if has_range {
  392. final_output.push(format!(
  393. "{}-{}",
  394. current.to_string(),
  395. &end.to_string(),
  396. ));
  397. supported.retain(|&x| x > end);
  398. } else {
  399. final_output.push(current.to_string());
  400. }
  401. }
  402. final_output.join(",")
  403. }
  404. /// Parses a protocol list without validating the protocol names
  405. ///
  406. /// # Inputs
  407. ///
  408. /// * `protocol_string`, a string comprised of keys and values, both which are
  409. /// strings. The keys are the protocol names while values are a string
  410. /// representation of the supported versions.
  411. ///
  412. /// The input is _not_ expected to be a subset of the Proto types
  413. ///
  414. /// # Returns
  415. ///
  416. /// A `Result` whose `Ok` value is a `HashSet<u32>` holding all of the unique
  417. /// version numbers.
  418. ///
  419. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  420. /// of the error.
  421. ///
  422. /// # Errors
  423. ///
  424. /// This function will error if:
  425. ///
  426. /// * The protocol string does not follow the "protocol_name=version_list"
  427. /// expected format
  428. /// * If the version string is malformed. See `get_versions`.
  429. ///
  430. fn parse_protocols_from_string_with_no_validation<'a>(
  431. protocol_string: &'a str,
  432. ) -> Result<HashMap<String, HashSet<u32>>, &'static str> {
  433. let protocols = &protocol_string.split(" ").collect::<Vec<&'a str>>()[..];
  434. let mut parsed: HashMap<String, HashSet<u32>> = HashMap::new();
  435. for subproto in protocols {
  436. let mut parts = subproto.splitn(2, "=");
  437. let name = match parts.next() {
  438. Some(n) => n,
  439. None => return Err("invalid protover entry"),
  440. };
  441. let vers = match parts.next() {
  442. Some(n) => n,
  443. None => return Err("invalid protover entry"),
  444. };
  445. let versions = get_versions(vers)?;
  446. parsed.insert(String::from(name), versions);
  447. }
  448. Ok(parsed)
  449. }
  450. /// Protocol voting implementation.
  451. ///
  452. /// Given a list of strings describing protocol versions, return a new
  453. /// string encoding all of the protocols that are listed by at
  454. /// least threshold of the inputs.
  455. ///
  456. /// The string is sorted according to the following conventions:
  457. /// - Protocols names are alphabetized
  458. /// - Protocols are in order low to high
  459. /// - Individual and ranges are listed together. For example,
  460. /// "3, 5-10,13"
  461. /// - All entries are unique
  462. ///
  463. /// # Examples
  464. /// ```
  465. /// use protover::compute_vote;
  466. ///
  467. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  468. /// let vote = compute_vote(protos, 2);
  469. /// assert_eq!("Link=3", vote)
  470. /// ```
  471. pub fn compute_vote(
  472. list_of_proto_strings: Vec<String>,
  473. threshold: i32,
  474. ) -> String {
  475. let empty = String::from("");
  476. if list_of_proto_strings.is_empty() {
  477. return empty;
  478. }
  479. // all_count is a structure to represent the count of the number of
  480. // supported versions for a specific protocol. For example, in JSON format:
  481. // {
  482. // "FirstSupportedProtocol": {
  483. // "1": "3",
  484. // "2": "1"
  485. // }
  486. // }
  487. // means that FirstSupportedProtocol has three votes which support version
  488. // 1, and one vote that supports version 2
  489. let mut all_count: HashMap<String, HashMap<u32, usize>> = HashMap::new();
  490. // parse and collect all of the protos and their versions and collect them
  491. for vote in list_of_proto_strings {
  492. let this_vote: HashMap<String, HashSet<u32>> =
  493. match parse_protocols_from_string_with_no_validation(&vote) {
  494. Ok(result) => result,
  495. Err(_) => continue,
  496. };
  497. for (protocol, versions) in this_vote {
  498. let supported_vers: &mut HashMap<u32, usize> =
  499. all_count.entry(protocol).or_insert(HashMap::new());
  500. for version in versions {
  501. let counter: &mut usize =
  502. supported_vers.entry(version).or_insert(0);
  503. *counter += 1;
  504. }
  505. }
  506. }
  507. let mut final_output: HashMap<String, String> =
  508. HashMap::with_capacity(SUPPORTED_PROTOCOLS.len());
  509. // Go through and remove verstions that are less than the threshold
  510. for (protocol, versions) in all_count {
  511. let mut meets_threshold = HashSet::new();
  512. for (version, count) in versions {
  513. if count >= threshold as usize {
  514. meets_threshold.insert(version);
  515. }
  516. }
  517. // For each protocol, compress its version list into the expected
  518. // protocol version string format
  519. let contracted = contract_protocol_list(&meets_threshold);
  520. if !contracted.is_empty() {
  521. final_output.insert(protocol, contracted);
  522. }
  523. }
  524. write_vote_to_string(&final_output)
  525. }
  526. /// Return a String comprised of protocol entries in alphabetical order
  527. ///
  528. /// # Inputs
  529. ///
  530. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  531. /// The keys are the protocol names while values are a string representation of
  532. /// the supported versions.
  533. ///
  534. /// # Returns
  535. ///
  536. /// A `String` whose value is series of pairs, comprising of the protocol name
  537. /// and versions that it supports. The string takes the following format:
  538. ///
  539. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  540. ///
  541. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  542. /// entry format.
  543. ///
  544. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  545. let mut keys: Vec<&String> = vote.keys().collect();
  546. keys.sort();
  547. let mut output = Vec::new();
  548. for key in keys {
  549. // TODO error in indexing here?
  550. output.push(format!("{}={}", key, vote[key]));
  551. }
  552. output.join(" ")
  553. }
  554. /// Returns a boolean indicating whether the given protocol and version is
  555. /// supported in any of the existing Tor protocols
  556. ///
  557. /// # Examples
  558. /// ```
  559. /// use protover::*;
  560. ///
  561. /// let is_supported = is_supported_here(Proto::Link, 5);
  562. /// assert_eq!(false, is_supported);
  563. ///
  564. /// let is_supported = is_supported_here(Proto::Link, 1);
  565. /// assert_eq!(true, is_supported);
  566. /// ```
  567. pub fn is_supported_here(proto: Proto, vers: u32) -> bool {
  568. let currently_supported: HashMap<Proto, HashSet<u32>>;
  569. match tor_supported() {
  570. Ok(result) => currently_supported = result,
  571. Err(_) => return false,
  572. }
  573. let supported_versions = match currently_supported.get(&proto) {
  574. Some(n) => n,
  575. None => return false,
  576. };
  577. supported_versions.contains(&vers)
  578. }
  579. /// Older versions of Tor cannot infer their own subprotocols
  580. /// Used to determine which subprotocols are supported by older Tor versions.
  581. ///
  582. /// # Inputs
  583. ///
  584. /// * `version`, a string comprised of "[0-9,-]"
  585. ///
  586. /// # Returns
  587. ///
  588. /// A `String` whose value is series of pairs, comprising of the protocol name
  589. /// and versions that it supports. The string takes the following format:
  590. ///
  591. /// "HSDir=1-1 LinkAuth=1"
  592. ///
  593. /// This function returns the protocols that are supported by the version input,
  594. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  595. ///
  596. pub fn compute_for_old_tor(version: &str) -> String {
  597. if c_tor_version_as_new_as(
  598. version,
  599. FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS,
  600. )
  601. {
  602. return String::new();
  603. }
  604. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  605. let ret = "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  606. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2";
  607. return String::from(ret);
  608. }
  609. if c_tor_version_as_new_as(version, "0.2.7.5") {
  610. let ret = "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  611. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2";
  612. return String::from(ret);
  613. }
  614. if c_tor_version_as_new_as(version, "0.2.4.19") {
  615. let ret = "Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  616. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2";
  617. return String::from(ret);
  618. }
  619. String::new()
  620. }
  621. #[cfg(test)]
  622. mod test {
  623. #[test]
  624. fn test_get_versions() {
  625. use std::collections::HashSet;
  626. use super::get_versions;
  627. assert_eq!(Err("version string is empty"), get_versions(""));
  628. assert_eq!(Err("invalid protocol entry"), get_versions("a,b"));
  629. assert_eq!(Err("invalid protocol entry"), get_versions("1,!"));
  630. {
  631. let mut versions: HashSet<u32> = HashSet::new();
  632. versions.insert(1);
  633. assert_eq!(Ok(versions), get_versions("1"));
  634. }
  635. {
  636. let mut versions: HashSet<u32> = HashSet::new();
  637. versions.insert(1);
  638. versions.insert(2);
  639. assert_eq!(Ok(versions), get_versions("1,2"));
  640. }
  641. {
  642. let mut versions: HashSet<u32> = HashSet::new();
  643. versions.insert(1);
  644. versions.insert(2);
  645. versions.insert(3);
  646. assert_eq!(Ok(versions), get_versions("1-3"));
  647. }
  648. {
  649. let mut versions: HashSet<u32> = HashSet::new();
  650. versions.insert(1);
  651. versions.insert(2);
  652. versions.insert(5);
  653. assert_eq!(Ok(versions), get_versions("1-2,5"));
  654. }
  655. {
  656. let mut versions: HashSet<u32> = HashSet::new();
  657. versions.insert(1);
  658. versions.insert(3);
  659. versions.insert(4);
  660. versions.insert(5);
  661. assert_eq!(Ok(versions), get_versions("1,3-5"));
  662. }
  663. }
  664. #[test]
  665. fn test_contains_only_supported_protocols() {
  666. use super::contains_only_supported_protocols;
  667. assert_eq!(false, contains_only_supported_protocols(""));
  668. assert_eq!(false, contains_only_supported_protocols("Cons="));
  669. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  670. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  671. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  672. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  673. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  674. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  675. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  676. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  677. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  678. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  679. }
  680. #[test]
  681. fn test_find_range() {
  682. use super::find_range;
  683. assert_eq!((false, 0), find_range(&vec![]));
  684. assert_eq!((false, 1), find_range(&vec![1]));
  685. assert_eq!((true, 2), find_range(&vec![1, 2]));
  686. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  687. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  688. }
  689. #[test]
  690. fn test_expand_version_range() {
  691. use super::expand_version_range;
  692. assert_eq!(Err("version string empty"), expand_version_range(""));
  693. assert_eq!(Ok(vec![1, 2]), expand_version_range("1-2"));
  694. assert_eq!(Ok(vec![1, 2, 3, 4]), expand_version_range("1-4"));
  695. assert_eq!(
  696. Err("cannot parse protocol range lower bound"),
  697. expand_version_range("a")
  698. );
  699. assert_eq!(
  700. Err("cannot parse protocol range upper bound"),
  701. expand_version_range("1-a")
  702. );
  703. }
  704. #[test]
  705. fn test_contract_protocol_list() {
  706. use std::collections::HashSet;
  707. use super::contract_protocol_list;
  708. {
  709. let mut versions = HashSet::<u32>::new();
  710. assert_eq!(String::from(""), contract_protocol_list(&versions));
  711. versions.insert(1);
  712. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  713. versions.insert(2);
  714. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  715. }
  716. {
  717. let mut versions = HashSet::<u32>::new();
  718. versions.insert(1);
  719. versions.insert(3);
  720. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  721. }
  722. {
  723. let mut versions = HashSet::<u32>::new();
  724. versions.insert(1);
  725. versions.insert(2);
  726. versions.insert(3);
  727. versions.insert(4);
  728. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  729. }
  730. {
  731. let mut versions = HashSet::<u32>::new();
  732. versions.insert(1);
  733. versions.insert(3);
  734. versions.insert(5);
  735. versions.insert(6);
  736. versions.insert(7);
  737. assert_eq!(
  738. String::from("1,3,5-7"),
  739. contract_protocol_list(&versions)
  740. );
  741. }
  742. {
  743. let mut versions = HashSet::<u32>::new();
  744. versions.insert(1);
  745. versions.insert(2);
  746. versions.insert(3);
  747. versions.insert(500);
  748. assert_eq!(
  749. String::from("1-3,500"),
  750. contract_protocol_list(&versions)
  751. );
  752. }
  753. }
  754. }