protover.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. // Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. use std::collections::HashMap;
  4. use std::collections::hash_map;
  5. use std::ffi::CStr;
  6. use std::fmt;
  7. use std::str;
  8. use std::str::FromStr;
  9. use std::string::String;
  10. use external::c_tor_version_as_new_as;
  11. use errors::ProtoverError;
  12. use protoset::Version;
  13. use protoset::ProtoSet;
  14. /// The first version of Tor that included "proto" entries in its descriptors.
  15. /// Authorities should use this to decide whether to guess proto lines.
  16. ///
  17. /// C_RUST_COUPLED:
  18. /// src/or/protover.h `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`
  19. const FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS: &'static str = "0.2.9.3-alpha";
  20. /// The maximum number of subprotocol version numbers we will attempt to expand
  21. /// before concluding that someone is trying to DoS us
  22. ///
  23. /// C_RUST_COUPLED: src/or/protover.c `MAX_PROTOCOLS_TO_EXPAND`
  24. pub(crate) const MAX_PROTOCOLS_TO_EXPAND: usize = (1<<16);
  25. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  26. ///
  27. /// C_RUST_COUPLED: src/or/protover.h `protocol_type_t`
  28. #[derive(Clone, Hash, Eq, PartialEq, Debug)]
  29. pub enum Protocol {
  30. Cons,
  31. Desc,
  32. DirCache,
  33. HSDir,
  34. HSIntro,
  35. HSRend,
  36. Link,
  37. LinkAuth,
  38. Microdesc,
  39. Relay,
  40. }
  41. impl fmt::Display for Protocol {
  42. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  43. write!(f, "{:?}", self)
  44. }
  45. }
  46. /// Translates a string representation of a protocol into a Proto type.
  47. /// Error if the string is an unrecognized protocol name.
  48. ///
  49. /// C_RUST_COUPLED: src/or/protover.c `PROTOCOL_NAMES`
  50. impl FromStr for Protocol {
  51. type Err = ProtoverError;
  52. fn from_str(s: &str) -> Result<Self, Self::Err> {
  53. match s {
  54. "Cons" => Ok(Protocol::Cons),
  55. "Desc" => Ok(Protocol::Desc),
  56. "DirCache" => Ok(Protocol::DirCache),
  57. "HSDir" => Ok(Protocol::HSDir),
  58. "HSIntro" => Ok(Protocol::HSIntro),
  59. "HSRend" => Ok(Protocol::HSRend),
  60. "Link" => Ok(Protocol::Link),
  61. "LinkAuth" => Ok(Protocol::LinkAuth),
  62. "Microdesc" => Ok(Protocol::Microdesc),
  63. "Relay" => Ok(Protocol::Relay),
  64. _ => Err(ProtoverError::UnknownProtocol),
  65. }
  66. }
  67. }
  68. /// A protocol string which is not one of the `Protocols` we currently know
  69. /// about.
  70. #[derive(Clone, Debug, Hash, Eq, PartialEq)]
  71. pub struct UnknownProtocol(String);
  72. impl fmt::Display for UnknownProtocol {
  73. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  74. write!(f, "{}", self.0)
  75. }
  76. }
  77. impl FromStr for UnknownProtocol {
  78. type Err = ProtoverError;
  79. fn from_str(s: &str) -> Result<Self, Self::Err> {
  80. Ok(UnknownProtocol(s.to_string()))
  81. }
  82. }
  83. impl From<Protocol> for UnknownProtocol {
  84. fn from(p: Protocol) -> UnknownProtocol {
  85. UnknownProtocol(p.to_string())
  86. }
  87. }
  88. /// Get a CStr representation of current supported protocols, for
  89. /// passing to C, or for converting to a `&str` for Rust.
  90. ///
  91. /// # Returns
  92. ///
  93. /// An `&'static CStr` whose value is the existing protocols supported by tor.
  94. /// Returned data is in the format as follows:
  95. ///
  96. /// "HSDir=1-1 LinkAuth=1"
  97. ///
  98. /// # Note
  99. ///
  100. /// Rust code can use the `&'static CStr` as a normal `&'a str` by
  101. /// calling `protover::get_supported_protocols`.
  102. ///
  103. // C_RUST_COUPLED: src/or/protover.c `protover_get_supported_protocols`
  104. pub(crate) fn get_supported_protocols_cstr() -> &'static CStr {
  105. cstr!("Cons=1-2 \
  106. Desc=1-2 \
  107. DirCache=1-2 \
  108. HSDir=1-2 \
  109. HSIntro=3-4 \
  110. HSRend=1-2 \
  111. Link=1-5 \
  112. LinkAuth=1,3 \
  113. Microdesc=1-2 \
  114. Relay=1-2")
  115. }
  116. /// A map of protocol names to the versions of them which are supported.
  117. #[derive(Clone, Debug, PartialEq, Eq)]
  118. pub struct ProtoEntry(HashMap<Protocol, ProtoSet>);
  119. impl Default for ProtoEntry {
  120. fn default() -> ProtoEntry {
  121. ProtoEntry( HashMap::new() )
  122. }
  123. }
  124. impl ProtoEntry {
  125. /// Get an iterator over the `Protocol`s and their `ProtoSet`s in this `ProtoEntry`.
  126. pub fn iter(&self) -> hash_map::Iter<Protocol, ProtoSet> {
  127. self.0.iter()
  128. }
  129. /// Translate the supported tor versions from a string into a
  130. /// ProtoEntry, which is useful when looking up a specific
  131. /// subprotocol.
  132. pub fn supported() -> Result<Self, ProtoverError> {
  133. let supported_cstr: &'static CStr = get_supported_protocols_cstr();
  134. let supported: &str = supported_cstr.to_str().unwrap_or("");
  135. supported.parse()
  136. }
  137. pub fn get(&self, protocol: &Protocol) -> Option<&ProtoSet> {
  138. self.0.get(protocol)
  139. }
  140. pub fn insert(&mut self, key: Protocol, value: ProtoSet) {
  141. self.0.insert(key, value);
  142. }
  143. pub fn remove(&mut self, key: &Protocol) -> Option<ProtoSet> {
  144. self.0.remove(key)
  145. }
  146. pub fn is_empty(&self) -> bool {
  147. self.0.is_empty()
  148. }
  149. }
  150. impl FromStr for ProtoEntry {
  151. type Err = ProtoverError;
  152. /// Parse a string of subprotocol types and their version numbers.
  153. ///
  154. /// # Inputs
  155. ///
  156. /// * A `protocol_entry` string, comprised of a keywords, an "=" sign, and
  157. /// one or more version numbers, each separated by a space. For example,
  158. /// `"Cons=3-4 HSDir=1"`.
  159. ///
  160. /// # Returns
  161. ///
  162. /// A `Result` whose `Ok` value is a `ProtoEntry`, where the
  163. /// first element is the subprotocol type (see `protover::Protocol`) and the last
  164. /// element is an ordered set of `(low, high)` unique version numbers which are supported.
  165. /// Otherwise, the `Err` value of this `Result` is a `ProtoverError`.
  166. fn from_str(protocol_entry: &str) -> Result<ProtoEntry, ProtoverError> {
  167. let mut proto_entry: ProtoEntry = ProtoEntry::default();
  168. let entries = protocol_entry.split(' ');
  169. for entry in entries {
  170. let mut parts = entry.splitn(2, '=');
  171. let proto = match parts.next() {
  172. Some(n) => n,
  173. None => return Err(ProtoverError::Unparseable),
  174. };
  175. let vers = match parts.next() {
  176. Some(n) => n,
  177. None => return Err(ProtoverError::Unparseable),
  178. };
  179. let versions: ProtoSet = vers.parse()?;
  180. let proto_name: Protocol = proto.parse()?;
  181. proto_entry.insert(proto_name, versions);
  182. }
  183. Ok(proto_entry)
  184. }
  185. }
  186. /// Generate an implementation of `ToString` for either a `ProtoEntry` or an
  187. /// `UnvalidatedProtoEntry`.
  188. macro_rules! impl_to_string_for_proto_entry {
  189. ($t:ty) => (
  190. impl ToString for $t {
  191. fn to_string(&self) -> String {
  192. let mut parts: Vec<String> = Vec::new();
  193. for (protocol, versions) in self.iter() {
  194. parts.push(format!("{}={}", protocol.to_string(), versions.to_string()));
  195. }
  196. parts.sort_unstable();
  197. parts.join(" ")
  198. }
  199. }
  200. )
  201. }
  202. impl_to_string_for_proto_entry!(ProtoEntry);
  203. impl_to_string_for_proto_entry!(UnvalidatedProtoEntry);
  204. /// A `ProtoEntry`, but whose `Protocols` can be any `UnknownProtocol`, not just
  205. /// the supported ones enumerated in `Protocols`. The protocol versions are
  206. /// validated, however.
  207. #[derive(Clone, Debug, PartialEq, Eq)]
  208. pub struct UnvalidatedProtoEntry(HashMap<UnknownProtocol, ProtoSet>);
  209. impl Default for UnvalidatedProtoEntry {
  210. fn default() -> UnvalidatedProtoEntry {
  211. UnvalidatedProtoEntry( HashMap::new() )
  212. }
  213. }
  214. impl UnvalidatedProtoEntry {
  215. /// Get an iterator over the `Protocol`s and their `ProtoSet`s in this `ProtoEntry`.
  216. pub fn iter(&self) -> hash_map::Iter<UnknownProtocol, ProtoSet> {
  217. self.0.iter()
  218. }
  219. pub fn get(&self, protocol: &UnknownProtocol) -> Option<&ProtoSet> {
  220. self.0.get(protocol)
  221. }
  222. pub fn insert(&mut self, key: UnknownProtocol, value: ProtoSet) {
  223. self.0.insert(key, value);
  224. }
  225. pub fn remove(&mut self, key: &UnknownProtocol) -> Option<ProtoSet> {
  226. self.0.remove(key)
  227. }
  228. pub fn is_empty(&self) -> bool {
  229. self.0.is_empty()
  230. }
  231. /// Determine if we support every protocol a client supports, and if not,
  232. /// determine which protocols we do not have support for.
  233. ///
  234. /// # Returns
  235. ///
  236. /// Optionally, return parameters which the client supports but which we do not.
  237. ///
  238. /// # Examples
  239. /// ```
  240. /// use protover::UnvalidatedProtoEntry;
  241. ///
  242. /// let protocols: UnvalidatedProtoEntry = "LinkAuth=1 Microdesc=1-2 Relay=2".parse().unwrap();
  243. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  244. /// assert_eq!(true, unsupported.is_none());
  245. ///
  246. /// let protocols: UnvalidatedProtoEntry = "Link=1-2 Wombat=9".parse().unwrap();
  247. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  248. /// assert_eq!(true, unsupported.is_some());
  249. /// assert_eq!("Wombat=9", &unsupported.unwrap().to_string());
  250. /// ```
  251. pub fn all_supported(&self) -> Option<UnvalidatedProtoEntry> {
  252. let mut unsupported: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  253. let supported: ProtoEntry = match ProtoEntry::supported() {
  254. Ok(x) => x,
  255. Err(_) => return None,
  256. };
  257. for (protocol, versions) in self.iter() {
  258. let is_supported: Result<Protocol, ProtoverError> = protocol.0.parse();
  259. let supported_protocol: Protocol;
  260. // If the protocol wasn't even in the enum, then we definitely don't
  261. // know about it and don't support any of its versions.
  262. if is_supported.is_err() {
  263. if !versions.is_empty() {
  264. unsupported.insert(protocol.clone(), versions.clone());
  265. }
  266. continue;
  267. } else {
  268. supported_protocol = is_supported.unwrap();
  269. }
  270. let maybe_supported_versions: Option<&ProtoSet> = supported.get(&supported_protocol);
  271. let supported_versions: &ProtoSet;
  272. let mut unsupported_versions: ProtoSet;
  273. // If the protocol wasn't in the map, then we don't know about it
  274. // and don't support any of its versions. Add its versions to the
  275. // map (if it has versions).
  276. if maybe_supported_versions.is_none() {
  277. if !versions.is_empty() {
  278. unsupported.insert(protocol.clone(), versions.clone());
  279. }
  280. continue;
  281. } else {
  282. supported_versions = maybe_supported_versions.unwrap();
  283. }
  284. unsupported_versions = versions.clone();
  285. unsupported_versions.retain(|x| !supported_versions.contains(x));
  286. if !unsupported_versions.is_empty() {
  287. unsupported.insert(protocol.clone(), unsupported_versions);
  288. }
  289. }
  290. if unsupported.is_empty() {
  291. return None;
  292. }
  293. Some(unsupported)
  294. }
  295. /// Determine if we have support for some protocol and version.
  296. ///
  297. /// # Inputs
  298. ///
  299. /// * `proto`, an `UnknownProtocol` to test support for
  300. /// * `vers`, a `Version` which we will go on to determine whether the
  301. /// specified protocol supports.
  302. ///
  303. /// # Return
  304. ///
  305. /// Returns `true` iff this `UnvalidatedProtoEntry` includes support for the
  306. /// indicated protocol and version, and `false` otherwise.
  307. ///
  308. /// # Examples
  309. ///
  310. /// ```
  311. /// # use std::str::FromStr;
  312. /// use protover::*;
  313. /// # use protover::errors::ProtoverError;
  314. ///
  315. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  316. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=1 Doggo=3-5".parse()?;
  317. /// assert_eq!(true, proto.supports_protocol(&Protocol::Cons.into(), &1));
  318. /// assert_eq!(false, proto.supports_protocol(&Protocol::Cons.into(), &5));
  319. /// assert_eq!(true, proto.supports_protocol(&UnknownProtocol::from_str("Doggo")?, &4));
  320. /// # Ok(proto)
  321. /// # } fn main () { do_test(); }
  322. /// ```
  323. pub fn supports_protocol(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  324. let supported_versions: &ProtoSet = match self.get(proto) {
  325. Some(n) => n,
  326. None => return false,
  327. };
  328. supported_versions.contains(&vers)
  329. }
  330. /// As `UnvalidatedProtoEntry::supports_protocol()`, but also returns `true`
  331. /// if any later version of the protocol is supported.
  332. ///
  333. /// # Examples
  334. /// ```
  335. /// use protover::*;
  336. /// # use protover::errors::ProtoverError;
  337. ///
  338. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  339. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=5".parse()?;
  340. ///
  341. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &5));
  342. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &4));
  343. /// assert_eq!(false, proto.supports_protocol_or_later(&Protocol::Cons.into(), &6));
  344. /// # Ok(proto)
  345. /// # } fn main () { do_test(); }
  346. /// ```
  347. pub fn supports_protocol_or_later(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  348. let supported_versions: &ProtoSet = match self.get(&proto) {
  349. Some(n) => n,
  350. None => return false,
  351. };
  352. supported_versions.iter().any(|v| v.1 >= *vers)
  353. }
  354. }
  355. impl FromStr for UnvalidatedProtoEntry {
  356. type Err = ProtoverError;
  357. /// Parses a protocol list without validating the protocol names.
  358. ///
  359. /// # Inputs
  360. ///
  361. /// * `protocol_string`, a string comprised of keys and values, both which are
  362. /// strings. The keys are the protocol names while values are a string
  363. /// representation of the supported versions.
  364. ///
  365. /// The input is _not_ expected to be a subset of the Protocol types
  366. ///
  367. /// # Returns
  368. ///
  369. /// A `Result` whose `Ok` value is a `ProtoSet` holding all of the
  370. /// unique version numbers.
  371. ///
  372. /// The returned `Result`'s `Err` value is an `ProtoverError` whose `Display`
  373. /// impl has a description of the error.
  374. ///
  375. /// # Errors
  376. ///
  377. /// This function will error if:
  378. ///
  379. /// * The protocol string does not follow the "protocol_name=version_list"
  380. /// expected format, or
  381. /// * If the version string is malformed. See `impl FromStr for ProtoSet`.
  382. fn from_str(protocol_string: &str) -> Result<UnvalidatedProtoEntry, ProtoverError> {
  383. let mut parsed: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  384. for subproto in protocol_string.split(' ') {
  385. let mut parts = subproto.splitn(2, '=');
  386. let name = match parts.next() {
  387. Some("") => return Err(ProtoverError::Unparseable),
  388. Some(n) => n,
  389. None => return Err(ProtoverError::Unparseable),
  390. };
  391. let vers = match parts.next() {
  392. Some(n) => n,
  393. None => return Err(ProtoverError::Unparseable),
  394. };
  395. let versions = ProtoSet::from_str(vers)?;
  396. let protocol = UnknownProtocol::from_str(name)?;
  397. parsed.insert(protocol, versions);
  398. }
  399. Ok(parsed)
  400. }
  401. }
  402. /// Pretend a `ProtoEntry` is actually an `UnvalidatedProtoEntry`.
  403. impl From<ProtoEntry> for UnvalidatedProtoEntry {
  404. fn from(proto_entry: ProtoEntry) -> UnvalidatedProtoEntry {
  405. let mut unvalidated: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  406. for (protocol, versions) in proto_entry.iter() {
  407. unvalidated.insert(UnknownProtocol::from(protocol.clone()), versions.clone());
  408. }
  409. unvalidated
  410. }
  411. }
  412. /// Protocol voting implementation.
  413. ///
  414. /// Given a list of strings describing protocol versions, return a new
  415. /// string encoding all of the protocols that are listed by at
  416. /// least threshold of the inputs.
  417. ///
  418. /// The string is sorted according to the following conventions:
  419. /// - Protocols names are alphabetized
  420. /// - Protocols are in order low to high
  421. /// - Individual and ranges are listed together. For example,
  422. /// "3, 5-10,13"
  423. /// - All entries are unique
  424. ///
  425. /// # Examples
  426. /// ```
  427. /// use protover::compute_vote;
  428. ///
  429. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  430. /// let vote = compute_vote(protos, 2);
  431. /// assert_eq!("Link=3", vote)
  432. /// ```
  433. pub fn compute_vote(
  434. list_of_proto_strings: Vec<String>,
  435. threshold: i32,
  436. ) -> String {
  437. let empty = String::from("");
  438. if list_of_proto_strings.is_empty() {
  439. return empty;
  440. }
  441. // all_count is a structure to represent the count of the number of
  442. // supported versions for a specific protocol. For example, in JSON format:
  443. // {
  444. // "FirstSupportedProtocol": {
  445. // "1": "3",
  446. // "2": "1"
  447. // }
  448. // }
  449. // means that FirstSupportedProtocol has three votes which support version
  450. // 1, and one vote that supports version 2
  451. let mut all_count: HashMap<String, HashMap<Version, usize>> =
  452. HashMap::new();
  453. // parse and collect all of the protos and their versions and collect them
  454. for vote in list_of_proto_strings {
  455. let this_vote: HashMap<String, Versions> =
  456. match parse_protocols_from_string_with_no_validation(&vote) {
  457. Ok(result) => result,
  458. Err(_) => continue,
  459. };
  460. for (protocol, versions) in this_vote {
  461. let supported_vers: &mut HashMap<Version, usize> =
  462. all_count.entry(protocol).or_insert(HashMap::new());
  463. for version in versions.0 {
  464. let counter: &mut usize =
  465. supported_vers.entry(version).or_insert(0);
  466. *counter += 1;
  467. }
  468. }
  469. }
  470. let mut final_output: HashMap<String, String> =
  471. HashMap::with_capacity(get_supported_protocols().split(" ").count());
  472. // Go through and remove verstions that are less than the threshold
  473. for (protocol, versions) in all_count {
  474. let mut meets_threshold = HashSet::new();
  475. for (version, count) in versions {
  476. if count >= threshold as usize {
  477. meets_threshold.insert(version);
  478. }
  479. }
  480. // For each protocol, compress its version list into the expected
  481. // protocol version string format
  482. let contracted = contract_protocol_list(&meets_threshold);
  483. if !contracted.is_empty() {
  484. final_output.insert(protocol, contracted);
  485. }
  486. }
  487. write_vote_to_string(&final_output)
  488. }
  489. /// Return a String comprised of protocol entries in alphabetical order
  490. ///
  491. /// # Inputs
  492. ///
  493. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  494. /// The keys are the protocol names while values are a string representation of
  495. /// the supported versions.
  496. ///
  497. /// # Returns
  498. ///
  499. /// A `String` whose value is series of pairs, comprising of the protocol name
  500. /// and versions that it supports. The string takes the following format:
  501. ///
  502. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  503. ///
  504. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  505. /// entry format.
  506. ///
  507. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  508. let mut keys: Vec<&String> = vote.keys().collect();
  509. keys.sort();
  510. let mut output = Vec::new();
  511. for key in keys {
  512. // TODO error in indexing here?
  513. output.push(format!("{}={}", key, vote[key]));
  514. }
  515. output.join(" ")
  516. }
  517. /// Returns a boolean indicating whether the given protocol and version is
  518. /// supported in any of the existing Tor protocols
  519. ///
  520. /// # Examples
  521. /// ```
  522. /// use protover::*;
  523. ///
  524. /// let is_supported = is_supported_here(Proto::Link, 10);
  525. /// assert_eq!(false, is_supported);
  526. ///
  527. /// let is_supported = is_supported_here(Proto::Link, 1);
  528. /// assert_eq!(true, is_supported);
  529. /// ```
  530. pub fn is_supported_here(proto: Proto, vers: Version) -> bool {
  531. let currently_supported = match SupportedProtocols::tor_supported() {
  532. Ok(result) => result.0,
  533. Err(_) => return false,
  534. };
  535. let supported_versions = match currently_supported.get(&proto) {
  536. Some(n) => n,
  537. None => return false,
  538. };
  539. supported_versions.0.contains(&vers)
  540. }
  541. /// Older versions of Tor cannot infer their own subprotocols
  542. /// Used to determine which subprotocols are supported by older Tor versions.
  543. ///
  544. /// # Inputs
  545. ///
  546. /// * `version`, a string comprised of "[0-9a-z.-]"
  547. ///
  548. /// # Returns
  549. ///
  550. /// A `&'static CStr` encoding a list of protocol names and supported
  551. /// versions. The string takes the following format:
  552. ///
  553. /// "HSDir=1-1 LinkAuth=1"
  554. ///
  555. /// This function returns the protocols that are supported by the version input,
  556. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  557. ///
  558. /// C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  559. pub fn compute_for_old_tor(version: &str) -> &'static CStr {
  560. let empty: &'static CStr = cstr!("");
  561. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  562. return empty;
  563. }
  564. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  565. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  566. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  567. }
  568. if c_tor_version_as_new_as(version, "0.2.7.5") {
  569. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  570. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  571. }
  572. if c_tor_version_as_new_as(version, "0.2.4.19") {
  573. return cstr!("Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  574. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2");
  575. }
  576. empty
  577. }
  578. #[cfg(test)]
  579. mod test {
  580. use std::str::FromStr;
  581. use std::string::ToString;
  582. use super::*;
  583. #[test]
  584. fn test_versions_from_version_string() {
  585. use std::collections::HashSet;
  586. use super::Versions;
  587. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  588. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  589. {
  590. let mut versions: HashSet<Version> = HashSet::new();
  591. versions.insert(1);
  592. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  593. }
  594. {
  595. let mut versions: HashSet<Version> = HashSet::new();
  596. versions.insert(1);
  597. versions.insert(2);
  598. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  599. }
  600. {
  601. let mut versions: HashSet<Version> = HashSet::new();
  602. versions.insert(1);
  603. versions.insert(2);
  604. versions.insert(3);
  605. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  606. }
  607. {
  608. let mut versions: HashSet<Version> = HashSet::new();
  609. versions.insert(1);
  610. versions.insert(2);
  611. versions.insert(5);
  612. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  613. }
  614. {
  615. let mut versions: HashSet<Version> = HashSet::new();
  616. versions.insert(1);
  617. versions.insert(3);
  618. versions.insert(4);
  619. versions.insert(5);
  620. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  621. }
  622. }
  623. #[test]
  624. fn test_contains_only_supported_protocols() {
  625. use super::contains_only_supported_protocols;
  626. assert_eq!(false, contains_only_supported_protocols(""));
  627. assert_eq!(true, contains_only_supported_protocols("Cons="));
  628. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  629. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  630. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  631. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  632. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  633. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  634. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  635. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  636. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  637. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  638. }
  639. #[test]
  640. fn test_find_range() {
  641. use super::find_range;
  642. assert_eq!((false, 0), find_range(&vec![]));
  643. assert_eq!((false, 1), find_range(&vec![1]));
  644. assert_eq!((true, 2), find_range(&vec![1, 2]));
  645. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  646. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  647. }
  648. #[test]
  649. fn test_expand_version_range() {
  650. use super::expand_version_range;
  651. assert_eq!(Err("version string empty"), expand_version_range(""));
  652. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  653. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  654. assert_eq!(
  655. Err("cannot parse protocol range lower bound"),
  656. expand_version_range("a")
  657. );
  658. assert_eq!(
  659. Err("cannot parse protocol range upper bound"),
  660. expand_version_range("1-a")
  661. );
  662. assert_eq!(Ok(1000..66536), expand_version_range("1000-66535"));
  663. assert_eq!(Err("Too many protocols in expanded range"),
  664. expand_version_range("1000-66536"));
  665. }
  666. #[test]
  667. fn test_contract_protocol_list() {
  668. use std::collections::HashSet;
  669. use super::contract_protocol_list;
  670. {
  671. let mut versions = HashSet::<Version>::new();
  672. assert_eq!(String::from(""), contract_protocol_list(&versions));
  673. versions.insert(1);
  674. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  675. versions.insert(2);
  676. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  677. }
  678. {
  679. let mut versions = HashSet::<Version>::new();
  680. versions.insert(1);
  681. versions.insert(3);
  682. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  683. }
  684. {
  685. let mut versions = HashSet::<Version>::new();
  686. versions.insert(1);
  687. versions.insert(2);
  688. versions.insert(3);
  689. versions.insert(4);
  690. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  691. }
  692. {
  693. let mut versions = HashSet::<Version>::new();
  694. versions.insert(1);
  695. versions.insert(3);
  696. versions.insert(5);
  697. versions.insert(6);
  698. versions.insert(7);
  699. assert_eq!(
  700. String::from("1,3,5-7"),
  701. contract_protocol_list(&versions)
  702. );
  703. }
  704. {
  705. let mut versions = HashSet::<Version>::new();
  706. versions.insert(1);
  707. versions.insert(2);
  708. versions.insert(3);
  709. versions.insert(500);
  710. assert_eq!(
  711. String::from("1-3,500"),
  712. contract_protocol_list(&versions)
  713. );
  714. }
  715. }
  716. }