protover.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. pub fn len(&self) -> usize {
  232. let mut total: usize = 0;
  233. for (_, versions) in self.iter() {
  234. total += versions.len();
  235. }
  236. total
  237. }
  238. /// Determine if we support every protocol a client supports, and if not,
  239. /// determine which protocols we do not have support for.
  240. ///
  241. /// # Returns
  242. ///
  243. /// Optionally, return parameters which the client supports but which we do not.
  244. ///
  245. /// # Examples
  246. /// ```
  247. /// use protover::UnvalidatedProtoEntry;
  248. ///
  249. /// let protocols: UnvalidatedProtoEntry = "LinkAuth=1 Microdesc=1-2 Relay=2".parse().unwrap();
  250. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  251. /// assert_eq!(true, unsupported.is_none());
  252. ///
  253. /// let protocols: UnvalidatedProtoEntry = "Link=1-2 Wombat=9".parse().unwrap();
  254. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  255. /// assert_eq!(true, unsupported.is_some());
  256. /// assert_eq!("Wombat=9", &unsupported.unwrap().to_string());
  257. /// ```
  258. pub fn all_supported(&self) -> Option<UnvalidatedProtoEntry> {
  259. let mut unsupported: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  260. let supported: ProtoEntry = match ProtoEntry::supported() {
  261. Ok(x) => x,
  262. Err(_) => return None,
  263. };
  264. for (protocol, versions) in self.iter() {
  265. let is_supported: Result<Protocol, ProtoverError> = protocol.0.parse();
  266. let supported_protocol: Protocol;
  267. // If the protocol wasn't even in the enum, then we definitely don't
  268. // know about it and don't support any of its versions.
  269. if is_supported.is_err() {
  270. if !versions.is_empty() {
  271. unsupported.insert(protocol.clone(), versions.clone());
  272. }
  273. continue;
  274. } else {
  275. supported_protocol = is_supported.unwrap();
  276. }
  277. let maybe_supported_versions: Option<&ProtoSet> = supported.get(&supported_protocol);
  278. let supported_versions: &ProtoSet;
  279. let mut unsupported_versions: ProtoSet;
  280. // If the protocol wasn't in the map, then we don't know about it
  281. // and don't support any of its versions. Add its versions to the
  282. // map (if it has versions).
  283. if maybe_supported_versions.is_none() {
  284. if !versions.is_empty() {
  285. unsupported.insert(protocol.clone(), versions.clone());
  286. }
  287. continue;
  288. } else {
  289. supported_versions = maybe_supported_versions.unwrap();
  290. }
  291. unsupported_versions = versions.clone();
  292. unsupported_versions.retain(|x| !supported_versions.contains(x));
  293. if !unsupported_versions.is_empty() {
  294. unsupported.insert(protocol.clone(), unsupported_versions);
  295. }
  296. }
  297. if unsupported.is_empty() {
  298. return None;
  299. }
  300. Some(unsupported)
  301. }
  302. /// Determine if we have support for some protocol and version.
  303. ///
  304. /// # Inputs
  305. ///
  306. /// * `proto`, an `UnknownProtocol` to test support for
  307. /// * `vers`, a `Version` which we will go on to determine whether the
  308. /// specified protocol supports.
  309. ///
  310. /// # Return
  311. ///
  312. /// Returns `true` iff this `UnvalidatedProtoEntry` includes support for the
  313. /// indicated protocol and version, and `false` otherwise.
  314. ///
  315. /// # Examples
  316. ///
  317. /// ```
  318. /// # use std::str::FromStr;
  319. /// use protover::*;
  320. /// # use protover::errors::ProtoverError;
  321. ///
  322. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  323. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=1 Doggo=3-5".parse()?;
  324. /// assert_eq!(true, proto.supports_protocol(&Protocol::Cons.into(), &1));
  325. /// assert_eq!(false, proto.supports_protocol(&Protocol::Cons.into(), &5));
  326. /// assert_eq!(true, proto.supports_protocol(&UnknownProtocol::from_str("Doggo")?, &4));
  327. /// # Ok(proto)
  328. /// # } fn main () { do_test(); }
  329. /// ```
  330. pub fn supports_protocol(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  331. let supported_versions: &ProtoSet = match self.get(proto) {
  332. Some(n) => n,
  333. None => return false,
  334. };
  335. supported_versions.contains(&vers)
  336. }
  337. /// As `UnvalidatedProtoEntry::supports_protocol()`, but also returns `true`
  338. /// if any later version of the protocol is supported.
  339. ///
  340. /// # Examples
  341. /// ```
  342. /// use protover::*;
  343. /// # use protover::errors::ProtoverError;
  344. ///
  345. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  346. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=5".parse()?;
  347. ///
  348. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &5));
  349. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &4));
  350. /// assert_eq!(false, proto.supports_protocol_or_later(&Protocol::Cons.into(), &6));
  351. /// # Ok(proto)
  352. /// # } fn main () { do_test(); }
  353. /// ```
  354. pub fn supports_protocol_or_later(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  355. let supported_versions: &ProtoSet = match self.get(&proto) {
  356. Some(n) => n,
  357. None => return false,
  358. };
  359. supported_versions.iter().any(|v| v.1 >= *vers)
  360. }
  361. }
  362. impl FromStr for UnvalidatedProtoEntry {
  363. type Err = ProtoverError;
  364. /// Parses a protocol list without validating the protocol names.
  365. ///
  366. /// # Inputs
  367. ///
  368. /// * `protocol_string`, a string comprised of keys and values, both which are
  369. /// strings. The keys are the protocol names while values are a string
  370. /// representation of the supported versions.
  371. ///
  372. /// The input is _not_ expected to be a subset of the Protocol types
  373. ///
  374. /// # Returns
  375. ///
  376. /// A `Result` whose `Ok` value is a `ProtoSet` holding all of the
  377. /// unique version numbers.
  378. ///
  379. /// The returned `Result`'s `Err` value is an `ProtoverError` whose `Display`
  380. /// impl has a description of the error.
  381. ///
  382. /// # Errors
  383. ///
  384. /// This function will error if:
  385. ///
  386. /// * The protocol string does not follow the "protocol_name=version_list"
  387. /// expected format, or
  388. /// * If the version string is malformed. See `impl FromStr for ProtoSet`.
  389. fn from_str(protocol_string: &str) -> Result<UnvalidatedProtoEntry, ProtoverError> {
  390. let mut parsed: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  391. for subproto in protocol_string.split(' ') {
  392. let mut parts = subproto.splitn(2, '=');
  393. let name = match parts.next() {
  394. Some("") => return Err(ProtoverError::Unparseable),
  395. Some(n) => n,
  396. None => return Err(ProtoverError::Unparseable),
  397. };
  398. let vers = match parts.next() {
  399. Some(n) => n,
  400. None => return Err(ProtoverError::Unparseable),
  401. };
  402. let versions = ProtoSet::from_str(vers)?;
  403. let protocol = UnknownProtocol::from_str(name)?;
  404. parsed.insert(protocol, versions);
  405. }
  406. Ok(parsed)
  407. }
  408. }
  409. /// Pretend a `ProtoEntry` is actually an `UnvalidatedProtoEntry`.
  410. impl From<ProtoEntry> for UnvalidatedProtoEntry {
  411. fn from(proto_entry: ProtoEntry) -> UnvalidatedProtoEntry {
  412. let mut unvalidated: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  413. for (protocol, versions) in proto_entry.iter() {
  414. unvalidated.insert(UnknownProtocol::from(protocol.clone()), versions.clone());
  415. }
  416. unvalidated
  417. }
  418. }
  419. /// A mapping of protocols to a count of how many times each of their `Version`s
  420. /// were voted for or supported.
  421. ///
  422. /// # Warning
  423. ///
  424. /// The "protocols" are *not* guaranteed to be known/supported `Protocol`s, in
  425. /// order to allow new subprotocols to be introduced even if Directory
  426. /// Authorities don't yet know of them.
  427. pub struct ProtoverVote( HashMap<UnknownProtocol, HashMap<Version, usize>> );
  428. impl Default for ProtoverVote {
  429. fn default() -> ProtoverVote {
  430. ProtoverVote( HashMap::new() )
  431. }
  432. }
  433. impl IntoIterator for ProtoverVote {
  434. type Item = (UnknownProtocol, HashMap<Version, usize>);
  435. type IntoIter = hash_map::IntoIter<UnknownProtocol, HashMap<Version, usize>>;
  436. fn into_iter(self) -> Self::IntoIter {
  437. self.0.into_iter()
  438. }
  439. }
  440. impl ProtoverVote {
  441. pub fn entry(&mut self, key: UnknownProtocol)
  442. -> hash_map::Entry<UnknownProtocol, HashMap<Version, usize>>
  443. {
  444. self.0.entry(key)
  445. }
  446. /// Protocol voting implementation.
  447. ///
  448. /// Given a slice of `UnvalidatedProtoEntry`s and a vote `threshold`, return
  449. /// a new `UnvalidatedProtoEntry` encoding all of the protocols that are
  450. /// listed by at least `threshold` of the inputs.
  451. ///
  452. /// # Examples
  453. ///
  454. /// ```
  455. /// use protover::ProtoverVote;
  456. /// use protover::UnvalidatedProtoEntry;
  457. ///
  458. /// let protos: &[UnvalidatedProtoEntry] = &["Link=3-4".parse().unwrap(),
  459. /// "Link=3".parse().unwrap()];
  460. /// let vote = ProtoverVote::compute(protos, &2);
  461. /// assert_eq!("Link=3", vote.to_string());
  462. /// ```
  463. // C_RUST_COUPLED: /src/or/protover.c protover_compute_vote
  464. pub fn compute(proto_entries: &[UnvalidatedProtoEntry], threshold: &usize) -> UnvalidatedProtoEntry {
  465. let mut all_count: ProtoverVote = ProtoverVote::default();
  466. let mut final_output: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  467. if proto_entries.is_empty() {
  468. return final_output;
  469. }
  470. // parse and collect all of the protos and their versions and collect them
  471. for vote in proto_entries {
  472. // C_RUST_DIFFERS: This doesn't actually differ, bu this check on
  473. // the total is here to make it match. Because the C version calls
  474. // expand_protocol_list() which checks if there would be too many
  475. // subprotocols *or* individual version numbers, i.e. more than
  476. // MAX_PROTOCOLS_TO_EXPAND, and does this *per vote*, we need to
  477. // match it's behaviour and ensure we're not allowing more than it
  478. // would.
  479. if vote.len() > MAX_PROTOCOLS_TO_EXPAND {
  480. continue;
  481. }
  482. for (protocol, versions) in vote.iter() {
  483. let supported_vers: &mut HashMap<Version, usize> =
  484. all_count.entry(protocol.clone()).or_insert(HashMap::new());
  485. for version in versions.clone().expand() {
  486. let counter: &mut usize =
  487. supported_vers.entry(version).or_insert(0);
  488. *counter += 1;
  489. }
  490. }
  491. }
  492. for (protocol, mut versions) in all_count {
  493. // Go through and remove versions that are less than the threshold
  494. versions.retain(|_, count| *count as usize >= *threshold);
  495. if versions.len() > 0 {
  496. let voted_versions: Vec<Version> = versions.keys().cloned().collect();
  497. let voted_protoset: ProtoSet = ProtoSet::from(voted_versions);
  498. final_output.insert(protocol, voted_protoset);
  499. }
  500. }
  501. final_output
  502. }
  503. }
  504. /// Returns a boolean indicating whether the given protocol and version is
  505. /// supported in any of the existing Tor protocols
  506. ///
  507. /// # Examples
  508. /// ```
  509. /// use protover::is_supported_here;
  510. /// use protover::Protocol;
  511. ///
  512. /// let is_supported = is_supported_here(&Protocol::Link, &10);
  513. /// assert_eq!(false, is_supported);
  514. ///
  515. /// let is_supported = is_supported_here(&Protocol::Link, &1);
  516. /// assert_eq!(true, is_supported);
  517. /// ```
  518. pub fn is_supported_here(proto: &Protocol, vers: &Version) -> bool {
  519. let currently_supported: ProtoEntry = match ProtoEntry::supported() {
  520. Ok(result) => result,
  521. Err(_) => return false,
  522. };
  523. let supported_versions = match currently_supported.get(proto) {
  524. Some(n) => n,
  525. None => return false,
  526. };
  527. supported_versions.contains(vers)
  528. }
  529. /// Older versions of Tor cannot infer their own subprotocols
  530. /// Used to determine which subprotocols are supported by older Tor versions.
  531. ///
  532. /// # Inputs
  533. ///
  534. /// * `version`, a string comprised of "[0-9a-z.-]"
  535. ///
  536. /// # Returns
  537. ///
  538. /// A `&'static CStr` encoding a list of protocol names and supported
  539. /// versions. The string takes the following format:
  540. ///
  541. /// "HSDir=1-1 LinkAuth=1"
  542. ///
  543. /// This function returns the protocols that are supported by the version input,
  544. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  545. ///
  546. /// C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  547. pub fn compute_for_old_tor(version: &str) -> &'static CStr {
  548. let empty: &'static CStr = cstr!("");
  549. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  550. return empty;
  551. }
  552. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  553. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  554. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  555. }
  556. if c_tor_version_as_new_as(version, "0.2.7.5") {
  557. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  558. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  559. }
  560. if c_tor_version_as_new_as(version, "0.2.4.19") {
  561. return cstr!("Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  562. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2");
  563. }
  564. empty
  565. }
  566. #[cfg(test)]
  567. mod test {
  568. use std::str::FromStr;
  569. use std::string::ToString;
  570. use super::*;
  571. #[test]
  572. fn test_versions_from_version_string() {
  573. use std::collections::HashSet;
  574. use super::Versions;
  575. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  576. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  577. {
  578. let mut versions: HashSet<Version> = HashSet::new();
  579. versions.insert(1);
  580. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  581. }
  582. {
  583. let mut versions: HashSet<Version> = HashSet::new();
  584. versions.insert(1);
  585. versions.insert(2);
  586. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  587. }
  588. {
  589. let mut versions: HashSet<Version> = HashSet::new();
  590. versions.insert(1);
  591. versions.insert(2);
  592. versions.insert(3);
  593. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  594. }
  595. {
  596. let mut versions: HashSet<Version> = HashSet::new();
  597. versions.insert(1);
  598. versions.insert(2);
  599. versions.insert(5);
  600. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  601. }
  602. {
  603. let mut versions: HashSet<Version> = HashSet::new();
  604. versions.insert(1);
  605. versions.insert(3);
  606. versions.insert(4);
  607. versions.insert(5);
  608. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  609. }
  610. }
  611. #[test]
  612. fn test_contains_only_supported_protocols() {
  613. use super::contains_only_supported_protocols;
  614. assert_eq!(false, contains_only_supported_protocols(""));
  615. assert_eq!(true, contains_only_supported_protocols("Cons="));
  616. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  617. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  618. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  619. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  620. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  621. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  622. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  623. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  624. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  625. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  626. }
  627. #[test]
  628. fn test_find_range() {
  629. use super::find_range;
  630. assert_eq!((false, 0), find_range(&vec![]));
  631. assert_eq!((false, 1), find_range(&vec![1]));
  632. assert_eq!((true, 2), find_range(&vec![1, 2]));
  633. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  634. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  635. }
  636. #[test]
  637. fn test_expand_version_range() {
  638. use super::expand_version_range;
  639. assert_eq!(Err("version string empty"), expand_version_range(""));
  640. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  641. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  642. assert_eq!(
  643. Err("cannot parse protocol range lower bound"),
  644. expand_version_range("a")
  645. );
  646. assert_eq!(
  647. Err("cannot parse protocol range upper bound"),
  648. expand_version_range("1-a")
  649. );
  650. assert_eq!(Ok(1000..66536), expand_version_range("1000-66535"));
  651. assert_eq!(Err("Too many protocols in expanded range"),
  652. expand_version_range("1000-66536"));
  653. }
  654. #[test]
  655. fn test_contract_protocol_list() {
  656. use std::collections::HashSet;
  657. use super::contract_protocol_list;
  658. {
  659. let mut versions = HashSet::<Version>::new();
  660. assert_eq!(String::from(""), contract_protocol_list(&versions));
  661. versions.insert(1);
  662. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  663. versions.insert(2);
  664. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  665. }
  666. {
  667. let mut versions = HashSet::<Version>::new();
  668. versions.insert(1);
  669. versions.insert(3);
  670. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  671. }
  672. {
  673. let mut versions = HashSet::<Version>::new();
  674. versions.insert(1);
  675. versions.insert(2);
  676. versions.insert(3);
  677. versions.insert(4);
  678. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  679. }
  680. {
  681. let mut versions = HashSet::<Version>::new();
  682. versions.insert(1);
  683. versions.insert(3);
  684. versions.insert(5);
  685. versions.insert(6);
  686. versions.insert(7);
  687. assert_eq!(
  688. String::from("1,3,5-7"),
  689. contract_protocol_list(&versions)
  690. );
  691. }
  692. {
  693. let mut versions = HashSet::<Version>::new();
  694. versions.insert(1);
  695. versions.insert(2);
  696. versions.insert(3);
  697. versions.insert(500);
  698. assert_eq!(
  699. String::from("1-3,500"),
  700. contract_protocol_list(&versions)
  701. );
  702. }
  703. }
  704. }