protover.rs 29 KB

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