protover.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. // Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. use external::c_tor_version_as_new_as;
  4. use std::str;
  5. use std::str::FromStr;
  6. use std::fmt;
  7. use std::collections::{HashMap, HashSet};
  8. use std::ops::Range;
  9. use std::string::String;
  10. /// The first version of Tor that included "proto" entries in its descriptors.
  11. /// Authorities should use this to decide whether to guess proto lines.
  12. ///
  13. /// C_RUST_COUPLED:
  14. /// src/or/protover.h `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`
  15. const FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS: &'static str = "0.2.9.3-alpha";
  16. /// The maximum number of subprotocol version numbers we will attempt to expand
  17. /// before concluding that someone is trying to DoS us
  18. ///
  19. /// C_RUST_COUPLED: src/or/protover.c `MAX_PROTOCOLS_TO_EXPAND`
  20. const MAX_PROTOCOLS_TO_EXPAND: u32 = 500;
  21. /// Currently supported protocols and their versions, as a byte-slice.
  22. ///
  23. /// # Warning
  24. ///
  25. /// This byte-slice ends in a NUL byte. This is so that we can directly convert
  26. /// it to an `&'static CStr` in the FFI code, in order to hand the static string
  27. /// to C in a way that is compatible with C static strings.
  28. ///
  29. /// Rust code which wishes to accesses this string should use
  30. /// `protover::get_supported_protocols()` instead.
  31. ///
  32. /// C_RUST_COUPLED: src/or/protover.c `protover_get_supported_protocols`
  33. pub(crate) const SUPPORTED_PROTOCOLS: &'static [u8] =
  34. b"Cons=1-2 \
  35. Desc=1-2 \
  36. DirCache=1-2 \
  37. HSDir=1-2 \
  38. HSIntro=3-4 \
  39. HSRend=1-2 \
  40. Link=1-5 \
  41. LinkAuth=1,3 \
  42. Microdesc=1-2 \
  43. Relay=1-2\0";
  44. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  45. ///
  46. /// C_RUST_COUPLED: src/or/protover.h `protocol_type_t`
  47. #[derive(Hash, Eq, PartialEq, Debug)]
  48. pub enum Proto {
  49. Cons,
  50. Desc,
  51. DirCache,
  52. HSDir,
  53. HSIntro,
  54. HSRend,
  55. Link,
  56. LinkAuth,
  57. Microdesc,
  58. Relay,
  59. }
  60. impl fmt::Display for Proto {
  61. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  62. write!(f, "{:?}", self)
  63. }
  64. }
  65. /// Translates a string representation of a protocol into a Proto type.
  66. /// Error if the string is an unrecognized protocol name.
  67. ///
  68. /// C_RUST_COUPLED: src/or/protover.c `PROTOCOL_NAMES`
  69. impl FromStr for Proto {
  70. type Err = &'static str;
  71. fn from_str(s: &str) -> Result<Self, Self::Err> {
  72. match s {
  73. "Cons" => Ok(Proto::Cons),
  74. "Desc" => Ok(Proto::Desc),
  75. "DirCache" => Ok(Proto::DirCache),
  76. "HSDir" => Ok(Proto::HSDir),
  77. "HSIntro" => Ok(Proto::HSIntro),
  78. "HSRend" => Ok(Proto::HSRend),
  79. "Link" => Ok(Proto::Link),
  80. "LinkAuth" => Ok(Proto::LinkAuth),
  81. "Microdesc" => Ok(Proto::Microdesc),
  82. "Relay" => Ok(Proto::Relay),
  83. _ => Err("Not a valid protocol type"),
  84. }
  85. }
  86. }
  87. /// Get the string representation of current supported protocols
  88. ///
  89. /// # Returns
  90. ///
  91. /// A `String` whose value is the existing protocols supported by tor.
  92. /// Returned data is in the format as follows:
  93. ///
  94. /// "HSDir=1-1 LinkAuth=1"
  95. ///
  96. pub fn get_supported_protocols() -> &'static str {
  97. unsafe {
  98. // The `len() - 1` is to remove the NUL byte.
  99. str::from_utf8_unchecked(&SUPPORTED_PROTOCOLS[..SUPPORTED_PROTOCOLS.len() - 1])
  100. }
  101. }
  102. /// Translates a vector representation of a protocol list into a HashMap
  103. fn parse_protocols<P, S>(
  104. protocols: P,
  105. ) -> Result<HashMap<Proto, HashSet<u32>>, &'static str>
  106. where
  107. P: Iterator<Item = S>,
  108. S: AsRef<str>,
  109. {
  110. let mut parsed = HashMap::new();
  111. for subproto in protocols {
  112. let (name, version) = get_proto_and_vers(subproto.as_ref())?;
  113. parsed.insert(name, version);
  114. }
  115. Ok(parsed)
  116. }
  117. /// Translates a string representation of a protocol list to a HashMap
  118. fn parse_protocols_from_string<'a>(
  119. protocol_string: &'a str,
  120. ) -> Result<HashMap<Proto, HashSet<u32>>, &'static str> {
  121. parse_protocols(protocol_string.split(" "))
  122. }
  123. /// Translates supported tor versions from a string into a HashMap, which is
  124. /// useful when looking up a specific subprotocol.
  125. ///
  126. /// # Returns
  127. ///
  128. /// A `Result` whose `Ok` value is a `HashMap<Proto, <u32>>` holding all
  129. /// subprotocols and versions currently supported by tor.
  130. ///
  131. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  132. /// of the error.
  133. ///
  134. fn tor_supported() -> Result<HashMap<Proto, HashSet<u32>>, &'static str> {
  135. parse_protocols(get_supported_protocols().split(" "))
  136. }
  137. /// Get the unique version numbers supported by a subprotocol.
  138. ///
  139. /// # Inputs
  140. ///
  141. /// * `version_string`, a string comprised of "[0-9,-]"
  142. ///
  143. /// # Returns
  144. ///
  145. /// A `Result` whose `Ok` value is a `HashSet<u32>` holding all of the unique
  146. /// version numbers. If there were ranges in the `version_string`, then these
  147. /// are expanded, i.e. `"1-3"` would expand to `HashSet<u32>::new([1, 2, 3])`.
  148. /// The returned HashSet is *unordered*.
  149. ///
  150. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  151. /// of the error.
  152. ///
  153. /// # Errors
  154. ///
  155. /// This function will error if:
  156. ///
  157. /// * the `version_string` is empty or contains an equals (`"="`) sign,
  158. /// * the expansion of a version range produces an error (see
  159. /// `expand_version_range`),
  160. /// * any single version number is not parseable as an `u32` in radix 10, or
  161. /// * there are greater than 2^16 version numbers to expand.
  162. ///
  163. fn get_versions(version_string: &str) -> Result<HashSet<u32>, &'static str> {
  164. if version_string.is_empty() {
  165. return Err("version string is empty");
  166. }
  167. let mut versions = HashSet::<u32>::new();
  168. for piece in version_string.split(",") {
  169. if piece.contains("-") {
  170. for p in expand_version_range(piece)? {
  171. versions.insert(p);
  172. }
  173. } else {
  174. versions.insert(u32::from_str(piece).or(
  175. Err("invalid protocol entry"),
  176. )?);
  177. }
  178. if versions.len() > MAX_PROTOCOLS_TO_EXPAND as usize {
  179. return Err("Too many versions to expand");
  180. }
  181. }
  182. Ok(versions)
  183. }
  184. /// Parse the subprotocol type and its version numbers.
  185. ///
  186. /// # Inputs
  187. ///
  188. /// * A `protocol_entry` string, comprised of a keyword, an "=" sign, and one
  189. /// or more version numbers.
  190. ///
  191. /// # Returns
  192. ///
  193. /// A `Result` whose `Ok` value is a tuple of `(Proto, HashSet<u32>)`, where the
  194. /// first element is the subprotocol type (see `protover::Proto`) and the last
  195. /// element is a(n unordered) set of unique version numbers which are supported.
  196. /// Otherwise, the `Err` value of this `Result` is a description of the error
  197. ///
  198. fn get_proto_and_vers<'a>(
  199. protocol_entry: &'a str,
  200. ) -> Result<(Proto, HashSet<u32>), &'static str> {
  201. let mut parts = protocol_entry.splitn(2, "=");
  202. let proto = match parts.next() {
  203. Some(n) => n,
  204. None => return Err("invalid protover entry"),
  205. };
  206. let vers = match parts.next() {
  207. Some(n) => n,
  208. None => return Err("invalid protover entry"),
  209. };
  210. let versions = get_versions(vers)?;
  211. let proto_name = proto.parse()?;
  212. Ok((proto_name, versions))
  213. }
  214. /// Parses a single subprotocol entry string into subprotocol and version
  215. /// parts, and then checks whether any of those versions are unsupported.
  216. /// Helper for protover::all_supported
  217. ///
  218. /// # Inputs
  219. ///
  220. /// Accepted data is in the string format as follows:
  221. ///
  222. /// "HSDir=1-1"
  223. ///
  224. /// # Returns
  225. ///
  226. /// Returns `true` if the protocol entry is well-formatted and only contains
  227. /// versions that are also supported in tor. Otherwise, returns false
  228. ///
  229. fn contains_only_supported_protocols(proto_entry: &str) -> bool {
  230. let (name, mut vers) = match get_proto_and_vers(proto_entry) {
  231. Ok(n) => n,
  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<Range<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)
  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 mut parsed: HashMap<String, HashSet<u32>> = HashMap::new();
  498. for subproto in protocol_string.split(" ") {
  499. let mut parts = subproto.splitn(2, "=");
  500. let name = match parts.next() {
  501. Some(n) => n,
  502. None => return Err("invalid protover entry"),
  503. };
  504. let vers = match parts.next() {
  505. Some(n) => n,
  506. None => return Err("invalid protover entry"),
  507. };
  508. let versions = get_versions(vers)?;
  509. parsed.insert(String::from(name), versions);
  510. }
  511. Ok(parsed)
  512. }
  513. /// Protocol voting implementation.
  514. ///
  515. /// Given a list of strings describing protocol versions, return a new
  516. /// string encoding all of the protocols that are listed by at
  517. /// least threshold of the inputs.
  518. ///
  519. /// The string is sorted according to the following conventions:
  520. /// - Protocols names are alphabetized
  521. /// - Protocols are in order low to high
  522. /// - Individual and ranges are listed together. For example,
  523. /// "3, 5-10,13"
  524. /// - All entries are unique
  525. ///
  526. /// # Examples
  527. /// ```
  528. /// use protover::compute_vote;
  529. ///
  530. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  531. /// let vote = compute_vote(protos, 2);
  532. /// assert_eq!("Link=3", vote)
  533. /// ```
  534. pub fn compute_vote(
  535. list_of_proto_strings: Vec<String>,
  536. threshold: i32,
  537. ) -> String {
  538. let empty = String::from("");
  539. if list_of_proto_strings.is_empty() {
  540. return empty;
  541. }
  542. // all_count is a structure to represent the count of the number of
  543. // supported versions for a specific protocol. For example, in JSON format:
  544. // {
  545. // "FirstSupportedProtocol": {
  546. // "1": "3",
  547. // "2": "1"
  548. // }
  549. // }
  550. // means that FirstSupportedProtocol has three votes which support version
  551. // 1, and one vote that supports version 2
  552. let mut all_count: HashMap<String, HashMap<u32, usize>> = HashMap::new();
  553. // parse and collect all of the protos and their versions and collect them
  554. for vote in list_of_proto_strings {
  555. let this_vote: HashMap<String, HashSet<u32>> =
  556. match parse_protocols_from_string_with_no_validation(&vote) {
  557. Ok(result) => result,
  558. Err(_) => continue,
  559. };
  560. for (protocol, versions) in this_vote {
  561. let supported_vers: &mut HashMap<u32, usize> =
  562. all_count.entry(protocol).or_insert(HashMap::new());
  563. for version in versions {
  564. let counter: &mut usize =
  565. supported_vers.entry(version).or_insert(0);
  566. *counter += 1;
  567. }
  568. }
  569. }
  570. let mut final_output: HashMap<String, String> =
  571. HashMap::with_capacity(get_supported_protocols().split(" ").count());
  572. // Go through and remove verstions that are less than the threshold
  573. for (protocol, versions) in all_count {
  574. let mut meets_threshold = HashSet::new();
  575. for (version, count) in versions {
  576. if count >= threshold as usize {
  577. meets_threshold.insert(version);
  578. }
  579. }
  580. // For each protocol, compress its version list into the expected
  581. // protocol version string format
  582. let contracted = contract_protocol_list(&meets_threshold);
  583. if !contracted.is_empty() {
  584. final_output.insert(protocol, contracted);
  585. }
  586. }
  587. write_vote_to_string(&final_output)
  588. }
  589. /// Return a String comprised of protocol entries in alphabetical order
  590. ///
  591. /// # Inputs
  592. ///
  593. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  594. /// The keys are the protocol names while values are a string representation of
  595. /// the supported versions.
  596. ///
  597. /// # Returns
  598. ///
  599. /// A `String` whose value is series of pairs, comprising of the protocol name
  600. /// and versions that it supports. The string takes the following format:
  601. ///
  602. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  603. ///
  604. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  605. /// entry format.
  606. ///
  607. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  608. let mut keys: Vec<&String> = vote.keys().collect();
  609. keys.sort();
  610. let mut output = Vec::new();
  611. for key in keys {
  612. // TODO error in indexing here?
  613. output.push(format!("{}={}", key, vote[key]));
  614. }
  615. output.join(" ")
  616. }
  617. /// Returns a boolean indicating whether the given protocol and version is
  618. /// supported in any of the existing Tor protocols
  619. ///
  620. /// # Examples
  621. /// ```
  622. /// use protover::*;
  623. ///
  624. /// let is_supported = is_supported_here(Proto::Link, 10);
  625. /// assert_eq!(false, is_supported);
  626. ///
  627. /// let is_supported = is_supported_here(Proto::Link, 1);
  628. /// assert_eq!(true, is_supported);
  629. /// ```
  630. pub fn is_supported_here(proto: Proto, vers: u32) -> bool {
  631. let currently_supported: HashMap<Proto, HashSet<u32>>;
  632. match tor_supported() {
  633. Ok(result) => currently_supported = result,
  634. Err(_) => return false,
  635. }
  636. let supported_versions = match currently_supported.get(&proto) {
  637. Some(n) => n,
  638. None => return false,
  639. };
  640. supported_versions.contains(&vers)
  641. }
  642. /// Older versions of Tor cannot infer their own subprotocols
  643. /// Used to determine which subprotocols are supported by older Tor versions.
  644. ///
  645. /// # Inputs
  646. ///
  647. /// * `version`, a string comprised of "[0-9,-]"
  648. ///
  649. /// # Returns
  650. ///
  651. /// A `String` whose value is series of pairs, comprising of the protocol name
  652. /// and versions that it supports. The string takes the following format:
  653. ///
  654. /// "HSDir=1-1 LinkAuth=1"
  655. ///
  656. /// This function returns the protocols that are supported by the version input,
  657. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  658. ///
  659. /// C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  660. pub fn compute_for_old_tor(version: &str) -> String {
  661. if c_tor_version_as_new_as(
  662. version,
  663. FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS,
  664. )
  665. {
  666. return String::new();
  667. }
  668. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  669. let ret = "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  670. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2";
  671. return String::from(ret);
  672. }
  673. if c_tor_version_as_new_as(version, "0.2.7.5") {
  674. let ret = "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  675. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2";
  676. return String::from(ret);
  677. }
  678. if c_tor_version_as_new_as(version, "0.2.4.19") {
  679. let ret = "Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  680. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2";
  681. return String::from(ret);
  682. }
  683. String::new()
  684. }
  685. #[cfg(test)]
  686. mod test {
  687. #[test]
  688. fn test_get_versions() {
  689. use std::collections::HashSet;
  690. use super::get_versions;
  691. assert_eq!(Err("version string is empty"), get_versions(""));
  692. assert_eq!(Err("invalid protocol entry"), get_versions("a,b"));
  693. assert_eq!(Err("invalid protocol entry"), get_versions("1,!"));
  694. {
  695. let mut versions: HashSet<u32> = HashSet::new();
  696. versions.insert(1);
  697. assert_eq!(Ok(versions), get_versions("1"));
  698. }
  699. {
  700. let mut versions: HashSet<u32> = HashSet::new();
  701. versions.insert(1);
  702. versions.insert(2);
  703. assert_eq!(Ok(versions), get_versions("1,2"));
  704. }
  705. {
  706. let mut versions: HashSet<u32> = HashSet::new();
  707. versions.insert(1);
  708. versions.insert(2);
  709. versions.insert(3);
  710. assert_eq!(Ok(versions), get_versions("1-3"));
  711. }
  712. {
  713. let mut versions: HashSet<u32> = HashSet::new();
  714. versions.insert(1);
  715. versions.insert(2);
  716. versions.insert(5);
  717. assert_eq!(Ok(versions), get_versions("1-2,5"));
  718. }
  719. {
  720. let mut versions: HashSet<u32> = HashSet::new();
  721. versions.insert(1);
  722. versions.insert(3);
  723. versions.insert(4);
  724. versions.insert(5);
  725. assert_eq!(Ok(versions), get_versions("1,3-5"));
  726. }
  727. }
  728. #[test]
  729. fn test_contains_only_supported_protocols() {
  730. use super::contains_only_supported_protocols;
  731. assert_eq!(false, contains_only_supported_protocols(""));
  732. assert_eq!(false, contains_only_supported_protocols("Cons="));
  733. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  734. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  735. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  736. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  737. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  738. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  739. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  740. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  741. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  742. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  743. }
  744. #[test]
  745. fn test_find_range() {
  746. use super::find_range;
  747. assert_eq!((false, 0), find_range(&vec![]));
  748. assert_eq!((false, 1), find_range(&vec![1]));
  749. assert_eq!((true, 2), find_range(&vec![1, 2]));
  750. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  751. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  752. }
  753. #[test]
  754. fn test_expand_version_range() {
  755. use super::expand_version_range;
  756. assert_eq!(Err("version string empty"), expand_version_range(""));
  757. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  758. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  759. assert_eq!(
  760. Err("cannot parse protocol range lower bound"),
  761. expand_version_range("a")
  762. );
  763. assert_eq!(
  764. Err("cannot parse protocol range upper bound"),
  765. expand_version_range("1-a")
  766. );
  767. }
  768. #[test]
  769. fn test_contract_protocol_list() {
  770. use std::collections::HashSet;
  771. use super::contract_protocol_list;
  772. {
  773. let mut versions = HashSet::<u32>::new();
  774. assert_eq!(String::from(""), contract_protocol_list(&versions));
  775. versions.insert(1);
  776. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  777. versions.insert(2);
  778. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  779. }
  780. {
  781. let mut versions = HashSet::<u32>::new();
  782. versions.insert(1);
  783. versions.insert(3);
  784. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  785. }
  786. {
  787. let mut versions = HashSet::<u32>::new();
  788. versions.insert(1);
  789. versions.insert(2);
  790. versions.insert(3);
  791. versions.insert(4);
  792. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  793. }
  794. {
  795. let mut versions = HashSet::<u32>::new();
  796. versions.insert(1);
  797. versions.insert(3);
  798. versions.insert(5);
  799. versions.insert(6);
  800. versions.insert(7);
  801. assert_eq!(
  802. String::from("1,3,5-7"),
  803. contract_protocol_list(&versions)
  804. );
  805. }
  806. {
  807. let mut versions = HashSet::<u32>::new();
  808. versions.insert(1);
  809. versions.insert(2);
  810. versions.insert(3);
  811. versions.insert(500);
  812. assert_eq!(
  813. String::from("1-3,500"),
  814. contract_protocol_list(&versions)
  815. );
  816. }
  817. }
  818. }