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