protover.rs 28 KB

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