protover.rs 28 KB

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