protover.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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: u32 = 500;
  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()
  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 as usize {
  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. Ok(lower..higher + 1)
  406. }
  407. /// Checks to see if there is a continuous range of integers, starting at the
  408. /// first in the list. Returns the last integer in the range if a range exists.
  409. /// Helper for compute_vote
  410. ///
  411. /// # Inputs
  412. ///
  413. /// `list`, an ordered vector of `u32` integers of "[0-9,-]" representing the
  414. /// supported versions for a single protocol.
  415. ///
  416. /// # Returns
  417. ///
  418. /// A `bool` indicating whether the list contains a range, starting at the
  419. /// first in the list, and an `u32` of the last integer in the range.
  420. ///
  421. /// For example, if given vec![1, 2, 3, 5], find_range will return true,
  422. /// as there is a continuous range, and 3, which is the last number in the
  423. /// continuous range.
  424. ///
  425. fn find_range(list: &Vec<u32>) -> (bool, u32) {
  426. if list.len() == 0 {
  427. return (false, 0);
  428. }
  429. let mut iterable = list.iter().peekable();
  430. let mut range_end = match iterable.next() {
  431. Some(n) => *n,
  432. None => return (false, 0),
  433. };
  434. let mut has_range = false;
  435. while iterable.peek().is_some() {
  436. let n = *iterable.next().unwrap();
  437. if n != range_end + 1 {
  438. break;
  439. }
  440. has_range = true;
  441. range_end = n;
  442. }
  443. (has_range, range_end)
  444. }
  445. /// Contracts a HashSet representation of supported versions into a string.
  446. /// Helper for compute_vote
  447. ///
  448. /// # Inputs
  449. ///
  450. /// `supported_set`, a set of integers of "[0-9,-]" representing the
  451. /// supported versions for a single protocol.
  452. ///
  453. /// # Returns
  454. ///
  455. /// A `String` representation of this set in ascending order.
  456. ///
  457. fn contract_protocol_list<'a>(supported_set: &'a HashSet<Version>) -> String {
  458. let mut supported: Vec<Version> =
  459. supported_set.iter().map(|x| *x).collect();
  460. supported.sort();
  461. let mut final_output: Vec<String> = Vec::new();
  462. while supported.len() != 0 {
  463. let (has_range, end) = find_range(&supported);
  464. let current = supported.remove(0);
  465. if has_range {
  466. final_output.push(format!(
  467. "{}-{}",
  468. current.to_string(),
  469. &end.to_string(),
  470. ));
  471. supported.retain(|&x| x > end);
  472. } else {
  473. final_output.push(current.to_string());
  474. }
  475. }
  476. final_output.join(",")
  477. }
  478. /// Parses a protocol list without validating the protocol names
  479. ///
  480. /// # Inputs
  481. ///
  482. /// * `protocol_string`, a string comprised of keys and values, both which are
  483. /// strings. The keys are the protocol names while values are a string
  484. /// representation of the supported versions.
  485. ///
  486. /// The input is _not_ expected to be a subset of the Proto types
  487. ///
  488. /// # Returns
  489. ///
  490. /// A `Result` whose `Ok` value is a `HashSet<Version>` holding all of the
  491. /// unique version numbers.
  492. ///
  493. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  494. /// of the error.
  495. ///
  496. /// # Errors
  497. ///
  498. /// This function will error if:
  499. ///
  500. /// * The protocol string does not follow the "protocol_name=version_list"
  501. /// expected format
  502. /// * If the version string is malformed. See `Versions::from_version_string`.
  503. ///
  504. fn parse_protocols_from_string_with_no_validation<'a>(
  505. protocol_string: &'a str,
  506. ) -> Result<HashMap<String, Versions>, &'static str> {
  507. let mut parsed: HashMap<String, Versions> = HashMap::new();
  508. for subproto in protocol_string.split(" ") {
  509. let mut parts = subproto.splitn(2, "=");
  510. let name = match parts.next() {
  511. Some(n) => n,
  512. None => return Err("invalid protover entry"),
  513. };
  514. let vers = match parts.next() {
  515. Some(n) => n,
  516. None => return Err("invalid protover entry"),
  517. };
  518. let versions = Versions::from_version_string(vers)?;
  519. parsed.insert(String::from(name), versions);
  520. }
  521. Ok(parsed)
  522. }
  523. /// Protocol voting implementation.
  524. ///
  525. /// Given a list of strings describing protocol versions, return a new
  526. /// string encoding all of the protocols that are listed by at
  527. /// least threshold of the inputs.
  528. ///
  529. /// The string is sorted according to the following conventions:
  530. /// - Protocols names are alphabetized
  531. /// - Protocols are in order low to high
  532. /// - Individual and ranges are listed together. For example,
  533. /// "3, 5-10,13"
  534. /// - All entries are unique
  535. ///
  536. /// # Examples
  537. /// ```
  538. /// use protover::compute_vote;
  539. ///
  540. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  541. /// let vote = compute_vote(protos, 2);
  542. /// assert_eq!("Link=3", vote)
  543. /// ```
  544. pub fn compute_vote(
  545. list_of_proto_strings: Vec<String>,
  546. threshold: i32,
  547. ) -> String {
  548. let empty = String::from("");
  549. if list_of_proto_strings.is_empty() {
  550. return empty;
  551. }
  552. // all_count is a structure to represent the count of the number of
  553. // supported versions for a specific protocol. For example, in JSON format:
  554. // {
  555. // "FirstSupportedProtocol": {
  556. // "1": "3",
  557. // "2": "1"
  558. // }
  559. // }
  560. // means that FirstSupportedProtocol has three votes which support version
  561. // 1, and one vote that supports version 2
  562. let mut all_count: HashMap<String, HashMap<Version, usize>> =
  563. HashMap::new();
  564. // parse and collect all of the protos and their versions and collect them
  565. for vote in list_of_proto_strings {
  566. let this_vote: HashMap<String, Versions> =
  567. match parse_protocols_from_string_with_no_validation(&vote) {
  568. Ok(result) => result,
  569. Err(_) => continue,
  570. };
  571. for (protocol, versions) in this_vote {
  572. let supported_vers: &mut HashMap<Version, usize> =
  573. all_count.entry(protocol).or_insert(HashMap::new());
  574. for version in versions.0 {
  575. let counter: &mut usize =
  576. supported_vers.entry(version).or_insert(0);
  577. *counter += 1;
  578. }
  579. }
  580. }
  581. let mut final_output: HashMap<String, String> =
  582. HashMap::with_capacity(get_supported_protocols().split(" ").count());
  583. // Go through and remove verstions that are less than the threshold
  584. for (protocol, versions) in all_count {
  585. let mut meets_threshold = HashSet::new();
  586. for (version, count) in versions {
  587. if count >= threshold as usize {
  588. meets_threshold.insert(version);
  589. }
  590. }
  591. // For each protocol, compress its version list into the expected
  592. // protocol version string format
  593. let contracted = contract_protocol_list(&meets_threshold);
  594. if !contracted.is_empty() {
  595. final_output.insert(protocol, contracted);
  596. }
  597. }
  598. write_vote_to_string(&final_output)
  599. }
  600. /// Return a String comprised of protocol entries in alphabetical order
  601. ///
  602. /// # Inputs
  603. ///
  604. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  605. /// The keys are the protocol names while values are a string representation of
  606. /// the supported versions.
  607. ///
  608. /// # Returns
  609. ///
  610. /// A `String` whose value is series of pairs, comprising of the protocol name
  611. /// and versions that it supports. The string takes the following format:
  612. ///
  613. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  614. ///
  615. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  616. /// entry format.
  617. ///
  618. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  619. let mut keys: Vec<&String> = vote.keys().collect();
  620. keys.sort();
  621. let mut output = Vec::new();
  622. for key in keys {
  623. // TODO error in indexing here?
  624. output.push(format!("{}={}", key, vote[key]));
  625. }
  626. output.join(" ")
  627. }
  628. /// Returns a boolean indicating whether the given protocol and version is
  629. /// supported in any of the existing Tor protocols
  630. ///
  631. /// # Examples
  632. /// ```
  633. /// use protover::*;
  634. ///
  635. /// let is_supported = is_supported_here(Proto::Link, 10);
  636. /// assert_eq!(false, is_supported);
  637. ///
  638. /// let is_supported = is_supported_here(Proto::Link, 1);
  639. /// assert_eq!(true, is_supported);
  640. /// ```
  641. pub fn is_supported_here(proto: Proto, vers: Version) -> bool {
  642. let currently_supported = match SupportedProtocols::tor_supported() {
  643. Ok(result) => result.0,
  644. Err(_) => return false,
  645. };
  646. let supported_versions = match currently_supported.get(&proto) {
  647. Some(n) => n,
  648. None => return false,
  649. };
  650. supported_versions.0.contains(&vers)
  651. }
  652. /// Older versions of Tor cannot infer their own subprotocols
  653. /// Used to determine which subprotocols are supported by older Tor versions.
  654. ///
  655. /// # Inputs
  656. ///
  657. /// * `version`, a string comprised of "[0-9a-z.-]"
  658. ///
  659. /// # Returns
  660. ///
  661. /// A `&'static [u8]` encoding a list of protocol names and supported
  662. /// versions. The string takes the following format:
  663. ///
  664. /// "HSDir=1-1 LinkAuth=1"
  665. ///
  666. /// This function returns the protocols that are supported by the version input,
  667. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  668. ///
  669. /// C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  670. pub fn compute_for_old_tor(version: &str) -> &'static [u8] {
  671. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  672. return NUL_BYTE;
  673. }
  674. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  675. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  676. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  677. }
  678. if c_tor_version_as_new_as(version, "0.2.7.5") {
  679. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  680. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  681. }
  682. if c_tor_version_as_new_as(version, "0.2.4.19") {
  683. return b"Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  684. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2\0";
  685. }
  686. NUL_BYTE
  687. }
  688. #[cfg(test)]
  689. mod test {
  690. use super::Version;
  691. #[test]
  692. fn test_versions_from_version_string() {
  693. use std::collections::HashSet;
  694. use super::Versions;
  695. assert_eq!(Err("version string is empty"), Versions::from_version_string(""));
  696. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  697. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  698. {
  699. let mut versions: HashSet<Version> = HashSet::new();
  700. versions.insert(1);
  701. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  702. }
  703. {
  704. let mut versions: HashSet<Version> = HashSet::new();
  705. versions.insert(1);
  706. versions.insert(2);
  707. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  708. }
  709. {
  710. let mut versions: HashSet<Version> = HashSet::new();
  711. versions.insert(1);
  712. versions.insert(2);
  713. versions.insert(3);
  714. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  715. }
  716. {
  717. let mut versions: HashSet<Version> = HashSet::new();
  718. versions.insert(1);
  719. versions.insert(2);
  720. versions.insert(5);
  721. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  722. }
  723. {
  724. let mut versions: HashSet<Version> = HashSet::new();
  725. versions.insert(1);
  726. versions.insert(3);
  727. versions.insert(4);
  728. versions.insert(5);
  729. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  730. }
  731. }
  732. #[test]
  733. fn test_contains_only_supported_protocols() {
  734. use super::contains_only_supported_protocols;
  735. assert_eq!(false, contains_only_supported_protocols(""));
  736. assert_eq!(false, contains_only_supported_protocols("Cons="));
  737. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  738. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  739. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  740. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  741. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  742. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  743. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  744. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  745. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  746. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  747. }
  748. #[test]
  749. fn test_find_range() {
  750. use super::find_range;
  751. assert_eq!((false, 0), find_range(&vec![]));
  752. assert_eq!((false, 1), find_range(&vec![1]));
  753. assert_eq!((true, 2), find_range(&vec![1, 2]));
  754. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  755. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  756. }
  757. #[test]
  758. fn test_expand_version_range() {
  759. use super::expand_version_range;
  760. assert_eq!(Err("version string empty"), expand_version_range(""));
  761. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  762. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  763. assert_eq!(
  764. Err("cannot parse protocol range lower bound"),
  765. expand_version_range("a")
  766. );
  767. assert_eq!(
  768. Err("cannot parse protocol range upper bound"),
  769. expand_version_range("1-a")
  770. );
  771. }
  772. #[test]
  773. fn test_contract_protocol_list() {
  774. use std::collections::HashSet;
  775. use super::contract_protocol_list;
  776. {
  777. let mut versions = HashSet::<Version>::new();
  778. assert_eq!(String::from(""), contract_protocol_list(&versions));
  779. versions.insert(1);
  780. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  781. versions.insert(2);
  782. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  783. }
  784. {
  785. let mut versions = HashSet::<Version>::new();
  786. versions.insert(1);
  787. versions.insert(3);
  788. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  789. }
  790. {
  791. let mut versions = HashSet::<Version>::new();
  792. versions.insert(1);
  793. versions.insert(2);
  794. versions.insert(3);
  795. versions.insert(4);
  796. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  797. }
  798. {
  799. let mut versions = HashSet::<Version>::new();
  800. versions.insert(1);
  801. versions.insert(3);
  802. versions.insert(5);
  803. versions.insert(6);
  804. versions.insert(7);
  805. assert_eq!(
  806. String::from("1,3,5-7"),
  807. contract_protocol_list(&versions)
  808. );
  809. }
  810. {
  811. let mut versions = HashSet::<Version>::new();
  812. versions.insert(1);
  813. versions.insert(2);
  814. versions.insert(3);
  815. versions.insert(500);
  816. assert_eq!(
  817. String::from("1-3,500"),
  818. contract_protocol_list(&versions)
  819. );
  820. }
  821. }
  822. }