hosts.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::collections::HashSet;
  19. use async_std::sync::{Arc, RwLock};
  20. use log::debug;
  21. use rand::{prelude::IteratorRandom, rngs::OsRng};
  22. use url::Url;
  23. use super::settings::SettingsPtr;
  24. /// Atomic pointer to hosts object
  25. pub type HostsPtr = Arc<Hosts>;
  26. /// Manages a store of network addresses
  27. pub struct Hosts {
  28. /// Set of stored addresses
  29. addrs: RwLock<HashSet<Url>>,
  30. /// Pointer to configured P2P settings
  31. settings: SettingsPtr,
  32. }
  33. impl Hosts {
  34. /// Create a new hosts list. Also initializes private IP ranges used
  35. /// for filtering.
  36. pub fn new(settings: SettingsPtr) -> HostsPtr {
  37. Arc::new(Self { addrs: RwLock::new(HashSet::new()), settings })
  38. }
  39. /// Append given addrs to the known set. Filtering should be done externally.
  40. pub async fn store(&self, addrs: &[Url]) {
  41. debug!(target: "net::hosts::store()", "hosts::store() [START]");
  42. let filtered_addrs = self.filter_addresses(addrs).await;
  43. if !filtered_addrs.is_empty() {
  44. let mut addrs_map = self.addrs.write().await;
  45. for addr in filtered_addrs {
  46. addrs_map.insert(addr);
  47. }
  48. }
  49. debug!(target: "net::hosts::store()", "hosts::store() [END]");
  50. }
  51. /// Filter given addresses based on certain rulesets and validity.
  52. async fn filter_addresses(&self, addrs: &[Url]) -> Vec<Url> {
  53. let mut ret = vec![];
  54. let localnet = self.settings.localnet;
  55. for _addr in addrs {
  56. // Validate that the format is `scheme://host_str:port`
  57. if _addr.host_str().is_none() ||
  58. _addr.port().is_none() ||
  59. _addr.cannot_be_a_base() ||
  60. _addr.path_segments().is_some()
  61. {
  62. continue
  63. }
  64. let host_str = _addr.host_str().unwrap();
  65. if !localnet {
  66. // Our own addresses should never enter the hosts set.
  67. let mut got_own = false;
  68. for ext in &self.settings.external_addrs {
  69. if host_str == ext.host_str().unwrap() {
  70. got_own = true;
  71. break
  72. }
  73. }
  74. if got_own {
  75. continue
  76. }
  77. }
  78. // We do this hack in order to parse IPs properly.
  79. // https://github.com/whatwg/url/issues/749
  80. let addr = Url::parse(&_addr.as_str().replace(_addr.scheme(), "http")).unwrap();
  81. // Filter non-global ranges if we're not allowing localnet.
  82. // Should never be allowed in production, so we don't really care
  83. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  84. if !localnet {
  85. // Filter private IP ranges
  86. match addr.host().unwrap() {
  87. url::Host::Ipv4(ip) => {
  88. if !ip.is_global() {
  89. continue
  90. }
  91. }
  92. url::Host::Ipv6(ip) => {
  93. if !ip.is_global() {
  94. continue
  95. }
  96. }
  97. url::Host::Domain(d) => {
  98. // TODO: This could perhaps be more exhaustive?
  99. if d == "localhost" {
  100. continue
  101. }
  102. }
  103. }
  104. }
  105. match addr.scheme() {
  106. // Validate that the address is an actual onion.
  107. #[cfg(feature = "p2p-transport-tor")]
  108. "tor" | "tor+tls" => {
  109. use std::str::FromStr;
  110. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  111. continue
  112. }
  113. }
  114. #[cfg(feature = "p2p-transport-nym")]
  115. "nym" | "nym+tls" => continue, // <-- Temp skip
  116. #[cfg(feature = "p2p-transport-tcp")]
  117. "tcp" | "tcp+tls" => {}
  118. _ => continue,
  119. }
  120. ret.push(_addr.clone());
  121. }
  122. ret
  123. }
  124. pub async fn remove(&self, url: &Url) -> bool {
  125. self.addrs.write().await.remove(url)
  126. }
  127. /// Check if the host list is empty.
  128. pub async fn is_empty(&self) -> bool {
  129. self.addrs.read().await.is_empty()
  130. }
  131. /// Check if host is already in the set
  132. pub async fn contains(&self, addr: &Url) -> bool {
  133. self.addrs.read().await.contains(addr)
  134. }
  135. /// Return all known hosts
  136. pub async fn load_all(&self) -> Vec<Url> {
  137. self.addrs.read().await.iter().cloned().collect()
  138. }
  139. /// Get up to n random hosts from the hosts set.
  140. pub async fn get_n_random(&self, n: u32) -> Vec<Url> {
  141. let n = n as usize;
  142. let addrs = self.addrs.read().await;
  143. let urls = addrs.iter().choose_multiple(&mut OsRng, n.min(addrs.len()));
  144. let urls = urls.iter().map(|&url| url.clone()).collect();
  145. urls
  146. }
  147. /// Get all peers that match the given transport schemes from the hosts set.
  148. pub async fn load_with_schemes(&self, schemes: &[String]) -> Vec<Url> {
  149. let mut ret = vec![];
  150. for addr in self.addrs.read().await.iter() {
  151. if schemes.contains(&addr.scheme().to_string()) {
  152. ret.push(addr.clone());
  153. }
  154. }
  155. ret
  156. }
  157. }
  158. #[cfg(test)]
  159. mod tests {
  160. use super::{super::settings::Settings, *};
  161. #[async_std::test]
  162. async fn test_store_localnet() {
  163. let mut settings = Settings::default();
  164. settings.localnet = true;
  165. settings.external_addrs = vec![
  166. Url::parse("tcp://foo.bar:123").unwrap(),
  167. Url::parse("tcp://lol.cat:321").unwrap(),
  168. ];
  169. let hosts = Hosts::new(Arc::new(settings.clone()));
  170. hosts.store(&settings.external_addrs).await;
  171. assert!(hosts.is_empty().await);
  172. let local_hosts = vec![
  173. Url::parse("tcp://localhost:3921").unwrap(),
  174. Url::parse("tcp://127.0.0.1:23957").unwrap(),
  175. Url::parse("tcp://[::1]:21481").unwrap(),
  176. Url::parse("tcp://192.168.10.65:311").unwrap(),
  177. Url::parse("tcp://0.0.0.0:2312").unwrap(),
  178. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  179. ];
  180. hosts.store(&local_hosts).await;
  181. assert!(hosts.is_empty().await);
  182. let remote_hosts = vec![
  183. Url::parse("tcp://dark.fi:80").unwrap(),
  184. Url::parse("tcp://top.kek:111").unwrap(),
  185. Url::parse("tcp://http.cat:401").unwrap(),
  186. ];
  187. hosts.store(&remote_hosts).await;
  188. assert!(hosts.is_empty().await);
  189. }
  190. #[async_std::test]
  191. async fn test_store() {
  192. let mut settings = Settings::default();
  193. settings.localnet = false;
  194. settings.external_addrs = vec![
  195. Url::parse("tcp://foo.bar:123").unwrap(),
  196. Url::parse("tcp://lol.cat:321").unwrap(),
  197. ];
  198. let hosts = Hosts::new(Arc::new(settings.clone()));
  199. hosts.store(&settings.external_addrs).await;
  200. assert!(hosts.is_empty().await);
  201. let local_hosts = vec![
  202. Url::parse("tcp://localhost:3921").unwrap(),
  203. Url::parse("tcp://127.0.0.1:23957").unwrap(),
  204. Url::parse("tor://[::1]:21481").unwrap(),
  205. Url::parse("tcp://192.168.10.65:311").unwrap(),
  206. Url::parse("tcp+tls://0.0.0.0:2312").unwrap(),
  207. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  208. ];
  209. hosts.store(&local_hosts).await;
  210. assert!(hosts.is_empty().await);
  211. let remote_hosts = vec![
  212. Url::parse("tcp://dark.fi:80").unwrap(),
  213. Url::parse("tcp://http.cat:401").unwrap(),
  214. Url::parse("tcp://foo.bar:111").unwrap(),
  215. ];
  216. hosts.store(&remote_hosts).await;
  217. assert!(hosts.is_empty().await);
  218. }
  219. }