protover.rs 25 KB

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