protover.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. // Copyright (c) 2016-2018, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. use std::collections::hash_map;
  4. use std::collections::HashMap;
  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::ProtoSet;
  13. use protoset::Version;
  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. /// 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: protover.c `MAX_PROTOCOLS_TO_EXPAND`
  24. const MAX_PROTOCOLS_TO_EXPAND: usize = (1 << 16);
  25. /// The maximum size an `UnknownProtocol`'s name may be.
  26. pub(crate) const MAX_PROTOCOL_NAME_LENGTH: usize = 100;
  27. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  28. ///
  29. /// C_RUST_COUPLED: protover.h `protocol_type_t`
  30. #[derive(Clone, Hash, Eq, PartialEq, Debug)]
  31. pub enum Protocol {
  32. Cons,
  33. Desc,
  34. DirCache,
  35. HSDir,
  36. HSIntro,
  37. HSRend,
  38. Link,
  39. LinkAuth,
  40. Microdesc,
  41. Relay,
  42. }
  43. impl fmt::Display for Protocol {
  44. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  45. write!(f, "{:?}", self)
  46. }
  47. }
  48. /// Translates a string representation of a protocol into a Proto type.
  49. /// Error if the string is an unrecognized protocol name.
  50. ///
  51. /// C_RUST_COUPLED: protover.c `PROTOCOL_NAMES`
  52. impl FromStr for Protocol {
  53. type Err = ProtoverError;
  54. fn from_str(s: &str) -> Result<Self, Self::Err> {
  55. match s {
  56. "Cons" => Ok(Protocol::Cons),
  57. "Desc" => Ok(Protocol::Desc),
  58. "DirCache" => Ok(Protocol::DirCache),
  59. "HSDir" => Ok(Protocol::HSDir),
  60. "HSIntro" => Ok(Protocol::HSIntro),
  61. "HSRend" => Ok(Protocol::HSRend),
  62. "Link" => Ok(Protocol::Link),
  63. "LinkAuth" => Ok(Protocol::LinkAuth),
  64. "Microdesc" => Ok(Protocol::Microdesc),
  65. "Relay" => Ok(Protocol::Relay),
  66. _ => Err(ProtoverError::UnknownProtocol),
  67. }
  68. }
  69. }
  70. /// A protocol string which is not one of the `Protocols` we currently know
  71. /// about.
  72. #[derive(Clone, Debug, Hash, Eq, PartialEq)]
  73. pub struct UnknownProtocol(String);
  74. impl fmt::Display for UnknownProtocol {
  75. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  76. write!(f, "{}", self.0)
  77. }
  78. }
  79. impl FromStr for UnknownProtocol {
  80. type Err = ProtoverError;
  81. fn from_str(s: &str) -> Result<Self, Self::Err> {
  82. if s.len() <= MAX_PROTOCOL_NAME_LENGTH {
  83. Ok(UnknownProtocol(s.to_string()))
  84. } else {
  85. Err(ProtoverError::ExceedsNameLimit)
  86. }
  87. }
  88. }
  89. impl UnknownProtocol {
  90. /// Create an `UnknownProtocol`, ignoring whether or not it
  91. /// exceeds MAX_PROTOCOL_NAME_LENGTH.
  92. fn from_str_any_len(s: &str) -> Result<Self, ProtoverError> {
  93. Ok(UnknownProtocol(s.to_string()))
  94. }
  95. }
  96. impl From<Protocol> for UnknownProtocol {
  97. fn from(p: Protocol) -> UnknownProtocol {
  98. UnknownProtocol(p.to_string())
  99. }
  100. }
  101. /// Get a CStr representation of current supported protocols, for
  102. /// passing to C, or for converting to a `&str` for Rust.
  103. ///
  104. /// # Returns
  105. ///
  106. /// An `&'static CStr` whose value is the existing protocols supported by tor.
  107. /// Returned data is in the format as follows:
  108. ///
  109. /// "HSDir=1-1 LinkAuth=1"
  110. ///
  111. /// # Note
  112. ///
  113. /// Rust code can use the `&'static CStr` as a normal `&'a str` by
  114. /// calling `protover::get_supported_protocols`.
  115. ///
  116. // C_RUST_COUPLED: protover.c `protover_get_supported_protocols`
  117. pub(crate) fn get_supported_protocols_cstr() -> &'static CStr {
  118. cstr!(
  119. "Cons=1-2 \
  120. Desc=1-2 \
  121. DirCache=1-2 \
  122. HSDir=1-2 \
  123. HSIntro=3-4 \
  124. HSRend=1-2 \
  125. Link=1-5 \
  126. LinkAuth=1,3 \
  127. Microdesc=1-2 \
  128. Relay=1-2"
  129. )
  130. }
  131. /// A map of protocol names to the versions of them which are supported.
  132. #[derive(Clone, Debug, PartialEq, Eq)]
  133. pub struct ProtoEntry(HashMap<Protocol, ProtoSet>);
  134. impl Default for ProtoEntry {
  135. fn default() -> ProtoEntry {
  136. ProtoEntry(HashMap::new())
  137. }
  138. }
  139. impl ProtoEntry {
  140. /// Get an iterator over the `Protocol`s and their `ProtoSet`s in this `ProtoEntry`.
  141. pub fn iter(&self) -> hash_map::Iter<Protocol, ProtoSet> {
  142. self.0.iter()
  143. }
  144. /// Translate the supported tor versions from a string into a
  145. /// ProtoEntry, which is useful when looking up a specific
  146. /// subprotocol.
  147. pub fn supported() -> Result<Self, ProtoverError> {
  148. let supported_cstr: &'static CStr = get_supported_protocols_cstr();
  149. let supported: &str = supported_cstr.to_str().unwrap_or("");
  150. supported.parse()
  151. }
  152. pub fn len(&self) -> usize {
  153. self.0.len()
  154. }
  155. pub fn get(&self, protocol: &Protocol) -> Option<&ProtoSet> {
  156. self.0.get(protocol)
  157. }
  158. pub fn insert(&mut self, key: Protocol, value: ProtoSet) {
  159. self.0.insert(key, value);
  160. }
  161. pub fn remove(&mut self, key: &Protocol) -> Option<ProtoSet> {
  162. self.0.remove(key)
  163. }
  164. pub fn is_empty(&self) -> bool {
  165. self.0.is_empty()
  166. }
  167. }
  168. impl FromStr for ProtoEntry {
  169. type Err = ProtoverError;
  170. /// Parse a string of subprotocol types and their version numbers.
  171. ///
  172. /// # Inputs
  173. ///
  174. /// * A `protocol_entry` string, comprised of a keywords, an "=" sign, and
  175. /// one or more version numbers, each separated by a space. For example,
  176. /// `"Cons=3-4 HSDir=1"`.
  177. ///
  178. /// # Returns
  179. ///
  180. /// A `Result` whose `Ok` value is a `ProtoEntry`.
  181. /// Otherwise, the `Err` value of this `Result` is a `ProtoverError`.
  182. fn from_str(protocol_entry: &str) -> Result<ProtoEntry, ProtoverError> {
  183. let mut proto_entry: ProtoEntry = ProtoEntry::default();
  184. let entries = protocol_entry.split(' ');
  185. for entry in entries {
  186. let mut parts = entry.splitn(2, '=');
  187. let proto = match parts.next() {
  188. Some(n) => n,
  189. None => return Err(ProtoverError::Unparseable),
  190. };
  191. let vers = match parts.next() {
  192. Some(n) => n,
  193. None => return Err(ProtoverError::Unparseable),
  194. };
  195. let versions: ProtoSet = vers.parse()?;
  196. let proto_name: Protocol = proto.parse()?;
  197. proto_entry.insert(proto_name, versions);
  198. if proto_entry.len() > MAX_PROTOCOLS_TO_EXPAND {
  199. return Err(ProtoverError::ExceedsMax);
  200. }
  201. }
  202. Ok(proto_entry)
  203. }
  204. }
  205. /// Generate an implementation of `ToString` for either a `ProtoEntry` or an
  206. /// `UnvalidatedProtoEntry`.
  207. macro_rules! impl_to_string_for_proto_entry {
  208. ($t:ty) => {
  209. impl ToString for $t {
  210. fn to_string(&self) -> String {
  211. let mut parts: Vec<String> = Vec::new();
  212. for (protocol, versions) in self.iter() {
  213. parts.push(format!("{}={}", protocol.to_string(), versions.to_string()));
  214. }
  215. parts.sort_unstable();
  216. parts.join(" ")
  217. }
  218. }
  219. };
  220. }
  221. impl_to_string_for_proto_entry!(ProtoEntry);
  222. impl_to_string_for_proto_entry!(UnvalidatedProtoEntry);
  223. /// A `ProtoEntry`, but whose `Protocols` can be any `UnknownProtocol`, not just
  224. /// the supported ones enumerated in `Protocols`. The protocol versions are
  225. /// validated, however.
  226. #[derive(Clone, Debug, PartialEq, Eq)]
  227. pub struct UnvalidatedProtoEntry(HashMap<UnknownProtocol, ProtoSet>);
  228. impl Default for UnvalidatedProtoEntry {
  229. fn default() -> UnvalidatedProtoEntry {
  230. UnvalidatedProtoEntry(HashMap::new())
  231. }
  232. }
  233. impl UnvalidatedProtoEntry {
  234. /// Get an iterator over the `Protocol`s and their `ProtoSet`s in this `ProtoEntry`.
  235. pub fn iter(&self) -> hash_map::Iter<UnknownProtocol, ProtoSet> {
  236. self.0.iter()
  237. }
  238. pub fn get(&self, protocol: &UnknownProtocol) -> Option<&ProtoSet> {
  239. self.0.get(protocol)
  240. }
  241. pub fn insert(&mut self, key: UnknownProtocol, value: ProtoSet) {
  242. self.0.insert(key, value);
  243. }
  244. pub fn remove(&mut self, key: &UnknownProtocol) -> Option<ProtoSet> {
  245. self.0.remove(key)
  246. }
  247. pub fn is_empty(&self) -> bool {
  248. self.0.is_empty()
  249. }
  250. pub fn len(&self) -> usize {
  251. let mut total: usize = 0;
  252. for (_, versions) in self.iter() {
  253. total += versions.len();
  254. }
  255. total
  256. }
  257. /// Determine if we support every protocol a client supports, and if not,
  258. /// determine which protocols we do not have support for.
  259. ///
  260. /// # Returns
  261. ///
  262. /// Optionally, return parameters which the client supports but which we do not.
  263. ///
  264. /// # Examples
  265. /// ```
  266. /// use protover::UnvalidatedProtoEntry;
  267. ///
  268. /// let protocols: UnvalidatedProtoEntry = "LinkAuth=1 Microdesc=1-2 Relay=2".parse().unwrap();
  269. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  270. /// assert_eq!(true, unsupported.is_none());
  271. ///
  272. /// let protocols: UnvalidatedProtoEntry = "Link=1-2 Wombat=9".parse().unwrap();
  273. /// let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  274. /// assert_eq!(true, unsupported.is_some());
  275. /// assert_eq!("Wombat=9", &unsupported.unwrap().to_string());
  276. /// ```
  277. pub fn all_supported(&self) -> Option<UnvalidatedProtoEntry> {
  278. let mut unsupported: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  279. let supported: ProtoEntry = match ProtoEntry::supported() {
  280. Ok(x) => x,
  281. Err(_) => return None,
  282. };
  283. for (protocol, versions) in self.iter() {
  284. let is_supported: Result<Protocol, ProtoverError> = protocol.0.parse();
  285. let supported_protocol: Protocol;
  286. // If the protocol wasn't even in the enum, then we definitely don't
  287. // know about it and don't support any of its versions.
  288. if is_supported.is_err() {
  289. if !versions.is_empty() {
  290. unsupported.insert(protocol.clone(), versions.clone());
  291. }
  292. continue;
  293. } else {
  294. supported_protocol = is_supported.unwrap();
  295. }
  296. let maybe_supported_versions: Option<&ProtoSet> = supported.get(&supported_protocol);
  297. let supported_versions: &ProtoSet;
  298. let mut unsupported_versions: ProtoSet;
  299. // If the protocol wasn't in the map, then we don't know about it
  300. // and don't support any of its versions. Add its versions to the
  301. // map (if it has versions).
  302. if maybe_supported_versions.is_none() {
  303. if !versions.is_empty() {
  304. unsupported.insert(protocol.clone(), versions.clone());
  305. }
  306. continue;
  307. } else {
  308. supported_versions = maybe_supported_versions.unwrap();
  309. }
  310. unsupported_versions = versions.clone();
  311. unsupported_versions.retain(|x| !supported_versions.contains(x));
  312. if !unsupported_versions.is_empty() {
  313. unsupported.insert(protocol.clone(), unsupported_versions);
  314. }
  315. }
  316. if unsupported.is_empty() {
  317. return None;
  318. }
  319. Some(unsupported)
  320. }
  321. /// Determine if we have support for some protocol and version.
  322. ///
  323. /// # Inputs
  324. ///
  325. /// * `proto`, an `UnknownProtocol` to test support for
  326. /// * `vers`, a `Version` which we will go on to determine whether the
  327. /// specified protocol supports.
  328. ///
  329. /// # Return
  330. ///
  331. /// Returns `true` iff this `UnvalidatedProtoEntry` includes support for the
  332. /// indicated protocol and version, and `false` otherwise.
  333. ///
  334. /// # Examples
  335. ///
  336. /// ```
  337. /// # use std::str::FromStr;
  338. /// use protover::*;
  339. /// # use protover::errors::ProtoverError;
  340. ///
  341. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  342. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=1 Doggo=3-5".parse()?;
  343. /// assert_eq!(true, proto.supports_protocol(&Protocol::Cons.into(), &1));
  344. /// assert_eq!(false, proto.supports_protocol(&Protocol::Cons.into(), &5));
  345. /// assert_eq!(true, proto.supports_protocol(&UnknownProtocol::from_str("Doggo")?, &4));
  346. /// # Ok(proto)
  347. /// # } fn main () { do_test(); }
  348. /// ```
  349. pub fn supports_protocol(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  350. let supported_versions: &ProtoSet = match self.get(proto) {
  351. Some(n) => n,
  352. None => return false,
  353. };
  354. supported_versions.contains(&vers)
  355. }
  356. /// As `UnvalidatedProtoEntry::supports_protocol()`, but also returns `true`
  357. /// if any later version of the protocol is supported.
  358. ///
  359. /// # Examples
  360. /// ```
  361. /// use protover::*;
  362. /// # use protover::errors::ProtoverError;
  363. ///
  364. /// # fn do_test () -> Result<UnvalidatedProtoEntry, ProtoverError> {
  365. /// let proto: UnvalidatedProtoEntry = "Link=3-4 Cons=5".parse()?;
  366. ///
  367. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &5));
  368. /// assert_eq!(true, proto.supports_protocol_or_later(&Protocol::Cons.into(), &4));
  369. /// assert_eq!(false, proto.supports_protocol_or_later(&Protocol::Cons.into(), &6));
  370. /// # Ok(proto)
  371. /// # } fn main () { do_test(); }
  372. /// ```
  373. pub fn supports_protocol_or_later(&self, proto: &UnknownProtocol, vers: &Version) -> bool {
  374. let supported_versions: &ProtoSet = match self.get(&proto) {
  375. Some(n) => n,
  376. None => return false,
  377. };
  378. supported_versions.iter().any(|v| v.1 >= *vers)
  379. }
  380. /// Split a string containing (potentially) several protocols and their
  381. /// versions into a `Vec` of tuples of string in `(protocol, versions)`
  382. /// form.
  383. ///
  384. /// # Inputs
  385. ///
  386. /// A &str in the form `"Link=3-4 Cons=5"`.
  387. ///
  388. /// # Returns
  389. ///
  390. /// A `Result` whose `Ok` variant is a `Vec<(&str, &str)>` of `(protocol,
  391. /// versions)`, or whose `Err` variant is a `ProtoverError`.
  392. ///
  393. /// # Errors
  394. ///
  395. /// This will error with a `ProtoverError::Unparseable` if any of the
  396. /// following are true:
  397. ///
  398. /// * If a protocol name is an empty string, e.g. `"Cons=1,3 =3-5"`.
  399. /// * If an entry has no equals sign, e.g. `"Cons=1,3 Desc"`.
  400. /// * If there is leading or trailing whitespace, e.g. `" Cons=1,3 Link=3"`.
  401. /// * If there is any other extra whitespice, e.g. `"Cons=1,3 Link=3"`.
  402. fn parse_protocol_and_version_str<'a>(
  403. protocol_string: &'a str,
  404. ) -> Result<Vec<(&'a str, &'a str)>, ProtoverError> {
  405. let mut protovers: Vec<(&str, &str)> = Vec::new();
  406. for subproto in protocol_string.split(' ') {
  407. let mut parts = subproto.splitn(2, '=');
  408. let name = match parts.next() {
  409. Some("") => return Err(ProtoverError::Unparseable),
  410. Some(n) => n,
  411. None => return Err(ProtoverError::Unparseable),
  412. };
  413. let vers = match parts.next() {
  414. Some(n) => n,
  415. None => return Err(ProtoverError::Unparseable),
  416. };
  417. protovers.push((name, vers));
  418. }
  419. Ok(protovers)
  420. }
  421. }
  422. impl FromStr for UnvalidatedProtoEntry {
  423. type Err = ProtoverError;
  424. /// Parses a protocol list without validating the protocol names.
  425. ///
  426. /// # Inputs
  427. ///
  428. /// * `protocol_string`, a string comprised of keys and values, both which are
  429. /// strings. The keys are the protocol names while values are a string
  430. /// representation of the supported versions.
  431. ///
  432. /// The input is _not_ expected to be a subset of the Protocol types
  433. ///
  434. /// # Returns
  435. ///
  436. /// A `Result` whose `Ok` value is an `UnvalidatedProtoEntry`.
  437. ///
  438. /// The returned `Result`'s `Err` value is an `ProtoverError`.
  439. ///
  440. /// # Errors
  441. ///
  442. /// This function will error if:
  443. ///
  444. /// * The protocol string does not follow the "protocol_name=version_list"
  445. /// expected format, or
  446. /// * If the version string is malformed. See `impl FromStr for ProtoSet`.
  447. fn from_str(protocol_string: &str) -> Result<UnvalidatedProtoEntry, ProtoverError> {
  448. let mut parsed: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  449. let parts: Vec<(&str, &str)> =
  450. UnvalidatedProtoEntry::parse_protocol_and_version_str(protocol_string)?;
  451. for &(name, vers) in parts.iter() {
  452. let versions = ProtoSet::from_str(vers)?;
  453. let protocol = UnknownProtocol::from_str(name)?;
  454. parsed.insert(protocol, versions);
  455. }
  456. Ok(parsed)
  457. }
  458. }
  459. impl UnvalidatedProtoEntry {
  460. /// Create an `UnknownProtocol`, ignoring whether or not it
  461. /// exceeds MAX_PROTOCOL_NAME_LENGTH.
  462. pub(crate) fn from_str_any_len(
  463. protocol_string: &str,
  464. ) -> Result<UnvalidatedProtoEntry, ProtoverError> {
  465. let mut parsed: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  466. let parts: Vec<(&str, &str)> =
  467. UnvalidatedProtoEntry::parse_protocol_and_version_str(protocol_string)?;
  468. for &(name, vers) in parts.iter() {
  469. let versions = ProtoSet::from_str(vers)?;
  470. let protocol = UnknownProtocol::from_str_any_len(name)?;
  471. parsed.insert(protocol, versions);
  472. }
  473. Ok(parsed)
  474. }
  475. }
  476. /// Pretend a `ProtoEntry` is actually an `UnvalidatedProtoEntry`.
  477. impl From<ProtoEntry> for UnvalidatedProtoEntry {
  478. fn from(proto_entry: ProtoEntry) -> UnvalidatedProtoEntry {
  479. let mut unvalidated: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  480. for (protocol, versions) in proto_entry.iter() {
  481. unvalidated.insert(UnknownProtocol::from(protocol.clone()), versions.clone());
  482. }
  483. unvalidated
  484. }
  485. }
  486. /// A mapping of protocols to a count of how many times each of their `Version`s
  487. /// were voted for or supported.
  488. ///
  489. /// # Warning
  490. ///
  491. /// The "protocols" are *not* guaranteed to be known/supported `Protocol`s, in
  492. /// order to allow new subprotocols to be introduced even if Directory
  493. /// Authorities don't yet know of them.
  494. pub struct ProtoverVote(HashMap<UnknownProtocol, HashMap<Version, usize>>);
  495. impl Default for ProtoverVote {
  496. fn default() -> ProtoverVote {
  497. ProtoverVote(HashMap::new())
  498. }
  499. }
  500. impl IntoIterator for ProtoverVote {
  501. type Item = (UnknownProtocol, HashMap<Version, usize>);
  502. type IntoIter = hash_map::IntoIter<UnknownProtocol, HashMap<Version, usize>>;
  503. fn into_iter(self) -> Self::IntoIter {
  504. self.0.into_iter()
  505. }
  506. }
  507. impl ProtoverVote {
  508. pub fn entry(
  509. &mut self,
  510. key: UnknownProtocol,
  511. ) -> hash_map::Entry<UnknownProtocol, HashMap<Version, usize>> {
  512. self.0.entry(key)
  513. }
  514. /// Protocol voting implementation.
  515. ///
  516. /// Given a slice of `UnvalidatedProtoEntry`s and a vote `threshold`, return
  517. /// a new `UnvalidatedProtoEntry` encoding all of the protocols that are
  518. /// listed by at least `threshold` of the inputs.
  519. ///
  520. /// # Examples
  521. ///
  522. /// ```
  523. /// use protover::ProtoverVote;
  524. /// use protover::UnvalidatedProtoEntry;
  525. ///
  526. /// let protos: &[UnvalidatedProtoEntry] = &["Link=3-4".parse().unwrap(),
  527. /// "Link=3".parse().unwrap()];
  528. /// let vote = ProtoverVote::compute(protos, &2);
  529. /// assert_eq!("Link=3", vote.to_string());
  530. /// ```
  531. // C_RUST_COUPLED: protover.c protover_compute_vote
  532. pub fn compute(
  533. proto_entries: &[UnvalidatedProtoEntry],
  534. threshold: &usize,
  535. ) -> UnvalidatedProtoEntry {
  536. let mut all_count: ProtoverVote = ProtoverVote::default();
  537. let mut final_output: UnvalidatedProtoEntry = UnvalidatedProtoEntry::default();
  538. if proto_entries.is_empty() {
  539. return final_output;
  540. }
  541. // parse and collect all of the protos and their versions and collect them
  542. for vote in proto_entries {
  543. // C_RUST_DIFFERS: This doesn't actually differ, bu this check on
  544. // the total is here to make it match. Because the C version calls
  545. // expand_protocol_list() which checks if there would be too many
  546. // subprotocols *or* individual version numbers, i.e. more than
  547. // MAX_PROTOCOLS_TO_EXPAND, and does this *per vote*, we need to
  548. // match it's behaviour and ensure we're not allowing more than it
  549. // would.
  550. if vote.len() > MAX_PROTOCOLS_TO_EXPAND {
  551. continue;
  552. }
  553. for (protocol, versions) in vote.iter() {
  554. let supported_vers: &mut HashMap<Version, usize> =
  555. all_count.entry(protocol.clone()).or_insert(HashMap::new());
  556. for version in versions.clone().expand() {
  557. let counter: &mut usize = supported_vers.entry(version).or_insert(0);
  558. *counter += 1;
  559. }
  560. }
  561. }
  562. for (protocol, mut versions) in all_count {
  563. // Go through and remove versions that are less than the threshold
  564. versions.retain(|_, count| *count as usize >= *threshold);
  565. if versions.len() > 0 {
  566. let voted_versions: Vec<Version> = versions.keys().cloned().collect();
  567. let voted_protoset: ProtoSet = ProtoSet::from(voted_versions);
  568. final_output.insert(protocol, voted_protoset);
  569. }
  570. }
  571. final_output
  572. }
  573. }
  574. /// Returns a boolean indicating whether the given protocol and version is
  575. /// supported in any of the existing Tor protocols
  576. ///
  577. /// # Examples
  578. /// ```
  579. /// use protover::is_supported_here;
  580. /// use protover::Protocol;
  581. ///
  582. /// let is_supported = is_supported_here(&Protocol::Link, &10);
  583. /// assert_eq!(false, is_supported);
  584. ///
  585. /// let is_supported = is_supported_here(&Protocol::Link, &1);
  586. /// assert_eq!(true, is_supported);
  587. /// ```
  588. pub fn is_supported_here(proto: &Protocol, vers: &Version) -> bool {
  589. let currently_supported: ProtoEntry = match ProtoEntry::supported() {
  590. Ok(result) => result,
  591. Err(_) => return false,
  592. };
  593. let supported_versions = match currently_supported.get(proto) {
  594. Some(n) => n,
  595. None => return false,
  596. };
  597. supported_versions.contains(vers)
  598. }
  599. /// Since older versions of Tor cannot infer their own subprotocols,
  600. /// determine which subprotocols are supported by older Tor versions.
  601. ///
  602. /// # Inputs
  603. ///
  604. /// * `version`, a string comprised of "[0-9a-z.-]"
  605. ///
  606. /// # Returns
  607. ///
  608. /// A `&'static CStr` encoding a list of protocol names and supported
  609. /// versions. The string takes the following format:
  610. ///
  611. /// "HSDir=1-1 LinkAuth=1"
  612. ///
  613. /// This function returns the protocols that are supported by the version input,
  614. /// only for tor versions older than `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`
  615. /// (but not older than 0.2.4.19). For newer tors (or older than 0.2.4.19), it
  616. /// returns an empty string.
  617. ///
  618. /// # Note
  619. ///
  620. /// This function is meant to be called for/within FFI code. If you'd
  621. /// like to use this code in Rust, please see `compute_for_old_tor()`.
  622. //
  623. // C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  624. pub(crate) fn compute_for_old_tor_cstr(version: &str) -> &'static CStr {
  625. let empty: &'static CStr = cstr!("");
  626. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  627. return empty;
  628. }
  629. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  630. return cstr!(
  631. "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  632. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2"
  633. );
  634. }
  635. if c_tor_version_as_new_as(version, "0.2.7.5") {
  636. return cstr!(
  637. "Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  638. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2"
  639. );
  640. }
  641. if c_tor_version_as_new_as(version, "0.2.4.19") {
  642. return cstr!(
  643. "Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  644. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2"
  645. );
  646. }
  647. empty
  648. }
  649. /// Since older versions of Tor cannot infer their own subprotocols,
  650. /// determine which subprotocols are supported by older Tor versions.
  651. ///
  652. /// # Inputs
  653. ///
  654. /// * `version`, a string comprised of "[0-9a-z.-]"
  655. ///
  656. /// # Returns
  657. ///
  658. /// A `Result` whose `Ok` value is an `&'static str` encoding a list of protocol
  659. /// names and supported versions. The string takes the following format:
  660. ///
  661. /// "HSDir=1-1 LinkAuth=1"
  662. ///
  663. /// This function returns the protocols that are supported by the version input,
  664. /// only for tor versions older than `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`.
  665. /// (but not older than 0.2.4.19). For newer tors (or older than 0.2.4.19), its
  666. /// `Ok` `Result` contains an empty string.
  667. ///
  668. /// Otherwise, its `Err` contains a `ProtoverError::Unparseable` if the
  669. /// `version` string was invalid utf-8.
  670. ///
  671. /// # Note
  672. ///
  673. /// This function is meant to be called for/within non-FFI Rust code.
  674. //
  675. // C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  676. pub fn compute_for_old_tor(version: &str) -> Result<&'static str, ProtoverError> {
  677. // .to_str() fails with a Utf8Error if it couldn't validate the
  678. // utf-8, so convert that here into an Unparseable ProtoverError.
  679. compute_for_old_tor_cstr(version)
  680. .to_str()
  681. .or(Err(ProtoverError::Unparseable))
  682. }
  683. #[cfg(test)]
  684. mod test {
  685. use std::str::FromStr;
  686. use std::string::ToString;
  687. use super::*;
  688. macro_rules! assert_protoentry_is_parseable {
  689. ($e:expr) => {
  690. let protoentry: Result<ProtoEntry, ProtoverError> = $e.parse();
  691. assert!(protoentry.is_ok(), format!("{:?}", protoentry.err()));
  692. };
  693. }
  694. macro_rules! assert_protoentry_is_unparseable {
  695. ($e:expr) => {
  696. let protoentry: Result<ProtoEntry, ProtoverError> = $e.parse();
  697. assert!(protoentry.is_err());
  698. };
  699. }
  700. #[test]
  701. fn test_protoentry_from_str_multiple_protocols_multiple_versions() {
  702. assert_protoentry_is_parseable!("Cons=3-4 Link=1,3-5");
  703. }
  704. #[test]
  705. fn test_protoentry_from_str_empty() {
  706. assert_protoentry_is_unparseable!("");
  707. }
  708. #[test]
  709. fn test_protoentry_from_str_single_protocol_single_version() {
  710. assert_protoentry_is_parseable!("HSDir=1");
  711. }
  712. #[test]
  713. fn test_protoentry_from_str_unknown_protocol() {
  714. assert_protoentry_is_unparseable!("Ducks=5-7,8");
  715. }
  716. #[test]
  717. fn test_protoentry_from_str_allowed_number_of_versions() {
  718. assert_protoentry_is_parseable!("Desc=1-4294967294");
  719. }
  720. #[test]
  721. fn test_protoentry_from_str_too_many_versions() {
  722. assert_protoentry_is_unparseable!("Desc=1-4294967295");
  723. }
  724. #[test]
  725. fn test_protoentry_from_str_() {
  726. assert_protoentry_is_unparseable!("");
  727. }
  728. #[test]
  729. fn test_protoentry_all_supported_single_protocol_single_version() {
  730. let protocol: UnvalidatedProtoEntry = "Cons=1".parse().unwrap();
  731. let unsupported: Option<UnvalidatedProtoEntry> = protocol.all_supported();
  732. assert_eq!(true, unsupported.is_none());
  733. }
  734. #[test]
  735. fn test_protoentry_all_supported_multiple_protocol_multiple_versions() {
  736. let protocols: UnvalidatedProtoEntry = "Link=3-4 Desc=2".parse().unwrap();
  737. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  738. assert_eq!(true, unsupported.is_none());
  739. }
  740. #[test]
  741. fn test_protoentry_all_supported_three_values() {
  742. let protocols: UnvalidatedProtoEntry = "LinkAuth=1 Microdesc=1-2 Relay=2".parse().unwrap();
  743. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  744. assert_eq!(true, unsupported.is_none());
  745. }
  746. #[test]
  747. fn test_protoentry_all_supported_unknown_protocol() {
  748. let protocols: UnvalidatedProtoEntry = "Wombat=9".parse().unwrap();
  749. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  750. assert_eq!(true, unsupported.is_some());
  751. assert_eq!("Wombat=9", &unsupported.unwrap().to_string());
  752. }
  753. #[test]
  754. fn test_protoentry_all_supported_unsupported_high_version() {
  755. let protocols: UnvalidatedProtoEntry = "HSDir=12-100".parse().unwrap();
  756. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  757. assert_eq!(true, unsupported.is_some());
  758. assert_eq!("HSDir=12-100", &unsupported.unwrap().to_string());
  759. }
  760. #[test]
  761. fn test_protoentry_all_supported_unsupported_low_version() {
  762. let protocols: UnvalidatedProtoEntry = "HSIntro=2-3".parse().unwrap();
  763. let unsupported: Option<UnvalidatedProtoEntry> = protocols.all_supported();
  764. assert_eq!(true, unsupported.is_some());
  765. assert_eq!("HSIntro=2", &unsupported.unwrap().to_string());
  766. }
  767. #[test]
  768. fn test_contract_protocol_list() {
  769. let mut versions = "";
  770. assert_eq!(
  771. String::from(versions),
  772. ProtoSet::from_str(&versions).unwrap().to_string()
  773. );
  774. versions = "1";
  775. assert_eq!(
  776. String::from(versions),
  777. ProtoSet::from_str(&versions).unwrap().to_string()
  778. );
  779. versions = "1-2";
  780. assert_eq!(
  781. String::from(versions),
  782. ProtoSet::from_str(&versions).unwrap().to_string()
  783. );
  784. versions = "1,3";
  785. assert_eq!(
  786. String::from(versions),
  787. ProtoSet::from_str(&versions).unwrap().to_string()
  788. );
  789. versions = "1-4";
  790. assert_eq!(
  791. String::from(versions),
  792. ProtoSet::from_str(&versions).unwrap().to_string()
  793. );
  794. versions = "1,3,5-7";
  795. assert_eq!(
  796. String::from(versions),
  797. ProtoSet::from_str(&versions).unwrap().to_string()
  798. );
  799. versions = "1-3,500";
  800. assert_eq!(
  801. String::from(versions),
  802. ProtoSet::from_str(&versions).unwrap().to_string()
  803. );
  804. }
  805. }