protover.rs 25 KB

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