protover.rs 31 KB

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