protover.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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 std::u32;
  11. use tor_util::strings::NUL_BYTE;
  12. /// The first version of Tor that included "proto" entries in its descriptors.
  13. /// Authorities should use this to decide whether to guess proto lines.
  14. ///
  15. /// C_RUST_COUPLED:
  16. /// src/or/protover.h `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`
  17. const FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS: &'static str = "0.2.9.3-alpha";
  18. /// The maximum number of subprotocol version numbers we will attempt to expand
  19. /// before concluding that someone is trying to DoS us
  20. ///
  21. /// C_RUST_COUPLED: src/or/protover.c `MAX_PROTOCOLS_TO_EXPAND`
  22. const MAX_PROTOCOLS_TO_EXPAND: usize = (1<<16);
  23. /// Currently supported protocols and their versions, as a byte-slice.
  24. ///
  25. /// # Warning
  26. ///
  27. /// This byte-slice ends in a NUL byte. This is so that we can directly convert
  28. /// it to an `&'static CStr` in the FFI code, in order to hand the static string
  29. /// to C in a way that is compatible with C static strings.
  30. ///
  31. /// Rust code which wishes to accesses this string should use
  32. /// `protover::get_supported_protocols()` instead.
  33. ///
  34. /// C_RUST_COUPLED: src/or/protover.c `protover_get_supported_protocols`
  35. pub(crate) const SUPPORTED_PROTOCOLS: &'static [u8] =
  36. b"Cons=1-2 \
  37. Desc=1-2 \
  38. DirCache=1-2 \
  39. HSDir=1-2 \
  40. HSIntro=3-4 \
  41. HSRend=1-2 \
  42. Link=1-5 \
  43. LinkAuth=1,3 \
  44. Microdesc=1-2 \
  45. Relay=1-2\0";
  46. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  47. ///
  48. /// C_RUST_COUPLED: src/or/protover.h `protocol_type_t`
  49. #[derive(Hash, Eq, PartialEq, Debug)]
  50. pub enum Proto {
  51. Cons,
  52. Desc,
  53. DirCache,
  54. HSDir,
  55. HSIntro,
  56. HSRend,
  57. Link,
  58. LinkAuth,
  59. Microdesc,
  60. Relay,
  61. }
  62. impl fmt::Display for Proto {
  63. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  64. write!(f, "{:?}", self)
  65. }
  66. }
  67. /// Translates a string representation of a protocol into a Proto type.
  68. /// Error if the string is an unrecognized protocol name.
  69. ///
  70. /// C_RUST_COUPLED: src/or/protover.c `PROTOCOL_NAMES`
  71. impl FromStr for Proto {
  72. type Err = &'static str;
  73. fn from_str(s: &str) -> Result<Self, Self::Err> {
  74. match s {
  75. "Cons" => Ok(Proto::Cons),
  76. "Desc" => Ok(Proto::Desc),
  77. "DirCache" => Ok(Proto::DirCache),
  78. "HSDir" => Ok(Proto::HSDir),
  79. "HSIntro" => Ok(Proto::HSIntro),
  80. "HSRend" => Ok(Proto::HSRend),
  81. "Link" => Ok(Proto::Link),
  82. "LinkAuth" => Ok(Proto::LinkAuth),
  83. "Microdesc" => Ok(Proto::Microdesc),
  84. "Relay" => Ok(Proto::Relay),
  85. _ => Err("Not a valid protocol type"),
  86. }
  87. }
  88. }
  89. /// Get the string representation of current supported protocols
  90. ///
  91. /// # Returns
  92. ///
  93. /// A `String` whose value is the existing protocols supported by tor.
  94. /// Returned data is in the format as follows:
  95. ///
  96. /// "HSDir=1-1 LinkAuth=1"
  97. ///
  98. pub fn get_supported_protocols() -> &'static str {
  99. // The `len() - 1` is to remove the NUL byte.
  100. // The `unwrap` is safe becauase we SUPPORTED_PROTOCOLS is under
  101. // our control.
  102. str::from_utf8(&SUPPORTED_PROTOCOLS[..SUPPORTED_PROTOCOLS.len() - 1])
  103. .unwrap_or("")
  104. }
  105. pub struct SupportedProtocols(HashMap<Proto, Versions>);
  106. impl SupportedProtocols {
  107. pub fn from_proto_entries<I, S>(protocol_strs: I) -> Result<Self, &'static str>
  108. where
  109. I: Iterator<Item = S>,
  110. S: AsRef<str>,
  111. {
  112. let mut parsed = HashMap::new();
  113. for subproto in protocol_strs {
  114. let (name, version) = get_proto_and_vers(subproto.as_ref())?;
  115. parsed.insert(name, version);
  116. }
  117. Ok(SupportedProtocols(parsed))
  118. }
  119. /// Translates a string representation of a protocol list to a
  120. /// SupportedProtocols instance.
  121. ///
  122. /// # Examples
  123. ///
  124. /// ```
  125. /// use protover::SupportedProtocols;
  126. ///
  127. /// let supported_protocols = SupportedProtocols::from_proto_entries_string(
  128. /// "HSDir=1-2 HSIntro=3-4"
  129. /// );
  130. /// ```
  131. pub fn from_proto_entries_string(
  132. proto_entries: &str,
  133. ) -> Result<Self, &'static str> {
  134. Self::from_proto_entries(proto_entries.split(" "))
  135. }
  136. /// Translate the supported tor versions from a string into a
  137. /// HashMap, which is useful when looking up a specific
  138. /// subprotocol.
  139. ///
  140. fn tor_supported() -> Result<Self, &'static str> {
  141. Self::from_proto_entries_string(get_supported_protocols())
  142. }
  143. }
  144. type Version = u32;
  145. /// Set of versions for a protocol.
  146. #[derive(Debug, PartialEq, Eq)]
  147. pub struct Versions(HashSet<Version>);
  148. impl Versions {
  149. /// Get the unique version numbers supported by a subprotocol.
  150. ///
  151. /// # Inputs
  152. ///
  153. /// * `version_string`, a string comprised of "[0-9,-]"
  154. ///
  155. /// # Returns
  156. ///
  157. /// A `Result` whose `Ok` value is a `HashSet<u32>` holding all of the unique
  158. /// version numbers. If there were ranges in the `version_string`, then these
  159. /// are expanded, i.e. `"1-3"` would expand to `HashSet<u32>::new([1, 2, 3])`.
  160. /// The returned HashSet is *unordered*.
  161. ///
  162. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  163. /// of the error.
  164. ///
  165. /// # Errors
  166. ///
  167. /// This function will error if:
  168. ///
  169. /// * the `version_string` is empty or contains an equals (`"="`) sign,
  170. /// * the expansion of a version range produces an error (see
  171. /// `expand_version_range`),
  172. /// * any single version number is not parseable as an `u32` in radix 10, or
  173. /// * there are greater than 2^16 version numbers to expand.
  174. ///
  175. fn from_version_string(
  176. version_string: &str,
  177. ) -> Result<Self, &'static str> {
  178. if version_string.is_empty() {
  179. return Err("version string is empty");
  180. }
  181. let mut versions = HashSet::<Version>::new();
  182. for piece in version_string.split(",") {
  183. if piece.contains("-") {
  184. for p in expand_version_range(piece)? {
  185. versions.insert(p);
  186. }
  187. } else {
  188. let v = u32::from_str(piece).or(
  189. Err("invalid protocol entry"),
  190. )?;
  191. if v == u32::MAX {
  192. return Err("invalid protocol entry");
  193. }
  194. versions.insert(v);
  195. }
  196. if versions.len() > MAX_PROTOCOLS_TO_EXPAND {
  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. if lower == u32::MAX || higher == u32::MAX {
  410. return Err("protocol range value out of range");
  411. }
  412. // We can use inclusive range syntax when it becomes stable.
  413. let result = lower..higher + 1;
  414. if result.len() > MAX_PROTOCOLS_TO_EXPAND {
  415. Err("Too many protocols in expanded range")
  416. } else {
  417. Ok(result)
  418. }
  419. }
  420. /// Checks to see if there is a continuous range of integers, starting at the
  421. /// first in the list. Returns the last integer in the range if a range exists.
  422. /// Helper for compute_vote
  423. ///
  424. /// # Inputs
  425. ///
  426. /// `list`, an ordered vector of `u32` integers of "[0-9,-]" representing the
  427. /// supported versions for a single protocol.
  428. ///
  429. /// # Returns
  430. ///
  431. /// A `bool` indicating whether the list contains a range, starting at the
  432. /// first in the list, and an `u32` of the last integer in the range.
  433. ///
  434. /// For example, if given vec![1, 2, 3, 5], find_range will return true,
  435. /// as there is a continuous range, and 3, which is the last number in the
  436. /// continuous range.
  437. ///
  438. fn find_range(list: &Vec<u32>) -> (bool, u32) {
  439. if list.len() == 0 {
  440. return (false, 0);
  441. }
  442. let mut iterable = list.iter().peekable();
  443. let mut range_end = match iterable.next() {
  444. Some(n) => *n,
  445. None => return (false, 0),
  446. };
  447. let mut has_range = false;
  448. while iterable.peek().is_some() {
  449. let n = *iterable.next().unwrap();
  450. if n != range_end + 1 {
  451. break;
  452. }
  453. has_range = true;
  454. range_end = n;
  455. }
  456. (has_range, range_end)
  457. }
  458. /// Contracts a HashSet representation of supported versions into a string.
  459. /// Helper for compute_vote
  460. ///
  461. /// # Inputs
  462. ///
  463. /// `supported_set`, a set of integers of "[0-9,-]" representing the
  464. /// supported versions for a single protocol.
  465. ///
  466. /// # Returns
  467. ///
  468. /// A `String` representation of this set in ascending order.
  469. ///
  470. fn contract_protocol_list<'a>(supported_set: &'a HashSet<Version>) -> String {
  471. let mut supported: Vec<Version> =
  472. supported_set.iter().map(|x| *x).collect();
  473. supported.sort();
  474. let mut final_output: Vec<String> = Vec::new();
  475. while supported.len() != 0 {
  476. let (has_range, end) = find_range(&supported);
  477. let current = supported.remove(0);
  478. if has_range {
  479. final_output.push(format!(
  480. "{}-{}",
  481. current.to_string(),
  482. &end.to_string(),
  483. ));
  484. supported.retain(|&x| x > end);
  485. } else {
  486. final_output.push(current.to_string());
  487. }
  488. }
  489. final_output.join(",")
  490. }
  491. /// Parses a protocol list without validating the protocol names
  492. ///
  493. /// # Inputs
  494. ///
  495. /// * `protocol_string`, a string comprised of keys and values, both which are
  496. /// strings. The keys are the protocol names while values are a string
  497. /// representation of the supported versions.
  498. ///
  499. /// The input is _not_ expected to be a subset of the Proto types
  500. ///
  501. /// # Returns
  502. ///
  503. /// A `Result` whose `Ok` value is a `HashSet<Version>` holding all of the
  504. /// unique version numbers.
  505. ///
  506. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  507. /// of the error.
  508. ///
  509. /// # Errors
  510. ///
  511. /// This function will error if:
  512. ///
  513. /// * The protocol string does not follow the "protocol_name=version_list"
  514. /// expected format
  515. /// * If the version string is malformed. See `Versions::from_version_string`.
  516. ///
  517. fn parse_protocols_from_string_with_no_validation<'a>(
  518. protocol_string: &'a str,
  519. ) -> Result<HashMap<String, Versions>, &'static str> {
  520. let mut parsed: HashMap<String, Versions> = HashMap::new();
  521. for subproto in protocol_string.split(" ") {
  522. let mut parts = subproto.splitn(2, "=");
  523. let name = match parts.next() {
  524. Some(n) => n,
  525. None => return Err("invalid protover entry"),
  526. };
  527. let vers = match parts.next() {
  528. Some(n) => n,
  529. None => return Err("invalid protover entry"),
  530. };
  531. let versions = Versions::from_version_string(vers)?;
  532. parsed.insert(String::from(name), versions);
  533. }
  534. Ok(parsed)
  535. }
  536. /// Protocol voting implementation.
  537. ///
  538. /// Given a list of strings describing protocol versions, return a new
  539. /// string encoding all of the protocols that are listed by at
  540. /// least threshold of the inputs.
  541. ///
  542. /// The string is sorted according to the following conventions:
  543. /// - Protocols names are alphabetized
  544. /// - Protocols are in order low to high
  545. /// - Individual and ranges are listed together. For example,
  546. /// "3, 5-10,13"
  547. /// - All entries are unique
  548. ///
  549. /// # Examples
  550. /// ```
  551. /// use protover::compute_vote;
  552. ///
  553. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  554. /// let vote = compute_vote(protos, 2);
  555. /// assert_eq!("Link=3", vote)
  556. /// ```
  557. pub fn compute_vote(
  558. list_of_proto_strings: Vec<String>,
  559. threshold: i32,
  560. ) -> String {
  561. let empty = String::from("");
  562. if list_of_proto_strings.is_empty() {
  563. return empty;
  564. }
  565. // all_count is a structure to represent the count of the number of
  566. // supported versions for a specific protocol. For example, in JSON format:
  567. // {
  568. // "FirstSupportedProtocol": {
  569. // "1": "3",
  570. // "2": "1"
  571. // }
  572. // }
  573. // means that FirstSupportedProtocol has three votes which support version
  574. // 1, and one vote that supports version 2
  575. let mut all_count: HashMap<String, HashMap<Version, usize>> =
  576. HashMap::new();
  577. // parse and collect all of the protos and their versions and collect them
  578. for vote in list_of_proto_strings {
  579. let this_vote: HashMap<String, Versions> =
  580. match parse_protocols_from_string_with_no_validation(&vote) {
  581. Ok(result) => result,
  582. Err(_) => continue,
  583. };
  584. for (protocol, versions) in this_vote {
  585. let supported_vers: &mut HashMap<Version, usize> =
  586. all_count.entry(protocol).or_insert(HashMap::new());
  587. for version in versions.0 {
  588. let counter: &mut usize =
  589. supported_vers.entry(version).or_insert(0);
  590. *counter += 1;
  591. }
  592. }
  593. }
  594. let mut final_output: HashMap<String, String> =
  595. HashMap::with_capacity(get_supported_protocols().split(" ").count());
  596. // Go through and remove verstions that are less than the threshold
  597. for (protocol, versions) in all_count {
  598. let mut meets_threshold = HashSet::new();
  599. for (version, count) in versions {
  600. if count >= threshold as usize {
  601. meets_threshold.insert(version);
  602. }
  603. }
  604. // For each protocol, compress its version list into the expected
  605. // protocol version string format
  606. let contracted = contract_protocol_list(&meets_threshold);
  607. if !contracted.is_empty() {
  608. final_output.insert(protocol, contracted);
  609. }
  610. }
  611. write_vote_to_string(&final_output)
  612. }
  613. /// Return a String comprised of protocol entries in alphabetical order
  614. ///
  615. /// # Inputs
  616. ///
  617. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  618. /// The keys are the protocol names while values are a string representation of
  619. /// the supported versions.
  620. ///
  621. /// # Returns
  622. ///
  623. /// A `String` whose value is series of pairs, comprising of the protocol name
  624. /// and versions that it supports. The string takes the following format:
  625. ///
  626. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  627. ///
  628. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  629. /// entry format.
  630. ///
  631. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  632. let mut keys: Vec<&String> = vote.keys().collect();
  633. keys.sort();
  634. let mut output = Vec::new();
  635. for key in keys {
  636. // TODO error in indexing here?
  637. output.push(format!("{}={}", key, vote[key]));
  638. }
  639. output.join(" ")
  640. }
  641. /// Returns a boolean indicating whether the given protocol and version is
  642. /// supported in any of the existing Tor protocols
  643. ///
  644. /// # Examples
  645. /// ```
  646. /// use protover::*;
  647. ///
  648. /// let is_supported = is_supported_here(Proto::Link, 10);
  649. /// assert_eq!(false, is_supported);
  650. ///
  651. /// let is_supported = is_supported_here(Proto::Link, 1);
  652. /// assert_eq!(true, is_supported);
  653. /// ```
  654. pub fn is_supported_here(proto: Proto, vers: Version) -> bool {
  655. let currently_supported = match SupportedProtocols::tor_supported() {
  656. Ok(result) => result.0,
  657. Err(_) => return false,
  658. };
  659. let supported_versions = match currently_supported.get(&proto) {
  660. Some(n) => n,
  661. None => return false,
  662. };
  663. supported_versions.0.contains(&vers)
  664. }
  665. /// Older versions of Tor cannot infer their own subprotocols
  666. /// Used to determine which subprotocols are supported by older Tor versions.
  667. ///
  668. /// # Inputs
  669. ///
  670. /// * `version`, a string comprised of "[0-9a-z.-]"
  671. ///
  672. /// # Returns
  673. ///
  674. /// A `&'static [u8]` encoding a list of protocol names and supported
  675. /// versions. The string takes the following format:
  676. ///
  677. /// "HSDir=1-1 LinkAuth=1"
  678. ///
  679. /// This function returns the protocols that are supported by the version input,
  680. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  681. ///
  682. /// C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  683. pub fn compute_for_old_tor(version: &str) -> &'static [u8] {
  684. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  685. return NUL_BYTE;
  686. }
  687. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  688. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  689. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  690. }
  691. if c_tor_version_as_new_as(version, "0.2.7.5") {
  692. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  693. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  694. }
  695. if c_tor_version_as_new_as(version, "0.2.4.19") {
  696. return b"Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  697. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2\0";
  698. }
  699. NUL_BYTE
  700. }
  701. #[cfg(test)]
  702. mod test {
  703. use super::Version;
  704. #[test]
  705. fn test_versions_from_version_string() {
  706. use std::collections::HashSet;
  707. use super::Versions;
  708. assert_eq!(Err("version string is empty"), Versions::from_version_string(""));
  709. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  710. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  711. {
  712. let mut versions: HashSet<Version> = HashSet::new();
  713. versions.insert(1);
  714. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  715. }
  716. {
  717. let mut versions: HashSet<Version> = HashSet::new();
  718. versions.insert(1);
  719. versions.insert(2);
  720. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  721. }
  722. {
  723. let mut versions: HashSet<Version> = HashSet::new();
  724. versions.insert(1);
  725. versions.insert(2);
  726. versions.insert(3);
  727. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  728. }
  729. {
  730. let mut versions: HashSet<Version> = HashSet::new();
  731. versions.insert(1);
  732. versions.insert(2);
  733. versions.insert(5);
  734. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  735. }
  736. {
  737. let mut versions: HashSet<Version> = HashSet::new();
  738. versions.insert(1);
  739. versions.insert(3);
  740. versions.insert(4);
  741. versions.insert(5);
  742. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  743. }
  744. }
  745. #[test]
  746. fn test_contains_only_supported_protocols() {
  747. use super::contains_only_supported_protocols;
  748. assert_eq!(false, contains_only_supported_protocols(""));
  749. assert_eq!(false, contains_only_supported_protocols("Cons="));
  750. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  751. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  752. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  753. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  754. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  755. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  756. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  757. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  758. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  759. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  760. }
  761. #[test]
  762. fn test_find_range() {
  763. use super::find_range;
  764. assert_eq!((false, 0), find_range(&vec![]));
  765. assert_eq!((false, 1), find_range(&vec![1]));
  766. assert_eq!((true, 2), find_range(&vec![1, 2]));
  767. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  768. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  769. }
  770. #[test]
  771. fn test_expand_version_range() {
  772. use super::expand_version_range;
  773. assert_eq!(Err("version string empty"), expand_version_range(""));
  774. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  775. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  776. assert_eq!(
  777. Err("cannot parse protocol range lower bound"),
  778. expand_version_range("a")
  779. );
  780. assert_eq!(
  781. Err("cannot parse protocol range upper bound"),
  782. expand_version_range("1-a")
  783. );
  784. assert_eq!(Ok(1000..66536), expand_version_range("1000-66535"));
  785. assert_eq!(Err("Too many protocols in expanded range"),
  786. expand_version_range("1000-66536"));
  787. }
  788. #[test]
  789. fn test_contract_protocol_list() {
  790. use std::collections::HashSet;
  791. use super::contract_protocol_list;
  792. {
  793. let mut versions = HashSet::<Version>::new();
  794. assert_eq!(String::from(""), contract_protocol_list(&versions));
  795. versions.insert(1);
  796. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  797. versions.insert(2);
  798. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  799. }
  800. {
  801. let mut versions = HashSet::<Version>::new();
  802. versions.insert(1);
  803. versions.insert(3);
  804. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  805. }
  806. {
  807. let mut versions = HashSet::<Version>::new();
  808. versions.insert(1);
  809. versions.insert(2);
  810. versions.insert(3);
  811. versions.insert(4);
  812. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  813. }
  814. {
  815. let mut versions = HashSet::<Version>::new();
  816. versions.insert(1);
  817. versions.insert(3);
  818. versions.insert(5);
  819. versions.insert(6);
  820. versions.insert(7);
  821. assert_eq!(
  822. String::from("1,3,5-7"),
  823. contract_protocol_list(&versions)
  824. );
  825. }
  826. {
  827. let mut versions = HashSet::<Version>::new();
  828. versions.insert(1);
  829. versions.insert(2);
  830. versions.insert(3);
  831. versions.insert(500);
  832. assert_eq!(
  833. String::from("1-3,500"),
  834. contract_protocol_list(&versions)
  835. );
  836. }
  837. }
  838. }