protover.rs 30 KB

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