protover.rs 25 KB

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