protover.rs 32 KB

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