protover.rs 27 KB

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