protover.rs 31 KB

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