protover.rs 28 KB

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