protover.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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::fmt;
  7. use std::collections::{HashMap, HashSet};
  8. use std::ops::Range;
  9. use std::string::String;
  10. use tor_util::strings::NUL_BYTE;
  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: usize = (1<<16);
  22. /// Currently supported protocols and their versions, as a byte-slice.
  23. ///
  24. /// # Warning
  25. ///
  26. /// This byte-slice ends in a NUL byte. This is so that we can directly convert
  27. /// it to an `&'static CStr` in the FFI code, in order to hand the static string
  28. /// to C in a way that is compatible with C static strings.
  29. ///
  30. /// Rust code which wishes to accesses this string should use
  31. /// `protover::get_supported_protocols()` instead.
  32. ///
  33. /// C_RUST_COUPLED: src/or/protover.c `protover_get_supported_protocols`
  34. pub(crate) const SUPPORTED_PROTOCOLS: &'static [u8] =
  35. b"Cons=1-2 \
  36. Desc=1-2 \
  37. DirCache=1-2 \
  38. HSDir=1-2 \
  39. HSIntro=3-4 \
  40. HSRend=1-2 \
  41. Link=1-5 \
  42. LinkAuth=1,3 \
  43. Microdesc=1-2 \
  44. Relay=1-2\0";
  45. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  46. ///
  47. /// C_RUST_COUPLED: src/or/protover.h `protocol_type_t`
  48. #[derive(Hash, Eq, PartialEq, Debug)]
  49. pub enum Proto {
  50. Cons,
  51. Desc,
  52. DirCache,
  53. HSDir,
  54. HSIntro,
  55. HSRend,
  56. Link,
  57. LinkAuth,
  58. Microdesc,
  59. Relay,
  60. }
  61. impl fmt::Display for Proto {
  62. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  63. write!(f, "{:?}", self)
  64. }
  65. }
  66. /// Translates a string representation of a protocol into a Proto type.
  67. /// Error if the string is an unrecognized protocol name.
  68. ///
  69. /// C_RUST_COUPLED: src/or/protover.c `PROTOCOL_NAMES`
  70. impl FromStr for Proto {
  71. type Err = &'static str;
  72. fn from_str(s: &str) -> Result<Self, Self::Err> {
  73. match s {
  74. "Cons" => Ok(Proto::Cons),
  75. "Desc" => Ok(Proto::Desc),
  76. "DirCache" => Ok(Proto::DirCache),
  77. "HSDir" => Ok(Proto::HSDir),
  78. "HSIntro" => Ok(Proto::HSIntro),
  79. "HSRend" => Ok(Proto::HSRend),
  80. "Link" => Ok(Proto::Link),
  81. "LinkAuth" => Ok(Proto::LinkAuth),
  82. "Microdesc" => Ok(Proto::Microdesc),
  83. "Relay" => Ok(Proto::Relay),
  84. _ => Err("Not a valid protocol type"),
  85. }
  86. }
  87. }
  88. /// Get the string representation of current supported protocols
  89. ///
  90. /// # Returns
  91. ///
  92. /// A `String` whose value is the existing protocols supported by tor.
  93. /// Returned data is in the format as follows:
  94. ///
  95. /// "HSDir=1-1 LinkAuth=1"
  96. ///
  97. pub fn get_supported_protocols() -> &'static str {
  98. // The `len() - 1` is to remove the NUL byte.
  99. // The `unwrap` is safe becauase we SUPPORTED_PROTOCOLS is under
  100. // our control.
  101. str::from_utf8(&SUPPORTED_PROTOCOLS[..SUPPORTED_PROTOCOLS.len() - 1])
  102. .unwrap_or("")
  103. }
  104. pub struct SupportedProtocols(HashMap<Proto, Versions>);
  105. impl SupportedProtocols {
  106. pub fn from_proto_entries<I, S>(protocol_strs: I) -> Result<Self, &'static str>
  107. where
  108. I: Iterator<Item = S>,
  109. S: AsRef<str>,
  110. {
  111. let mut parsed = HashMap::new();
  112. for subproto in protocol_strs {
  113. let (name, version) = get_proto_and_vers(subproto.as_ref())?;
  114. parsed.insert(name, version);
  115. }
  116. Ok(SupportedProtocols(parsed))
  117. }
  118. /// Translates a string representation of a protocol list to a
  119. /// SupportedProtocols instance.
  120. ///
  121. /// # Examples
  122. ///
  123. /// ```
  124. /// use protover::SupportedProtocols;
  125. ///
  126. /// let supported_protocols = SupportedProtocols::from_proto_entries_string(
  127. /// "HSDir=1-2 HSIntro=3-4"
  128. /// );
  129. /// ```
  130. pub fn from_proto_entries_string(
  131. proto_entries: &str,
  132. ) -> Result<Self, &'static str> {
  133. Self::from_proto_entries(proto_entries.split(" "))
  134. }
  135. /// Translate the supported tor versions from a string into a
  136. /// HashMap, which is useful when looking up a specific
  137. /// subprotocol.
  138. ///
  139. fn tor_supported() -> Result<Self, &'static str> {
  140. Self::from_proto_entries_string(get_supported_protocols())
  141. }
  142. }
  143. type Version = u32;
  144. /// Set of versions for a protocol.
  145. #[derive(Debug, PartialEq, Eq)]
  146. pub struct Versions(HashSet<Version>);
  147. impl Versions {
  148. /// Get the unique version numbers supported by a subprotocol.
  149. ///
  150. /// # Inputs
  151. ///
  152. /// * `version_string`, a string comprised of "[0-9,-]"
  153. ///
  154. /// # Returns
  155. ///
  156. /// A `Result` whose `Ok` value is a `HashSet<u32>` holding all of the unique
  157. /// version numbers. If there were ranges in the `version_string`, then these
  158. /// are expanded, i.e. `"1-3"` would expand to `HashSet<u32>::new([1, 2, 3])`.
  159. /// The returned HashSet is *unordered*.
  160. ///
  161. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  162. /// of the error.
  163. ///
  164. /// # Errors
  165. ///
  166. /// This function will error if:
  167. ///
  168. /// * the `version_string` is empty or contains an equals (`"="`) sign,
  169. /// * the expansion of a version range produces an error (see
  170. /// `expand_version_range`),
  171. /// * any single version number is not parseable as an `u32` in radix 10, or
  172. /// * there are greater than 2^16 version numbers to expand.
  173. ///
  174. fn from_version_string(
  175. version_string: &str,
  176. ) -> Result<Self, &'static str> {
  177. if version_string.is_empty() {
  178. return Err("version string is empty");
  179. }
  180. let mut versions = HashSet::<Version>::new();
  181. for piece in version_string.split(",") {
  182. if piece.contains("-") {
  183. for p in expand_version_range(piece)? {
  184. versions.insert(p);
  185. }
  186. } else {
  187. versions.insert(u32::from_str(piece).or(
  188. Err("invalid protocol entry"),
  189. )?);
  190. }
  191. if versions.len() > MAX_PROTOCOLS_TO_EXPAND {
  192. return Err("Too many versions to expand");
  193. }
  194. }
  195. Ok(Versions(versions))
  196. }
  197. }
  198. /// Parse the subprotocol type and its version numbers.
  199. ///
  200. /// # Inputs
  201. ///
  202. /// * A `protocol_entry` string, comprised of a keyword, an "=" sign, and one
  203. /// or more version numbers.
  204. ///
  205. /// # Returns
  206. ///
  207. /// A `Result` whose `Ok` value is a tuple of `(Proto, HashSet<u32>)`, where the
  208. /// first element is the subprotocol type (see `protover::Proto`) and the last
  209. /// element is a(n unordered) set of unique version numbers which are supported.
  210. /// Otherwise, the `Err` value of this `Result` is a description of the error
  211. ///
  212. fn get_proto_and_vers<'a>(
  213. protocol_entry: &'a str,
  214. ) -> Result<(Proto, Versions), &'static str> {
  215. let mut parts = protocol_entry.splitn(2, "=");
  216. let proto = match parts.next() {
  217. Some(n) => n,
  218. None => return Err("invalid protover entry"),
  219. };
  220. let vers = match parts.next() {
  221. Some(n) => n,
  222. None => return Err("invalid protover entry"),
  223. };
  224. let versions = Versions::from_version_string(vers)?;
  225. let proto_name = proto.parse()?;
  226. Ok((proto_name, versions))
  227. }
  228. /// Parses a single subprotocol entry string into subprotocol and version
  229. /// parts, and then checks whether any of those versions are unsupported.
  230. /// Helper for protover::all_supported
  231. ///
  232. /// # Inputs
  233. ///
  234. /// Accepted data is in the string format as follows:
  235. ///
  236. /// "HSDir=1-1"
  237. ///
  238. /// # Returns
  239. ///
  240. /// Returns `true` if the protocol entry is well-formatted and only contains
  241. /// versions that are also supported in tor. Otherwise, returns false
  242. ///
  243. fn contains_only_supported_protocols(proto_entry: &str) -> bool {
  244. let (name, mut vers) = match get_proto_and_vers(proto_entry) {
  245. Ok(n) => n,
  246. Err(_) => return false,
  247. };
  248. let currently_supported = match SupportedProtocols::tor_supported() {
  249. Ok(n) => n.0,
  250. Err(_) => return false,
  251. };
  252. let supported_versions = match currently_supported.get(&name) {
  253. Some(n) => n,
  254. None => return false,
  255. };
  256. vers.0.retain(|x| !supported_versions.0.contains(x));
  257. vers.0.is_empty()
  258. }
  259. /// Determine if we support every protocol a client supports, and if not,
  260. /// determine which protocols we do not have support for.
  261. ///
  262. /// # Inputs
  263. ///
  264. /// Accepted data is in the string format as follows:
  265. ///
  266. /// "HSDir=1-1 LinkAuth=1-2"
  267. ///
  268. /// # Returns
  269. ///
  270. /// Return `true` if every protocol version is one that we support.
  271. /// Otherwise, return `false`.
  272. /// Optionally, return parameters which the client supports but which we do not
  273. ///
  274. /// # Examples
  275. /// ```
  276. /// use protover::all_supported;
  277. ///
  278. /// let (is_supported, unsupported) = all_supported("Link=1");
  279. /// assert_eq!(true, is_supported);
  280. ///
  281. /// let (is_supported, unsupported) = all_supported("Link=5-6");
  282. /// assert_eq!(false, is_supported);
  283. /// assert_eq!("Link=5-6", unsupported);
  284. ///
  285. pub fn all_supported(protocols: &str) -> (bool, String) {
  286. let unsupported = protocols
  287. .split_whitespace()
  288. .filter(|v| !contains_only_supported_protocols(v))
  289. .collect::<Vec<&str>>();
  290. (unsupported.is_empty(), unsupported.join(" "))
  291. }
  292. /// Return true iff the provided protocol list includes support for the
  293. /// indicated protocol and version.
  294. /// Otherwise, return false
  295. ///
  296. /// # Inputs
  297. ///
  298. /// * `list`, a string representation of a list of protocol entries.
  299. /// * `proto`, a `Proto` to test support for
  300. /// * `vers`, a `Version` version which we will go on to determine whether the
  301. /// specified protocol supports.
  302. ///
  303. /// # Examples
  304. /// ```
  305. /// use protover::*;
  306. ///
  307. /// let is_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  308. /// Proto::Cons,1);
  309. /// assert_eq!(true, is_supported);
  310. ///
  311. /// let is_not_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  312. /// Proto::Cons,5);
  313. /// assert_eq!(false, is_not_supported)
  314. /// ```
  315. pub fn protover_string_supports_protocol(
  316. list: &str,
  317. proto: Proto,
  318. vers: Version,
  319. ) -> bool {
  320. let supported = match SupportedProtocols::from_proto_entries_string(list) {
  321. Ok(result) => result.0,
  322. Err(_) => return false,
  323. };
  324. let supported_versions = match supported.get(&proto) {
  325. Some(n) => n,
  326. None => return false,
  327. };
  328. supported_versions.0.contains(&vers)
  329. }
  330. /// As protover_string_supports_protocol(), but also returns True if
  331. /// any later version of the protocol is supported.
  332. ///
  333. /// # Examples
  334. /// ```
  335. /// use protover::*;
  336. ///
  337. /// let is_supported = protover_string_supports_protocol_or_later(
  338. /// "Link=3-4 Cons=5", Proto::Cons, 5);
  339. ///
  340. /// assert_eq!(true, is_supported);
  341. ///
  342. /// let is_supported = protover_string_supports_protocol_or_later(
  343. /// "Link=3-4 Cons=5", Proto::Cons, 4);
  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, 6);
  349. ///
  350. /// assert_eq!(false, is_supported);
  351. /// ```
  352. pub fn protover_string_supports_protocol_or_later(
  353. list: &str,
  354. proto: Proto,
  355. vers: u32,
  356. ) -> bool {
  357. let supported = match SupportedProtocols::from_proto_entries_string(list) {
  358. Ok(result) => result.0,
  359. Err(_) => return false,
  360. };
  361. let supported_versions = match supported.get(&proto) {
  362. Some(n) => n,
  363. None => return false,
  364. };
  365. supported_versions.0.iter().any(|v| v >= &vers)
  366. }
  367. /// Fully expand a version range. For example, 1-3 expands to 1,2,3
  368. /// Helper for Versions::from_version_string
  369. ///
  370. /// # Inputs
  371. ///
  372. /// `range`, a string comprised of "[0-9,-]"
  373. ///
  374. /// # Returns
  375. ///
  376. /// A `Result` whose `Ok` value a vector of unsigned integers representing the
  377. /// expanded range of supported versions by a single protocol.
  378. /// Otherwise, the `Err` value of this `Result` is a description of the error
  379. ///
  380. /// # Errors
  381. ///
  382. /// This function will error if:
  383. ///
  384. /// * the specified range is empty
  385. /// * the version range does not contain both a valid lower and upper bound.
  386. ///
  387. fn expand_version_range(range: &str) -> Result<Range<u32>, &'static str> {
  388. if range.is_empty() {
  389. return Err("version string empty");
  390. }
  391. let mut parts = range.split("-");
  392. let lower_string = parts.next().ok_or(
  393. "cannot parse protocol range lower bound",
  394. )?;
  395. let lower = u32::from_str_radix(lower_string, 10).or(Err(
  396. "cannot parse protocol range lower bound",
  397. ))?;
  398. let higher_string = parts.next().ok_or(
  399. "cannot parse protocol range upper bound",
  400. )?;
  401. let higher = u32::from_str_radix(higher_string, 10).or(Err(
  402. "cannot parse protocol range upper bound",
  403. ))?;
  404. // We can use inclusive range syntax when it becomes stable.
  405. let result = lower..higher + 1;
  406. if result.len() > MAX_PROTOCOLS_TO_EXPAND {
  407. Err("Too many protocols in expanded range")
  408. } else {
  409. Ok(result)
  410. }
  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 [u8]` 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 [u8] {
  676. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  677. return NUL_BYTE;
  678. }
  679. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  680. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  681. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  682. }
  683. if c_tor_version_as_new_as(version, "0.2.7.5") {
  684. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  685. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  686. }
  687. if c_tor_version_as_new_as(version, "0.2.4.19") {
  688. return b"Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  689. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2\0";
  690. }
  691. NUL_BYTE
  692. }
  693. #[cfg(test)]
  694. mod test {
  695. use super::Version;
  696. #[test]
  697. fn test_versions_from_version_string() {
  698. use std::collections::HashSet;
  699. use super::Versions;
  700. assert_eq!(Err("version string is empty"), Versions::from_version_string(""));
  701. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  702. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  703. {
  704. let mut versions: HashSet<Version> = HashSet::new();
  705. versions.insert(1);
  706. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  707. }
  708. {
  709. let mut versions: HashSet<Version> = HashSet::new();
  710. versions.insert(1);
  711. versions.insert(2);
  712. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  713. }
  714. {
  715. let mut versions: HashSet<Version> = HashSet::new();
  716. versions.insert(1);
  717. versions.insert(2);
  718. versions.insert(3);
  719. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  720. }
  721. {
  722. let mut versions: HashSet<Version> = HashSet::new();
  723. versions.insert(1);
  724. versions.insert(2);
  725. versions.insert(5);
  726. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  727. }
  728. {
  729. let mut versions: HashSet<Version> = HashSet::new();
  730. versions.insert(1);
  731. versions.insert(3);
  732. versions.insert(4);
  733. versions.insert(5);
  734. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  735. }
  736. }
  737. #[test]
  738. fn test_contains_only_supported_protocols() {
  739. use super::contains_only_supported_protocols;
  740. assert_eq!(false, contains_only_supported_protocols(""));
  741. assert_eq!(false, contains_only_supported_protocols("Cons="));
  742. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  743. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  744. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  745. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  746. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  747. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  748. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  749. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  750. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  751. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  752. }
  753. #[test]
  754. fn test_find_range() {
  755. use super::find_range;
  756. assert_eq!((false, 0), find_range(&vec![]));
  757. assert_eq!((false, 1), find_range(&vec![1]));
  758. assert_eq!((true, 2), find_range(&vec![1, 2]));
  759. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  760. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  761. }
  762. #[test]
  763. fn test_expand_version_range() {
  764. use super::expand_version_range;
  765. assert_eq!(Err("version string empty"), expand_version_range(""));
  766. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  767. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  768. assert_eq!(
  769. Err("cannot parse protocol range lower bound"),
  770. expand_version_range("a")
  771. );
  772. assert_eq!(
  773. Err("cannot parse protocol range upper bound"),
  774. expand_version_range("1-a")
  775. );
  776. assert_eq!(Ok(1000..66536), expand_version_range("1000-66535"));
  777. assert_eq!(Err("Too many protocols in expanded range"),
  778. expand_version_range("1000-66536"));
  779. }
  780. #[test]
  781. fn test_contract_protocol_list() {
  782. use std::collections::HashSet;
  783. use super::contract_protocol_list;
  784. {
  785. let mut versions = HashSet::<Version>::new();
  786. assert_eq!(String::from(""), contract_protocol_list(&versions));
  787. versions.insert(1);
  788. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  789. versions.insert(2);
  790. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  791. }
  792. {
  793. let mut versions = HashSet::<Version>::new();
  794. versions.insert(1);
  795. versions.insert(3);
  796. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  797. }
  798. {
  799. let mut versions = HashSet::<Version>::new();
  800. versions.insert(1);
  801. versions.insert(2);
  802. versions.insert(3);
  803. versions.insert(4);
  804. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  805. }
  806. {
  807. let mut versions = HashSet::<Version>::new();
  808. versions.insert(1);
  809. versions.insert(3);
  810. versions.insert(5);
  811. versions.insert(6);
  812. versions.insert(7);
  813. assert_eq!(
  814. String::from("1,3,5-7"),
  815. contract_protocol_list(&versions)
  816. );
  817. }
  818. {
  819. let mut versions = HashSet::<Version>::new();
  820. versions.insert(1);
  821. versions.insert(2);
  822. versions.insert(3);
  823. versions.insert(500);
  824. assert_eq!(
  825. String::from("1-3,500"),
  826. contract_protocol_list(&versions)
  827. );
  828. }
  829. }
  830. }