protover.rs 31 KB

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