protover.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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. 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 len(&self) -> usize {
  138. self.0.len()
  139. }
  140. pub fn get(&self, protocol: &Protocol) -> Option<&ProtoSet> {
  141. self.0.get(protocol)
  142. }
  143. pub fn insert(&mut self, key: Protocol, value: ProtoSet) {
  144. self.0.insert(key, value);
  145. }
  146. pub fn remove(&mut self, key: &Protocol) -> Option<ProtoSet> {
  147. self.0.remove(key)
  148. }
  149. pub fn is_empty(&self) -> bool {
  150. self.0.is_empty()
  151. }
  152. }
  153. impl FromStr for ProtoEntry {
  154. type Err = ProtoverError;
  155. /// Parse a string of subprotocol types and their version numbers.
  156. ///
  157. /// # Inputs
  158. ///
  159. /// * A `protocol_entry` string, comprised of a keywords, an "=" sign, and
  160. /// one or more version numbers, each separated by a space. For example,
  161. /// `"Cons=3-4 HSDir=1"`.
  162. ///
  163. /// # Returns
  164. ///
  165. /// A `Result` whose `Ok` value is a `ProtoEntry`, where the
  166. /// first element is the subprotocol type (see `protover::Protocol`) and the last
  167. /// element is an ordered set of `(low, high)` unique version numbers which are supported.
  168. /// Otherwise, the `Err` value of this `Result` is a `ProtoverError`.
  169. fn from_str(protocol_entry: &str) -> Result<ProtoEntry, ProtoverError> {
  170. let mut proto_entry: ProtoEntry = ProtoEntry::default();
  171. let entries = protocol_entry.split(' ');
  172. for entry in entries {
  173. let mut parts = entry.splitn(2, '=');
  174. let proto = match parts.next() {
  175. Some(n) => n,
  176. None => return Err(ProtoverError::Unparseable),
  177. };
  178. let vers = match parts.next() {
  179. Some(n) => n,
  180. None => return Err(ProtoverError::Unparseable),
  181. };
  182. let versions: ProtoSet = vers.parse()?;
  183. let proto_name: Protocol = proto.parse()?;
  184. proto_entry.insert(proto_name, versions);
  185. if proto_entry.len() > MAX_PROTOCOLS_TO_EXPAND {
  186. return Err(ProtoverError::ExceedsMax);
  187. }
  188. }
  189. Ok(proto_entry)
  190. }
  191. }
  192. /// Generate an implementation of `ToString` for either a `ProtoEntry` or an
  193. /// `UnvalidatedProtoEntry`.
  194. macro_rules! impl_to_string_for_proto_entry {
  195. ($t:ty) => (
  196. impl ToString for $t {
  197. fn to_string(&self) -> String {
  198. let mut parts: Vec<String> = Vec::new();
  199. for (protocol, versions) in self.iter() {
  200. parts.push(format!("{}={}", protocol.to_string(), versions.to_string()));
  201. }
  202. parts.sort_unstable();
  203. parts.join(" ")
  204. }
  205. }
  206. )
  207. }
  208. impl_to_string_for_proto_entry!(ProtoEntry);
  209. impl_to_string_for_proto_entry!(UnvalidatedProtoEntry);
  210. /// A `ProtoEntry`, but whose `Protocols` can be any `UnknownProtocol`, not just
  211. /// the supported ones enumerated in `Protocols`. The protocol versions are
  212. /// validated, however.
  213. #[derive(Clone, Debug, PartialEq, Eq)]
  214. pub struct UnvalidatedProtoEntry(HashMap<UnknownProtocol, ProtoSet>);
  215. impl Default for UnvalidatedProtoEntry {
  216. fn default() -> UnvalidatedProtoEntry {
  217. UnvalidatedProtoEntry( HashMap::new() )
  218. }
  219. }
  220. impl UnvalidatedProtoEntry {
  221. /// Get an iterator over the `Protocol`s and their `ProtoSet`s in this `ProtoEntry`.
  222. pub fn iter(&self) -> hash_map::Iter<UnknownProtocol, ProtoSet> {
  223. self.0.iter()
  224. }
  225. pub fn get(&self, protocol: &UnknownProtocol) -> Option<&ProtoSet> {
  226. self.0.get(protocol)
  227. }
  228. pub fn insert(&mut self, key: UnknownProtocol, value: ProtoSet) {
  229. self.0.insert(key, value);
  230. }
  231. pub fn remove(&mut self, key: &UnknownProtocol) -> Option<ProtoSet> {
  232. self.0.remove(key)
  233. }
  234. pub fn is_empty(&self) -> bool {
  235. self.0.is_empty()
  236. }
  237. pub fn len(&self) -> usize {
  238. let mut total: usize = 0;
  239. for (_, versions) in self.iter() {
  240. total += versions.len();
  241. }
  242. total
  243. }
  244. /// Determine if we support every protocol a client supports, and if not,
  245. /// determine which protocols we do not have support for.
  246. ///
  247. /// # Returns
  248. ///
  249. /// Optionally, return parameters which the client supports but which we do not.
  250. ///
  251. /// # Examples
  252. /// ```
  253. /// use protover::UnvalidatedProtoEntry;
  254. ///
  255. /// let protocols: UnvalidatedProtoEntry = "LinkAuth=1 Microdesc=1-2 Relay=2".parse().unwrap();
  256. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  257. /// assert_eq!(true, unsupported.is_none());
  258. ///
  259. /// let protocols: UnvalidatedProtoEntry = "Link=1-2 Wombat=9".parse().unwrap();
  260. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  261. /// assert_eq!(true, unsupported.is_some());
  262. /// assert_eq!("Wombat=9", &unsupported.unwrap().to_string());
  263. /// ```
  264. pub fn all_supported(&self) -> Option<UnvalidatedProtoEntry> {
  265. let mut unsupported: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  266. let supported: ProtoEntry = match ProtoEntry::supported() {
  267. Ok(x) => x,
  268. Err(_) => return None,
  269. };
  270. for (protocol, versions) in self.iter() {
  271. let is_supported: Result<Protocol, ProtoverError> = protocol.0.parse();
  272. let supported_protocol: Protocol;
  273. // If the protocol wasn't even in the enum, then we definitely don't
  274. // know about it and don't support any of its versions.
  275. if is_supported.is_err() {
  276. if !versions.is_empty() {
  277. unsupported.insert(protocol.clone(), versions.clone());
  278. }
  279. continue;
  280. } else {
  281. supported_protocol = is_supported.unwrap();
  282. }
  283. let maybe_supported_versions: Option<&ProtoSet> = supported.get(&supported_protocol);
  284. let supported_versions: &ProtoSet;
  285. let mut unsupported_versions: ProtoSet;
  286. // If the protocol wasn't in the map, then we don't know about it
  287. // and don't support any of its versions. Add its versions to the
  288. // map (if it has versions).
  289. if maybe_supported_versions.is_none() {
  290. if !versions.is_empty() {
  291. unsupported.insert(protocol.clone(), versions.clone());
  292. }
  293. continue;
  294. } else {
  295. supported_versions = maybe_supported_versions.unwrap();
  296. }
  297. unsupported_versions = versions.clone();
  298. unsupported_versions.retain(|x| !supported_versions.contains(x));
  299. if !unsupported_versions.is_empty() {
  300. unsupported.insert(protocol.clone(), unsupported_versions);
  301. }
  302. }
  303. if unsupported.is_empty() {
  304. return None;
  305. }
  306. Some(unsupported)
  307. }
  308. /// Determine if we have support for some protocol and version.
  309. ///
  310. /// # Inputs
  311. ///
  312. /// * `proto`, an `UnknownProtocol` to test support for
  313. /// * `vers`, a `Version` which we will go on to determine whether the
  314. /// specified protocol supports.
  315. ///
  316. /// # Return
  317. ///
  318. /// Returns `true` iff this `UnvalidatedProtoEntry` includes support for the
  319. /// indicated protocol and version, and `false` otherwise.
  320. ///
  321. /// # Examples
  322. ///
  323. /// ```
  324. /// # use std::str::FromStr;
  325. /// use protover::*;
  326. /// # use protover::errors::ProtoverError;
  327. ///
  328. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  329. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=1 Doggo=3-5".parse()?;
  330. /// assert_eq!(true, proto.supports_protocol(&Protocol::Cons.into(), &1));
  331. /// assert_eq!(false, proto.supports_protocol(&Protocol::Cons.into(), &5));
  332. /// assert_eq!(true, proto.supports_protocol(&UnknownProtocol::from_str("Doggo")?, &4));
  333. /// # Ok(proto)
  334. /// # } fn main () { do_test(); }
  335. /// ```
  336. pub fn supports_protocol(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  337. let supported_versions: &ProtoSet = match self.get(proto) {
  338. Some(n) => n,
  339. None => return false,
  340. };
  341. supported_versions.contains(&vers)
  342. }
  343. /// As `UnvalidatedProtoEntry::supports_protocol()`, but also returns `true`
  344. /// if any later version of the protocol is supported.
  345. ///
  346. /// # Examples
  347. /// ```
  348. /// use protover::*;
  349. /// # use protover::errors::ProtoverError;
  350. ///
  351. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  352. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=5".parse()?;
  353. ///
  354. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &5));
  355. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &4));
  356. /// assert_eq!(false, proto.supports_protocol_or_later(&Protocol::Cons.into(), &6));
  357. /// # Ok(proto)
  358. /// # } fn main () { do_test(); }
  359. /// ```
  360. pub fn supports_protocol_or_later(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  361. let supported_versions: &ProtoSet = match self.get(&proto) {
  362. Some(n) => n,
  363. None => return false,
  364. };
  365. supported_versions.iter().any(|v| v.1 >= *vers)
  366. }
  367. }
  368. impl FromStr for UnvalidatedProtoEntry {
  369. type Err = ProtoverError;
  370. /// Parses a protocol list without validating the protocol names.
  371. ///
  372. /// # Inputs
  373. ///
  374. /// * `protocol_string`, a string comprised of keys and values, both which are
  375. /// strings. The keys are the protocol names while values are a string
  376. /// representation of the supported versions.
  377. ///
  378. /// The input is _not_ expected to be a subset of the Protocol types
  379. ///
  380. /// # Returns
  381. ///
  382. /// A `Result` whose `Ok` value is a `ProtoSet` holding all of the
  383. /// unique version numbers.
  384. ///
  385. /// The returned `Result`'s `Err` value is an `ProtoverError` whose `Display`
  386. /// impl has a description of the error.
  387. ///
  388. /// # Errors
  389. ///
  390. /// This function will error if:
  391. ///
  392. /// * The protocol string does not follow the "protocol_name=version_list"
  393. /// expected format, or
  394. /// * If the version string is malformed. See `impl FromStr for ProtoSet`.
  395. fn from_str(protocol_string: &str) -> Result<UnvalidatedProtoEntry, ProtoverError> {
  396. let mut parsed: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  397. for subproto in protocol_string.split(' ') {
  398. let mut parts = subproto.splitn(2, '=');
  399. let name = match parts.next() {
  400. Some("") => return Err(ProtoverError::Unparseable),
  401. Some(n) => n,
  402. None => return Err(ProtoverError::Unparseable),
  403. };
  404. let vers = match parts.next() {
  405. Some(n) => n,
  406. None => return Err(ProtoverError::Unparseable),
  407. };
  408. let versions = ProtoSet::from_str(vers)?;
  409. let protocol = UnknownProtocol::from_str(name)?;
  410. parsed.insert(protocol, versions);
  411. }
  412. Ok(parsed)
  413. }
  414. }
  415. /// Pretend a `ProtoEntry` is actually an `UnvalidatedProtoEntry`.
  416. impl From<ProtoEntry> for UnvalidatedProtoEntry {
  417. fn from(proto_entry: ProtoEntry) -> UnvalidatedProtoEntry {
  418. let mut unvalidated: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  419. for (protocol, versions) in proto_entry.iter() {
  420. unvalidated.insert(UnknownProtocol::from(protocol.clone()), versions.clone());
  421. }
  422. unvalidated
  423. }
  424. }
  425. /// A mapping of protocols to a count of how many times each of their `Version`s
  426. /// were voted for or supported.
  427. ///
  428. /// # Warning
  429. ///
  430. /// The "protocols" are *not* guaranteed to be known/supported `Protocol`s, in
  431. /// order to allow new subprotocols to be introduced even if Directory
  432. /// Authorities don't yet know of them.
  433. pub struct ProtoverVote( HashMap<UnknownProtocol, HashMap<Version, usize>> );
  434. impl Default for ProtoverVote {
  435. fn default() -> ProtoverVote {
  436. ProtoverVote( HashMap::new() )
  437. }
  438. }
  439. impl IntoIterator for ProtoverVote {
  440. type Item = (UnknownProtocol, HashMap<Version, usize>);
  441. type IntoIter = hash_map::IntoIter<UnknownProtocol, HashMap<Version, usize>>;
  442. fn into_iter(self) -> Self::IntoIter {
  443. self.0.into_iter()
  444. }
  445. }
  446. impl ProtoverVote {
  447. pub fn entry(&mut self, key: UnknownProtocol)
  448. -> hash_map::Entry<UnknownProtocol, HashMap<Version, usize>>
  449. {
  450. self.0.entry(key)
  451. }
  452. /// Protocol voting implementation.
  453. ///
  454. /// Given a slice of `UnvalidatedProtoEntry`s and a vote `threshold`, return
  455. /// a new `UnvalidatedProtoEntry` encoding all of the protocols that are
  456. /// listed by at least `threshold` of the inputs.
  457. ///
  458. /// # Examples
  459. ///
  460. /// ```
  461. /// use protover::ProtoverVote;
  462. /// use protover::UnvalidatedProtoEntry;
  463. ///
  464. /// let protos: &[UnvalidatedProtoEntry] = &["Link=3-4".parse().unwrap(),
  465. /// "Link=3".parse().unwrap()];
  466. /// let vote = ProtoverVote::compute(protos, &2);
  467. /// assert_eq!("Link=3", vote.to_string());
  468. /// ```
  469. // C_RUST_COUPLED: /src/or/protover.c protover_compute_vote
  470. pub fn compute(proto_entries: &[UnvalidatedProtoEntry], threshold: &usize) -> UnvalidatedProtoEntry {
  471. let mut all_count: ProtoverVote = ProtoverVote::default();
  472. let mut final_output: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  473. if proto_entries.is_empty() {
  474. return final_output;
  475. }
  476. // parse and collect all of the protos and their versions and collect them
  477. for vote in proto_entries {
  478. // C_RUST_DIFFERS: This doesn't actually differ, bu this check on
  479. // the total is here to make it match. Because the C version calls
  480. // expand_protocol_list() which checks if there would be too many
  481. // subprotocols *or* individual version numbers, i.e. more than
  482. // MAX_PROTOCOLS_TO_EXPAND, and does this *per vote*, we need to
  483. // match it's behaviour and ensure we're not allowing more than it
  484. // would.
  485. if vote.len() > MAX_PROTOCOLS_TO_EXPAND {
  486. continue;
  487. }
  488. for (protocol, versions) in vote.iter() {
  489. let supported_vers: &mut HashMap<Version, usize> =
  490. all_count.entry(protocol.clone()).or_insert(HashMap::new());
  491. for version in versions.clone().expand() {
  492. let counter: &mut usize =
  493. supported_vers.entry(version).or_insert(0);
  494. *counter += 1;
  495. }
  496. }
  497. }
  498. for (protocol, mut versions) in all_count {
  499. // Go through and remove versions that are less than the threshold
  500. versions.retain(|_, count| *count as usize >= *threshold);
  501. if versions.len() > 0 {
  502. let voted_versions: Vec<Version> = versions.keys().cloned().collect();
  503. let voted_protoset: ProtoSet = ProtoSet::from(voted_versions);
  504. final_output.insert(protocol, voted_protoset);
  505. }
  506. }
  507. final_output
  508. }
  509. }
  510. /// Returns a boolean indicating whether the given protocol and version is
  511. /// supported in any of the existing Tor protocols
  512. ///
  513. /// # Examples
  514. /// ```
  515. /// use protover::is_supported_here;
  516. /// use protover::Protocol;
  517. ///
  518. /// let is_supported = is_supported_here(&Protocol::Link, &10);
  519. /// assert_eq!(false, is_supported);
  520. ///
  521. /// let is_supported = is_supported_here(&Protocol::Link, &1);
  522. /// assert_eq!(true, is_supported);
  523. /// ```
  524. pub fn is_supported_here(proto: &Protocol, vers: &Version) -> bool {
  525. let currently_supported: ProtoEntry = match ProtoEntry::supported() {
  526. Ok(result) => result,
  527. Err(_) => return false,
  528. };
  529. let supported_versions = match currently_supported.get(proto) {
  530. Some(n) => n,
  531. None => return false,
  532. };
  533. supported_versions.contains(vers)
  534. }
  535. /// Since older versions of Tor cannot infer their own subprotocols,
  536. /// determine which subprotocols are supported by older Tor versions.
  537. ///
  538. /// # Inputs
  539. ///
  540. /// * `version`, a string comprised of "[0-9a-z.-]"
  541. ///
  542. /// # Returns
  543. ///
  544. /// A `&'static CStr` encoding a list of protocol names and supported
  545. /// versions. The string takes the following format:
  546. ///
  547. /// "HSDir=1-1 LinkAuth=1"
  548. ///
  549. /// This function returns the protocols that are supported by the version input,
  550. /// only for tor versions older than `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`
  551. /// (but not older than 0.2.4.19). For newer tors (or older than 0.2.4.19), it
  552. /// returns an empty string.
  553. ///
  554. /// # Note
  555. ///
  556. /// This function is meant to be called for/within FFI code. If you'd
  557. /// like to use this code in Rust, please see `compute_for_old_tor()`.
  558. //
  559. // C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  560. pub(crate) fn compute_for_old_tor_cstr(version: &str) -> &'static CStr {
  561. let empty: &'static CStr = cstr!("");
  562. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  563. return empty;
  564. }
  565. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  566. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  567. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  568. }
  569. if c_tor_version_as_new_as(version, "0.2.7.5") {
  570. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  571. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  572. }
  573. if c_tor_version_as_new_as(version, "0.2.4.19") {
  574. return cstr!("Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  575. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2");
  576. }
  577. empty
  578. }
  579. /// Since older versions of Tor cannot infer their own subprotocols,
  580. /// determine which subprotocols are supported by older Tor versions.
  581. ///
  582. /// # Inputs
  583. ///
  584. /// * `version`, a string comprised of "[0-9a-z.-]"
  585. ///
  586. /// # Returns
  587. ///
  588. /// A `Result` whose `Ok` value is an `&'static str` encoding a list of protocol
  589. /// names and supported versions. The string takes the following format:
  590. ///
  591. /// "HSDir=1-1 LinkAuth=1"
  592. ///
  593. /// This function returns the protocols that are supported by the version input,
  594. /// only for tor versions older than `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`.
  595. /// (but not older than 0.2.4.19). For newer tors (or older than 0.2.4.19), its
  596. /// `Ok` `Result` contains an empty string.
  597. ///
  598. /// Otherwise, its `Err` contains a `ProtoverError::Unparseable` if the
  599. /// `version` string was invalid utf-8.
  600. ///
  601. /// # Note
  602. ///
  603. /// This function is meant to be called for/within non-FFI Rust code.
  604. //
  605. // C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  606. pub fn compute_for_old_tor(version: &str) -> Result<&'static str, ProtoverError> {
  607. // .to_str() fails with a Utf8Error if it couldn't validate the
  608. // utf-8, so convert that here into an Unparseable ProtoverError.
  609. compute_for_old_tor_cstr(version).to_str().or(Err(ProtoverError::Unparseable))
  610. }
  611. #[cfg(test)]
  612. mod test {
  613. use std::str::FromStr;
  614. use std::string::ToString;
  615. use super::*;
  616. macro_rules! assert_protoentry_is_parseable {
  617. ($e:expr) => (
  618. let protoentry: Result<ProtoEntry, ProtoverError> = $e.parse();
  619. assert!(protoentry.is_ok(), format!("{:?}", protoentry.err()));
  620. )
  621. }
  622. macro_rules! assert_protoentry_is_unparseable {
  623. ($e:expr) => (
  624. let protoentry: Result<ProtoEntry, ProtoverError> = $e.parse();
  625. assert!(protoentry.is_err());
  626. )
  627. }
  628. #[test]
  629. fn test_protoentry_from_str_multiple_protocols_multiple_versions() {
  630. assert_protoentry_is_parseable!("Cons=3-4 Link=1,3-5");
  631. }
  632. #[test]
  633. fn test_protoentry_from_str_empty() {
  634. assert_protoentry_is_unparseable!("");
  635. }
  636. #[test]
  637. fn test_protoentry_from_str_single_protocol_single_version() {
  638. assert_protoentry_is_parseable!("HSDir=1");
  639. }
  640. #[test]
  641. fn test_protoentry_from_str_unknown_protocol() {
  642. assert_protoentry_is_unparseable!("Ducks=5-7,8");
  643. }
  644. #[test]
  645. fn test_protoentry_from_str_allowed_number_of_versions() {
  646. assert_protoentry_is_parseable!("Desc=1-4294967294");
  647. }
  648. #[test]
  649. fn test_protoentry_from_str_too_many_versions() {
  650. assert_protoentry_is_unparseable!("Desc=1-4294967295");
  651. }
  652. #[test]
  653. fn test_protoentry_from_str_() {
  654. assert_protoentry_is_unparseable!("");
  655. }
  656. #[test]
  657. fn test_protoentry_all_supported_single_protocol_single_version() {
  658. let protocol: UnvalidatedProtoEntry = "Cons=1".parse().unwrap();
  659. let unsupported: Option<UnvalidatedProtoEntry> = protocol.all_supported();
  660. assert_eq!(true, unsupported.is_none());
  661. }
  662. #[test]
  663. fn test_protoentry_all_supported_multiple_protocol_multiple_versions() {
  664. let protocols: UnvalidatedProtoEntry = "Link=3-4 Desc=2".parse().unwrap();
  665. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  666. assert_eq!(true, unsupported.is_none());
  667. }
  668. #[test]
  669. fn test_protoentry_all_supported_three_values() {
  670. let protocols: UnvalidatedProtoEntry = "LinkAuth=1 Microdesc=1-2 Relay=2".parse().unwrap();
  671. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  672. assert_eq!(true, unsupported.is_none());
  673. }
  674. #[test]
  675. fn test_protoentry_all_supported_unknown_protocol() {
  676. let protocols: UnvalidatedProtoEntry = "Wombat=9".parse().unwrap();
  677. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  678. assert_eq!(true, unsupported.is_some());
  679. assert_eq!("Wombat=9", &unsupported.unwrap().to_string());
  680. }
  681. #[test]
  682. fn test_protoentry_all_supported_unsupported_high_version() {
  683. let protocols: UnvalidatedProtoEntry = "HSDir=12-100".parse().unwrap();
  684. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  685. assert_eq!(true, unsupported.is_some());
  686. assert_eq!("HSDir=12-100", &unsupported.unwrap().to_string());
  687. }
  688. #[test]
  689. fn test_protoentry_all_supported_unsupported_low_version() {
  690. let protocols: UnvalidatedProtoEntry = "Cons=0-1".parse().unwrap();
  691. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  692. assert_eq!(true, unsupported.is_some());
  693. assert_eq!("Cons=0", &unsupported.unwrap().to_string());
  694. }
  695. #[test]
  696. fn test_contract_protocol_list() {
  697. let mut versions = "";
  698. assert_eq!(String::from(versions), ProtoSet::from_str(&versions).unwrap().to_string());
  699. versions = "1";
  700. assert_eq!(String::from(versions), ProtoSet::from_str(&versions).unwrap().to_string());
  701. versions = "1-2";
  702. assert_eq!(String::from(versions), ProtoSet::from_str(&versions).unwrap().to_string());
  703. versions = "1,3";
  704. assert_eq!(String::from(versions), ProtoSet::from_str(&versions).unwrap().to_string());
  705. versions = "1-4";
  706. assert_eq!(String::from(versions), ProtoSet::from_str(&versions).unwrap().to_string());
  707. versions = "1,3,5-7";
  708. assert_eq!(String::from(versions), ProtoSet::from_str(&versions).unwrap().to_string());
  709. versions = "1-3,500";
  710. assert_eq!(String::from(versions), ProtoSet::from_str(&versions).unwrap().to_string());
  711. }
  712. }