protover.rs 27 KB

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