protover.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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_clone = supported_set.clone();
  384. let mut supported: Vec<u32> = supported_clone.drain().collect();
  385. supported.sort();
  386. let mut final_output: Vec<String> = Vec::new();
  387. while supported.len() != 0 {
  388. let (has_range, end) = find_range(&supported);
  389. let current = supported.remove(0);
  390. if has_range {
  391. final_output.push(format!(
  392. "{}-{}",
  393. current.to_string(),
  394. &end.to_string(),
  395. ));
  396. supported.retain(|&x| x > end);
  397. } else {
  398. final_output.push(current.to_string());
  399. }
  400. }
  401. final_output.join(",")
  402. }
  403. /// Parses a protocol list without validating the protocol names
  404. ///
  405. /// # Inputs
  406. ///
  407. /// * `protocol_string`, a string comprised of keys and values, both which are
  408. /// strings. The keys are the protocol names while values are a string
  409. /// representation of the supported versions.
  410. ///
  411. /// The input is _not_ expected to be a subset of the Proto types
  412. ///
  413. /// # Returns
  414. ///
  415. /// A `Result` whose `Ok` value is a `HashSet<u32>` holding all of the unique
  416. /// version numbers.
  417. ///
  418. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  419. /// of the error.
  420. ///
  421. /// # Errors
  422. ///
  423. /// This function will error if:
  424. ///
  425. /// * The protocol string does not follow the "protocol_name=version_list"
  426. /// expected format
  427. /// * If the version string is malformed. See `get_versions`.
  428. ///
  429. fn parse_protocols_from_string_with_no_validation<'a>(
  430. protocol_string: &'a str,
  431. ) -> Result<HashMap<String, HashSet<u32>>, &'static str> {
  432. let protocols = &protocol_string.split(" ").collect::<Vec<&'a str>>()[..];
  433. let mut parsed: HashMap<String, HashSet<u32>> = HashMap::new();
  434. for subproto in protocols {
  435. let mut parts = subproto.splitn(2, "=");
  436. let name = match parts.next() {
  437. Some(n) => n,
  438. None => return Err("invalid protover entry"),
  439. };
  440. let vers = match parts.next() {
  441. Some(n) => n,
  442. None => return Err("invalid protover entry"),
  443. };
  444. let versions = get_versions(vers)?;
  445. parsed.insert(String::from(name), versions);
  446. }
  447. Ok(parsed)
  448. }
  449. /// Protocol voting implementation.
  450. ///
  451. /// Given a list of strings describing protocol versions, return a new
  452. /// string encoding all of the protocols that are listed by at
  453. /// least threshold of the inputs.
  454. ///
  455. /// The string is sorted according to the following conventions:
  456. /// - Protocols names are alphabetized
  457. /// - Protocols are in order low to high
  458. /// - Individual and ranges are listed together. For example,
  459. /// "3, 5-10,13"
  460. /// - All entries are unique
  461. ///
  462. /// # Examples
  463. /// ```
  464. /// use protover::compute_vote;
  465. ///
  466. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  467. /// let vote = compute_vote(protos, 2);
  468. /// assert_eq!("Link=3", vote)
  469. /// ```
  470. pub fn compute_vote(
  471. list_of_proto_strings: Vec<String>,
  472. threshold: i32,
  473. ) -> String {
  474. let empty = String::from("");
  475. if list_of_proto_strings.is_empty() {
  476. return empty;
  477. }
  478. // all_count is a structure to represent the count of the number of
  479. // supported versions for a specific protocol. For example, in JSON format:
  480. // {
  481. // "FirstSupportedProtocol": {
  482. // "1": "3",
  483. // "2": "1"
  484. // }
  485. // }
  486. // means that FirstSupportedProtocol has three votes which support version
  487. // 1, and one vote that supports version 2
  488. let mut all_count: HashMap<String, HashMap<u32, usize>> = HashMap::new();
  489. // parse and collect all of the protos and their versions and collect them
  490. for vote in list_of_proto_strings {
  491. let this_vote: HashMap<String, HashSet<u32>> =
  492. match parse_protocols_from_string_with_no_validation(&vote) {
  493. Ok(result) => result,
  494. Err(_) => continue,
  495. };
  496. for (protocol, versions) in this_vote {
  497. let supported_vers: &mut HashMap<u32, usize> =
  498. all_count.entry(protocol).or_insert(HashMap::new());
  499. for version in versions {
  500. let counter: &mut usize =
  501. supported_vers.entry(version).or_insert(0);
  502. *counter += 1;
  503. }
  504. }
  505. }
  506. let mut final_output: HashMap<String, String> =
  507. HashMap::with_capacity(SUPPORTED_PROTOCOLS.len());
  508. // Go through and remove verstions that are less than the threshold
  509. for (protocol, versions) in all_count {
  510. let mut meets_threshold = HashSet::new();
  511. for (version, count) in versions {
  512. if count >= threshold as usize {
  513. meets_threshold.insert(version);
  514. }
  515. }
  516. // For each protocol, compress its version list into the expected
  517. // protocol version string format
  518. let contracted = contract_protocol_list(&meets_threshold);
  519. if !contracted.is_empty() {
  520. final_output.insert(protocol, contracted);
  521. }
  522. }
  523. write_vote_to_string(&final_output)
  524. }
  525. /// Return a String comprised of protocol entries in alphabetical order
  526. ///
  527. /// # Inputs
  528. ///
  529. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  530. /// The keys are the protocol names while values are a string representation of
  531. /// the supported versions.
  532. ///
  533. /// # Returns
  534. ///
  535. /// A `String` whose value is series of pairs, comprising of the protocol name
  536. /// and versions that it supports. The string takes the following format:
  537. ///
  538. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  539. ///
  540. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  541. /// entry format.
  542. ///
  543. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  544. let mut keys: Vec<&String> = vote.keys().collect();
  545. keys.sort();
  546. let mut output = Vec::new();
  547. for key in keys {
  548. // TODO error in indexing here?
  549. output.push(format!("{}={}", key, vote[key]));
  550. }
  551. output.join(" ")
  552. }
  553. /// Returns a boolean indicating whether the given protocol and version is
  554. /// supported in any of the existing Tor protocols
  555. ///
  556. /// # Examples
  557. /// ```
  558. /// use protover::*;
  559. ///
  560. /// let is_supported = is_supported_here(Proto::Link, 5);
  561. /// assert_eq!(false, is_supported);
  562. ///
  563. /// let is_supported = is_supported_here(Proto::Link, 1);
  564. /// assert_eq!(true, is_supported);
  565. /// ```
  566. pub fn is_supported_here(proto: Proto, vers: u32) -> bool {
  567. let currently_supported: HashMap<Proto, HashSet<u32>>;
  568. match tor_supported() {
  569. Ok(result) => currently_supported = result,
  570. Err(_) => return false,
  571. }
  572. let supported_versions = match currently_supported.get(&proto) {
  573. Some(n) => n,
  574. None => return false,
  575. };
  576. supported_versions.contains(&vers)
  577. }
  578. /// Older versions of Tor cannot infer their own subprotocols
  579. /// Used to determine which subprotocols are supported by older Tor versions.
  580. ///
  581. /// # Inputs
  582. ///
  583. /// * `version`, a string comprised of "[0-9,-]"
  584. ///
  585. /// # Returns
  586. ///
  587. /// A `String` whose value is series of pairs, comprising of the protocol name
  588. /// and versions that it supports. The string takes the following format:
  589. ///
  590. /// "HSDir=1-1 LinkAuth=1"
  591. ///
  592. /// This function returns the protocols that are supported by the version input,
  593. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  594. ///
  595. pub fn compute_for_old_tor(version: &str) -> String {
  596. if c_tor_version_as_new_as(
  597. version,
  598. FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS,
  599. )
  600. {
  601. return String::new();
  602. }
  603. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  604. let ret = "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  605. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2";
  606. return String::from(ret);
  607. }
  608. if c_tor_version_as_new_as(version, "0.2.7.5") {
  609. let ret = "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  610. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2";
  611. return String::from(ret);
  612. }
  613. if c_tor_version_as_new_as(version, "0.2.4.19") {
  614. let ret = "Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  615. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2";
  616. return String::from(ret);
  617. }
  618. String::new()
  619. }
  620. #[cfg(test)]
  621. mod test {
  622. #[test]
  623. fn test_get_versions() {
  624. use std::collections::HashSet;
  625. use super::get_versions;
  626. assert_eq!(Err("version string is empty"), get_versions(""));
  627. assert_eq!(Err("invalid protocol entry"), get_versions("a,b"));
  628. assert_eq!(Err("invalid protocol entry"), get_versions("1,!"));
  629. {
  630. let mut versions: HashSet<u32> = HashSet::new();
  631. versions.insert(1);
  632. assert_eq!(Ok(versions), get_versions("1"));
  633. }
  634. {
  635. let mut versions: HashSet<u32> = HashSet::new();
  636. versions.insert(1);
  637. versions.insert(2);
  638. assert_eq!(Ok(versions), get_versions("1,2"));
  639. }
  640. {
  641. let mut versions: HashSet<u32> = HashSet::new();
  642. versions.insert(1);
  643. versions.insert(2);
  644. versions.insert(3);
  645. assert_eq!(Ok(versions), get_versions("1-3"));
  646. }
  647. {
  648. let mut versions: HashSet<u32> = HashSet::new();
  649. versions.insert(1);
  650. versions.insert(2);
  651. versions.insert(5);
  652. assert_eq!(Ok(versions), get_versions("1-2,5"));
  653. }
  654. {
  655. let mut versions: HashSet<u32> = HashSet::new();
  656. versions.insert(1);
  657. versions.insert(3);
  658. versions.insert(4);
  659. versions.insert(5);
  660. assert_eq!(Ok(versions), get_versions("1,3-5"));
  661. }
  662. }
  663. #[test]
  664. fn test_contains_only_supported_protocols() {
  665. use super::contains_only_supported_protocols;
  666. assert_eq!(false, contains_only_supported_protocols(""));
  667. assert_eq!(false, contains_only_supported_protocols("Cons="));
  668. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  669. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  670. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  671. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  672. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  673. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  674. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  675. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  676. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  677. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  678. }
  679. #[test]
  680. fn test_find_range() {
  681. use super::find_range;
  682. assert_eq!((false, 0), find_range(&vec![]));
  683. assert_eq!((false, 1), find_range(&vec![1]));
  684. assert_eq!((true, 2), find_range(&vec![1, 2]));
  685. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  686. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  687. }
  688. #[test]
  689. fn test_expand_version_range() {
  690. use super::expand_version_range;
  691. assert_eq!(Err("version string empty"), expand_version_range(""));
  692. assert_eq!(Ok(vec![1, 2]), expand_version_range("1-2"));
  693. assert_eq!(Ok(vec![1, 2, 3, 4]), expand_version_range("1-4"));
  694. assert_eq!(
  695. Err("cannot parse protocol range lower bound"),
  696. expand_version_range("a")
  697. );
  698. assert_eq!(
  699. Err("cannot parse protocol range upper bound"),
  700. expand_version_range("1-a")
  701. );
  702. }
  703. #[test]
  704. fn test_contract_protocol_list() {
  705. use std::collections::HashSet;
  706. use super::contract_protocol_list;
  707. {
  708. let mut versions = HashSet::<u32>::new();
  709. assert_eq!(String::from(""), contract_protocol_list(&versions));
  710. versions.insert(1);
  711. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  712. versions.insert(2);
  713. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  714. }
  715. {
  716. let mut versions = HashSet::<u32>::new();
  717. versions.insert(1);
  718. versions.insert(3);
  719. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  720. }
  721. {
  722. let mut versions = HashSet::<u32>::new();
  723. versions.insert(1);
  724. versions.insert(2);
  725. versions.insert(3);
  726. versions.insert(4);
  727. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  728. }
  729. {
  730. let mut versions = HashSet::<u32>::new();
  731. versions.insert(1);
  732. versions.insert(3);
  733. versions.insert(5);
  734. versions.insert(6);
  735. versions.insert(7);
  736. assert_eq!(
  737. String::from("1,3,5-7"),
  738. contract_protocol_list(&versions)
  739. );
  740. }
  741. {
  742. let mut versions = HashSet::<u32>::new();
  743. versions.insert(1);
  744. versions.insert(2);
  745. versions.insert(3);
  746. versions.insert(500);
  747. assert_eq!(
  748. String::from("1-3,500"),
  749. contract_protocol_list(&versions)
  750. );
  751. }
  752. }
  753. }