protover.rs 28 KB

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