protover.rs 29 KB

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