protover.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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. let mut versions = HashSet::<Version>::new();
  179. for piece in version_string.split(",") {
  180. if piece.contains("-") {
  181. for p in expand_version_range(piece)? {
  182. versions.insert(p);
  183. }
  184. } else if piece == "" {
  185. continue;
  186. } else {
  187. let v = u32::from_str(piece).or(
  188. Err("invalid protocol entry"),
  189. )?;
  190. if v == u32::MAX {
  191. return Err("invalid protocol entry");
  192. }
  193. versions.insert(v);
  194. }
  195. if versions.len() > MAX_PROTOCOLS_TO_EXPAND {
  196. return Err("Too many versions to expand");
  197. }
  198. }
  199. Ok(Versions(versions))
  200. }
  201. }
  202. /// Parse the subprotocol type and its version numbers.
  203. ///
  204. /// # Inputs
  205. ///
  206. /// * A `protocol_entry` string, comprised of a keyword, an "=" sign, and one
  207. /// or more version numbers.
  208. ///
  209. /// # Returns
  210. ///
  211. /// A `Result` whose `Ok` value is a tuple of `(Proto, HashSet<u32>)`, where the
  212. /// first element is the subprotocol type (see `protover::Proto`) and the last
  213. /// element is a(n unordered) set of unique version numbers which are supported.
  214. /// Otherwise, the `Err` value of this `Result` is a description of the error
  215. ///
  216. fn get_proto_and_vers<'a>(
  217. protocol_entry: &'a str,
  218. ) -> Result<(Proto, Versions), &'static str> {
  219. let mut parts = protocol_entry.splitn(2, "=");
  220. let proto = match parts.next() {
  221. Some(n) => n,
  222. None => return Err("invalid protover entry"),
  223. };
  224. let vers = match parts.next() {
  225. Some(n) => n,
  226. None => return Err("invalid protover entry"),
  227. };
  228. let versions = Versions::from_version_string(vers)?;
  229. let proto_name = proto.parse()?;
  230. Ok((proto_name, versions))
  231. }
  232. /// Parses a single subprotocol entry string into subprotocol and version
  233. /// parts, and then checks whether any of those versions are unsupported.
  234. /// Helper for protover::all_supported
  235. ///
  236. /// # Inputs
  237. ///
  238. /// Accepted data is in the string format as follows:
  239. ///
  240. /// "HSDir=1-1"
  241. ///
  242. /// # Returns
  243. ///
  244. /// Returns `true` if the protocol entry is well-formatted and only contains
  245. /// versions that are also supported in tor. Otherwise, returns false
  246. ///
  247. fn contains_only_supported_protocols(proto_entry: &str) -> bool {
  248. let (name, mut vers) = match get_proto_and_vers(proto_entry) {
  249. Ok(n) => n,
  250. Err(_) => return false,
  251. };
  252. let currently_supported = match SupportedProtocols::tor_supported() {
  253. Ok(n) => n.0,
  254. Err(_) => return false,
  255. };
  256. let supported_versions = match currently_supported.get(&name) {
  257. Some(n) => n,
  258. None => return false,
  259. };
  260. vers.0.retain(|x| !supported_versions.0.contains(x));
  261. vers.0.is_empty()
  262. }
  263. /// Determine if we support every protocol a client supports, and if not,
  264. /// determine which protocols we do not have support for.
  265. ///
  266. /// # Inputs
  267. ///
  268. /// Accepted data is in the string format as follows:
  269. ///
  270. /// "HSDir=1-1 LinkAuth=1-2"
  271. ///
  272. /// # Returns
  273. ///
  274. /// Return `true` if every protocol version is one that we support.
  275. /// Otherwise, return `false`.
  276. /// Optionally, return parameters which the client supports but which we do not
  277. ///
  278. /// # Examples
  279. /// ```
  280. /// use protover::all_supported;
  281. ///
  282. /// let (is_supported, unsupported) = all_supported("Link=1");
  283. /// assert_eq!(true, is_supported);
  284. ///
  285. /// let (is_supported, unsupported) = all_supported("Link=5-6");
  286. /// assert_eq!(false, is_supported);
  287. /// assert_eq!("Link=5-6", unsupported);
  288. ///
  289. pub fn all_supported(protocols: &str) -> (bool, String) {
  290. let unsupported = protocols
  291. .split_whitespace()
  292. .filter(|v| !contains_only_supported_protocols(v))
  293. .collect::<Vec<&str>>();
  294. (unsupported.is_empty(), unsupported.join(" "))
  295. }
  296. /// Return true iff the provided protocol list includes support for the
  297. /// indicated protocol and version.
  298. /// Otherwise, return false
  299. ///
  300. /// # Inputs
  301. ///
  302. /// * `list`, a string representation of a list of protocol entries.
  303. /// * `proto`, a `Proto` to test support for
  304. /// * `vers`, a `Version` version which we will go on to determine whether the
  305. /// specified protocol supports.
  306. ///
  307. /// # Examples
  308. /// ```
  309. /// use protover::*;
  310. ///
  311. /// let is_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  312. /// Proto::Cons,1);
  313. /// assert_eq!(true, is_supported);
  314. ///
  315. /// let is_not_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  316. /// Proto::Cons,5);
  317. /// assert_eq!(false, is_not_supported)
  318. /// ```
  319. pub fn protover_string_supports_protocol(
  320. list: &str,
  321. proto: Proto,
  322. vers: Version,
  323. ) -> bool {
  324. let supported = match SupportedProtocols::from_proto_entries_string(list) {
  325. Ok(result) => result.0,
  326. Err(_) => return false,
  327. };
  328. let supported_versions = match supported.get(&proto) {
  329. Some(n) => n,
  330. None => return false,
  331. };
  332. supported_versions.0.contains(&vers)
  333. }
  334. /// As protover_string_supports_protocol(), but also returns True if
  335. /// any later version of the protocol is supported.
  336. ///
  337. /// # Examples
  338. /// ```
  339. /// use protover::*;
  340. ///
  341. /// let is_supported = protover_string_supports_protocol_or_later(
  342. /// "Link=3-4 Cons=5", Proto::Cons, 5);
  343. ///
  344. /// assert_eq!(true, is_supported);
  345. ///
  346. /// let is_supported = protover_string_supports_protocol_or_later(
  347. /// "Link=3-4 Cons=5", Proto::Cons, 4);
  348. ///
  349. /// assert_eq!(true, is_supported);
  350. ///
  351. /// let is_supported = protover_string_supports_protocol_or_later(
  352. /// "Link=3-4 Cons=5", Proto::Cons, 6);
  353. ///
  354. /// assert_eq!(false, is_supported);
  355. /// ```
  356. pub fn protover_string_supports_protocol_or_later(
  357. list: &str,
  358. proto: Proto,
  359. vers: u32,
  360. ) -> bool {
  361. let supported = match SupportedProtocols::from_proto_entries_string(list) {
  362. Ok(result) => result.0,
  363. Err(_) => return false,
  364. };
  365. let supported_versions = match supported.get(&proto) {
  366. Some(n) => n,
  367. None => return false,
  368. };
  369. supported_versions.0.iter().any(|v| v >= &vers)
  370. }
  371. /// Fully expand a version range. For example, 1-3 expands to 1,2,3
  372. /// Helper for Versions::from_version_string
  373. ///
  374. /// # Inputs
  375. ///
  376. /// `range`, a string comprised of "[0-9,-]"
  377. ///
  378. /// # Returns
  379. ///
  380. /// A `Result` whose `Ok` value a vector of unsigned integers representing the
  381. /// expanded range of supported versions by a single protocol.
  382. /// Otherwise, the `Err` value of this `Result` is a description of the error
  383. ///
  384. /// # Errors
  385. ///
  386. /// This function will error if:
  387. ///
  388. /// * the specified range is empty
  389. /// * the version range does not contain both a valid lower and upper bound.
  390. ///
  391. fn expand_version_range(range: &str) -> Result<Range<u32>, &'static str> {
  392. if range.is_empty() {
  393. return Err("version string empty");
  394. }
  395. let mut parts = range.split("-");
  396. let lower_string = parts.next().ok_or(
  397. "cannot parse protocol range lower bound",
  398. )?;
  399. let lower = u32::from_str_radix(lower_string, 10).or(Err(
  400. "cannot parse protocol range lower bound",
  401. ))?;
  402. let higher_string = parts.next().ok_or(
  403. "cannot parse protocol range upper bound",
  404. )?;
  405. let higher = u32::from_str_radix(higher_string, 10).or(Err(
  406. "cannot parse protocol range upper bound",
  407. ))?;
  408. if lower == u32::MAX || higher == u32::MAX {
  409. return Err("protocol range value out of range");
  410. }
  411. if lower > higher {
  412. return Err("protocol range is badly formed");
  413. }
  414. // We can use inclusive range syntax when it becomes stable.
  415. let result = lower..higher + 1;
  416. if result.len() > MAX_PROTOCOLS_TO_EXPAND {
  417. Err("Too many protocols in expanded range")
  418. } else {
  419. Ok(result)
  420. }
  421. }
  422. /// Checks to see if there is a continuous range of integers, starting at the
  423. /// first in the list. Returns the last integer in the range if a range exists.
  424. /// Helper for compute_vote
  425. ///
  426. /// # Inputs
  427. ///
  428. /// `list`, an ordered vector of `u32` integers of "[0-9,-]" representing the
  429. /// supported versions for a single protocol.
  430. ///
  431. /// # Returns
  432. ///
  433. /// A `bool` indicating whether the list contains a range, starting at the
  434. /// first in the list, and an `u32` of the last integer in the range.
  435. ///
  436. /// For example, if given vec![1, 2, 3, 5], find_range will return true,
  437. /// as there is a continuous range, and 3, which is the last number in the
  438. /// continuous range.
  439. ///
  440. fn find_range(list: &Vec<u32>) -> (bool, u32) {
  441. if list.len() == 0 {
  442. return (false, 0);
  443. }
  444. let mut iterable = list.iter().peekable();
  445. let mut range_end = match iterable.next() {
  446. Some(n) => *n,
  447. None => return (false, 0),
  448. };
  449. let mut has_range = false;
  450. while iterable.peek().is_some() {
  451. let n = *iterable.next().unwrap();
  452. if n != range_end + 1 {
  453. break;
  454. }
  455. has_range = true;
  456. range_end = n;
  457. }
  458. (has_range, range_end)
  459. }
  460. /// Contracts a HashSet representation of supported versions into a string.
  461. /// Helper for compute_vote
  462. ///
  463. /// # Inputs
  464. ///
  465. /// `supported_set`, a set of integers of "[0-9,-]" representing the
  466. /// supported versions for a single protocol.
  467. ///
  468. /// # Returns
  469. ///
  470. /// A `String` representation of this set in ascending order.
  471. ///
  472. fn contract_protocol_list<'a>(supported_set: &'a HashSet<Version>) -> String {
  473. let mut supported: Vec<Version> =
  474. supported_set.iter().map(|x| *x).collect();
  475. supported.sort();
  476. let mut final_output: Vec<String> = Vec::new();
  477. while supported.len() != 0 {
  478. let (has_range, end) = find_range(&supported);
  479. let current = supported.remove(0);
  480. if has_range {
  481. final_output.push(format!(
  482. "{}-{}",
  483. current.to_string(),
  484. &end.to_string(),
  485. ));
  486. supported.retain(|&x| x > end);
  487. } else {
  488. final_output.push(current.to_string());
  489. }
  490. }
  491. final_output.join(",")
  492. }
  493. /// Parses a protocol list without validating the protocol names
  494. ///
  495. /// # Inputs
  496. ///
  497. /// * `protocol_string`, a string comprised of keys and values, both which are
  498. /// strings. The keys are the protocol names while values are a string
  499. /// representation of the supported versions.
  500. ///
  501. /// The input is _not_ expected to be a subset of the Proto types
  502. ///
  503. /// # Returns
  504. ///
  505. /// A `Result` whose `Ok` value is a `HashSet<Version>` holding all of the
  506. /// unique version numbers.
  507. ///
  508. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  509. /// of the error.
  510. ///
  511. /// # Errors
  512. ///
  513. /// This function will error if:
  514. ///
  515. /// * The protocol string does not follow the "protocol_name=version_list"
  516. /// expected format
  517. /// * If the version string is malformed. See `Versions::from_version_string`.
  518. ///
  519. fn parse_protocols_from_string_with_no_validation<'a>(
  520. protocol_string: &'a str,
  521. ) -> Result<HashMap<String, Versions>, &'static str> {
  522. let mut parsed: HashMap<String, Versions> = HashMap::new();
  523. for subproto in protocol_string.split(" ") {
  524. let mut parts = subproto.splitn(2, "=");
  525. let name = match parts.next() {
  526. Some("") => return Err("invalid protover entry"),
  527. Some(n) => n,
  528. None => return Err("invalid protover entry"),
  529. };
  530. let vers = match parts.next() {
  531. Some(n) => n,
  532. None => return Err("invalid protover entry"),
  533. };
  534. let versions = Versions::from_version_string(vers)?;
  535. parsed.insert(String::from(name), versions);
  536. }
  537. Ok(parsed)
  538. }
  539. /// Protocol voting implementation.
  540. ///
  541. /// Given a list of strings describing protocol versions, return a new
  542. /// string encoding all of the protocols that are listed by at
  543. /// least threshold of the inputs.
  544. ///
  545. /// The string is sorted according to the following conventions:
  546. /// - Protocols names are alphabetized
  547. /// - Protocols are in order low to high
  548. /// - Individual and ranges are listed together. For example,
  549. /// "3, 5-10,13"
  550. /// - All entries are unique
  551. ///
  552. /// # Examples
  553. /// ```
  554. /// use protover::compute_vote;
  555. ///
  556. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  557. /// let vote = compute_vote(protos, 2);
  558. /// assert_eq!("Link=3", vote)
  559. /// ```
  560. pub fn compute_vote(
  561. list_of_proto_strings: Vec<String>,
  562. threshold: i32,
  563. ) -> String {
  564. let empty = String::from("");
  565. if list_of_proto_strings.is_empty() {
  566. return empty;
  567. }
  568. // all_count is a structure to represent the count of the number of
  569. // supported versions for a specific protocol. For example, in JSON format:
  570. // {
  571. // "FirstSupportedProtocol": {
  572. // "1": "3",
  573. // "2": "1"
  574. // }
  575. // }
  576. // means that FirstSupportedProtocol has three votes which support version
  577. // 1, and one vote that supports version 2
  578. let mut all_count: HashMap<String, HashMap<Version, usize>> =
  579. HashMap::new();
  580. // parse and collect all of the protos and their versions and collect them
  581. for vote in list_of_proto_strings {
  582. let this_vote: HashMap<String, Versions> =
  583. match parse_protocols_from_string_with_no_validation(&vote) {
  584. Ok(result) => result,
  585. Err(_) => continue,
  586. };
  587. for (protocol, versions) in this_vote {
  588. let supported_vers: &mut HashMap<Version, usize> =
  589. all_count.entry(protocol).or_insert(HashMap::new());
  590. for version in versions.0 {
  591. let counter: &mut usize =
  592. supported_vers.entry(version).or_insert(0);
  593. *counter += 1;
  594. }
  595. }
  596. }
  597. let mut final_output: HashMap<String, String> =
  598. HashMap::with_capacity(get_supported_protocols().split(" ").count());
  599. // Go through and remove verstions that are less than the threshold
  600. for (protocol, versions) in all_count {
  601. let mut meets_threshold = HashSet::new();
  602. for (version, count) in versions {
  603. if count >= threshold as usize {
  604. meets_threshold.insert(version);
  605. }
  606. }
  607. // For each protocol, compress its version list into the expected
  608. // protocol version string format
  609. let contracted = contract_protocol_list(&meets_threshold);
  610. if !contracted.is_empty() {
  611. final_output.insert(protocol, contracted);
  612. }
  613. }
  614. write_vote_to_string(&final_output)
  615. }
  616. /// Return a String comprised of protocol entries in alphabetical order
  617. ///
  618. /// # Inputs
  619. ///
  620. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  621. /// The keys are the protocol names while values are a string representation of
  622. /// the supported versions.
  623. ///
  624. /// # Returns
  625. ///
  626. /// A `String` whose value is series of pairs, comprising of the protocol name
  627. /// and versions that it supports. The string takes the following format:
  628. ///
  629. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  630. ///
  631. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  632. /// entry format.
  633. ///
  634. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  635. let mut keys: Vec<&String> = vote.keys().collect();
  636. keys.sort();
  637. let mut output = Vec::new();
  638. for key in keys {
  639. // TODO error in indexing here?
  640. output.push(format!("{}={}", key, vote[key]));
  641. }
  642. output.join(" ")
  643. }
  644. /// Returns a boolean indicating whether the given protocol and version is
  645. /// supported in any of the existing Tor protocols
  646. ///
  647. /// # Examples
  648. /// ```
  649. /// use protover::*;
  650. ///
  651. /// let is_supported = is_supported_here(Proto::Link, 10);
  652. /// assert_eq!(false, is_supported);
  653. ///
  654. /// let is_supported = is_supported_here(Proto::Link, 1);
  655. /// assert_eq!(true, is_supported);
  656. /// ```
  657. pub fn is_supported_here(proto: Proto, vers: Version) -> bool {
  658. let currently_supported = match SupportedProtocols::tor_supported() {
  659. Ok(result) => result.0,
  660. Err(_) => return false,
  661. };
  662. let supported_versions = match currently_supported.get(&proto) {
  663. Some(n) => n,
  664. None => return false,
  665. };
  666. supported_versions.0.contains(&vers)
  667. }
  668. /// Older versions of Tor cannot infer their own subprotocols
  669. /// Used to determine which subprotocols are supported by older Tor versions.
  670. ///
  671. /// # Inputs
  672. ///
  673. /// * `version`, a string comprised of "[0-9a-z.-]"
  674. ///
  675. /// # Returns
  676. ///
  677. /// A `&'static [u8]` encoding a list of protocol names and supported
  678. /// versions. The string takes the following format:
  679. ///
  680. /// "HSDir=1-1 LinkAuth=1"
  681. ///
  682. /// This function returns the protocols that are supported by the version input,
  683. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  684. ///
  685. /// C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  686. pub fn compute_for_old_tor(version: &str) -> &'static [u8] {
  687. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  688. return NUL_BYTE;
  689. }
  690. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  691. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  692. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  693. }
  694. if c_tor_version_as_new_as(version, "0.2.7.5") {
  695. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  696. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  697. }
  698. if c_tor_version_as_new_as(version, "0.2.4.19") {
  699. return b"Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  700. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2\0";
  701. }
  702. NUL_BYTE
  703. }
  704. #[cfg(test)]
  705. mod test {
  706. use super::Version;
  707. #[test]
  708. fn test_versions_from_version_string() {
  709. use std::collections::HashSet;
  710. use super::Versions;
  711. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  712. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  713. {
  714. let mut versions: HashSet<Version> = HashSet::new();
  715. versions.insert(1);
  716. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  717. }
  718. {
  719. let mut versions: HashSet<Version> = HashSet::new();
  720. versions.insert(1);
  721. versions.insert(2);
  722. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  723. }
  724. {
  725. let mut versions: HashSet<Version> = HashSet::new();
  726. versions.insert(1);
  727. versions.insert(2);
  728. versions.insert(3);
  729. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  730. }
  731. {
  732. let mut versions: HashSet<Version> = HashSet::new();
  733. versions.insert(1);
  734. versions.insert(2);
  735. versions.insert(5);
  736. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  737. }
  738. {
  739. let mut versions: HashSet<Version> = HashSet::new();
  740. versions.insert(1);
  741. versions.insert(3);
  742. versions.insert(4);
  743. versions.insert(5);
  744. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  745. }
  746. }
  747. #[test]
  748. fn test_contains_only_supported_protocols() {
  749. use super::contains_only_supported_protocols;
  750. assert_eq!(false, contains_only_supported_protocols(""));
  751. assert_eq!(true, contains_only_supported_protocols("Cons="));
  752. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  753. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  754. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  755. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  756. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  757. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  758. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  759. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  760. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  761. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  762. }
  763. #[test]
  764. fn test_find_range() {
  765. use super::find_range;
  766. assert_eq!((false, 0), find_range(&vec![]));
  767. assert_eq!((false, 1), find_range(&vec![1]));
  768. assert_eq!((true, 2), find_range(&vec![1, 2]));
  769. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  770. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  771. }
  772. #[test]
  773. fn test_expand_version_range() {
  774. use super::expand_version_range;
  775. assert_eq!(Err("version string empty"), expand_version_range(""));
  776. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  777. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  778. assert_eq!(
  779. Err("cannot parse protocol range lower bound"),
  780. expand_version_range("a")
  781. );
  782. assert_eq!(
  783. Err("cannot parse protocol range upper bound"),
  784. expand_version_range("1-a")
  785. );
  786. assert_eq!(Ok(1000..66536), expand_version_range("1000-66535"));
  787. assert_eq!(Err("Too many protocols in expanded range"),
  788. expand_version_range("1000-66536"));
  789. }
  790. #[test]
  791. fn test_contract_protocol_list() {
  792. use std::collections::HashSet;
  793. use super::contract_protocol_list;
  794. {
  795. let mut versions = HashSet::<Version>::new();
  796. assert_eq!(String::from(""), contract_protocol_list(&versions));
  797. versions.insert(1);
  798. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  799. versions.insert(2);
  800. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  801. }
  802. {
  803. let mut versions = HashSet::<Version>::new();
  804. versions.insert(1);
  805. versions.insert(3);
  806. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  807. }
  808. {
  809. let mut versions = HashSet::<Version>::new();
  810. versions.insert(1);
  811. versions.insert(2);
  812. versions.insert(3);
  813. versions.insert(4);
  814. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  815. }
  816. {
  817. let mut versions = HashSet::<Version>::new();
  818. versions.insert(1);
  819. versions.insert(3);
  820. versions.insert(5);
  821. versions.insert(6);
  822. versions.insert(7);
  823. assert_eq!(
  824. String::from("1,3,5-7"),
  825. contract_protocol_list(&versions)
  826. );
  827. }
  828. {
  829. let mut versions = HashSet::<Version>::new();
  830. versions.insert(1);
  831. versions.insert(2);
  832. versions.insert(3);
  833. versions.insert(500);
  834. assert_eq!(
  835. String::from("1-3,500"),
  836. contract_protocol_list(&versions)
  837. );
  838. }
  839. }
  840. }