protover.rs 31 KB

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