hosts.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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::{
  19. collections::{HashMap, HashSet},
  20. sync::Arc,
  21. };
  22. use log::debug;
  23. use rand::{prelude::IteratorRandom, rngs::OsRng};
  24. use smol::lock::RwLock;
  25. use url::Url;
  26. use super::settings::SettingsPtr;
  27. use crate::{
  28. system::{Subscriber, SubscriberPtr, Subscription},
  29. Result,
  30. };
  31. /// Atomic pointer to hosts object
  32. pub type HostsPtr = Arc<Hosts>;
  33. /// Manages a store of network addresses
  34. pub struct Hosts {
  35. /// Set of stored addresses
  36. addrs: RwLock<HashSet<Url>>,
  37. /// Set of stored addresses that are quarantined.
  38. /// We quarantine peers we've been unable to connect to, but we keep them
  39. /// around so we can potentially try them again, up to n tries. This should
  40. /// be helpful in order to self-heal the p2p connections in case we have an
  41. /// Internet interrupt (goblins unplugging cables)
  42. quarantine: RwLock<HashMap<Url, usize>>,
  43. /// Peers we reject from connecting
  44. rejected: RwLock<HashSet<String>>,
  45. /// Subscriber listening for store updates
  46. store_subscriber: SubscriberPtr<usize>,
  47. /// Pointer to configured P2P settings
  48. settings: SettingsPtr,
  49. }
  50. impl Hosts {
  51. /// Create a new hosts list>
  52. pub fn new(settings: SettingsPtr) -> HostsPtr {
  53. Arc::new(Self {
  54. addrs: RwLock::new(HashSet::new()),
  55. quarantine: RwLock::new(HashMap::new()),
  56. rejected: RwLock::new(HashSet::new()),
  57. store_subscriber: Subscriber::new(),
  58. settings,
  59. })
  60. }
  61. /// Append given addrs to the known set.
  62. pub async fn store(&self, addrs: &[Url]) {
  63. debug!(target: "net::hosts::store()", "hosts::store() [START]");
  64. let filtered_addrs = self.filter_addresses(addrs).await;
  65. let filtered_addrs_len = filtered_addrs.len();
  66. if !filtered_addrs.is_empty() {
  67. let mut addrs_map = self.addrs.write().await;
  68. let mut quarantine = self.quarantine.write().await;
  69. for addr in filtered_addrs {
  70. // We assume this was called for a valid peer, and/or we managed
  71. // to successfully connect. So we'll also remove them from the
  72. // quarantine zone if they're there.
  73. quarantine.remove(&addr);
  74. debug!(target: "net::hosts::store()", "Inserting {}", addr);
  75. addrs_map.insert(addr);
  76. }
  77. }
  78. self.store_subscriber.notify(filtered_addrs_len).await;
  79. debug!(target: "net::hosts::store()", "hosts::store() [END]");
  80. }
  81. pub async fn subscribe_store(&self) -> Result<Subscription<usize>> {
  82. let sub = self.store_subscriber.clone().subscribe().await;
  83. Ok(sub)
  84. }
  85. /// Filter given addresses based on certain rulesets and validity.
  86. async fn filter_addresses(&self, addrs: &[Url]) -> Vec<Url> {
  87. debug!(target: "net::hosts::filter_addresses()", "Filtering addrs: {:?}", addrs);
  88. let mut ret = vec![];
  89. let localnet = self.settings.localnet;
  90. for addr_ in addrs {
  91. // Validate that the format is `scheme://host_str:port`
  92. if addr_.host_str().is_none() ||
  93. addr_.port().is_none() ||
  94. addr_.cannot_be_a_base() ||
  95. addr_.path_segments().is_some()
  96. {
  97. continue
  98. }
  99. let host_str = addr_.host_str().unwrap();
  100. if !localnet {
  101. // Our own addresses should never enter the hosts set.
  102. let mut got_own = false;
  103. for ext in &self.settings.external_addrs {
  104. if host_str == ext.host_str().unwrap() {
  105. got_own = true;
  106. break
  107. }
  108. }
  109. if got_own {
  110. continue
  111. }
  112. }
  113. // We do this hack in order to parse IPs properly.
  114. // https://github.com/whatwg/url/issues/749
  115. let addr = Url::parse(&addr_.as_str().replace(addr_.scheme(), "http")).unwrap();
  116. // Filter non-global ranges if we're not allowing localnet.
  117. // Should never be allowed in production, so we don't really care
  118. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  119. if !localnet {
  120. // Filter private IP ranges
  121. match addr.host().unwrap() {
  122. url::Host::Ipv4(ip) => {
  123. if !ip.is_global() {
  124. continue
  125. }
  126. }
  127. url::Host::Ipv6(ip) => {
  128. if !ip.is_global() {
  129. continue
  130. }
  131. }
  132. url::Host::Domain(d) => {
  133. // TODO: This could perhaps be more exhaustive?
  134. if d == "localhost" {
  135. continue
  136. }
  137. }
  138. }
  139. }
  140. match addr_.scheme() {
  141. // Validate that the address is an actual onion.
  142. #[cfg(feature = "p2p-tor")]
  143. "tor" | "tor+tls" => {
  144. use std::str::FromStr;
  145. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  146. continue
  147. }
  148. debug!(target: "net::hosts::filter_addresses()", "[Tor] Valid: {}", host_str);
  149. }
  150. #[cfg(feature = "p2p-nym")]
  151. "nym" | "nym+tls" => continue, // <-- Temp skip
  152. #[cfg(feature = "p2p-tcp")]
  153. "tcp" | "tcp+tls" => {
  154. debug!(target: "net::hosts::filter_addresses()", "[TCP] Valid: {}", host_str);
  155. }
  156. _ => continue,
  157. }
  158. ret.push(addr_.clone());
  159. }
  160. ret
  161. }
  162. pub async fn remove(&self, url: &Url) {
  163. debug!(target: "net::hosts::remove()", "Removing peer {}", url);
  164. self.addrs.write().await.remove(url);
  165. self.quarantine.write().await.remove(url);
  166. }
  167. /// Quarantine a peer. If they've been quarantined for 50 times, forget them.
  168. pub async fn quarantine(&self, url: &Url) {
  169. debug!(target: "net::hosts::quarantine()", "Attempted to quarantine {}", url);
  170. /*
  171. debug!(target: "net::hosts::remove()", "Quarantining peer {}", url);
  172. // Remove from main hosts set
  173. self.addrs.write().await.remove(url);
  174. let mut q = self.quarantine.write().await;
  175. if let Some(retries) = q.get_mut(url) {
  176. *retries += 1;
  177. debug!(target: "net::hosts::quarantine()", "Peer {} quarantined {} times", url, retries);
  178. if *retries == self.settings.hosts_quarantine_limit {
  179. debug!(target: "net::hosts::quarantine()", "Deleting peer {}", url);
  180. q.remove(url);
  181. }
  182. } else {
  183. debug!(target: "net::hosts::remove()", "Added peer {} to quarantine", url);
  184. q.insert(url.clone(), 0);
  185. }
  186. */
  187. }
  188. /// Check if a given peer should be rejected
  189. pub async fn is_rejected(&self, peer: &Url) -> bool {
  190. let Some(hostname) = peer.host_str() else { return false };
  191. // Don't reject localhost.
  192. // This however allows any Tor and Nym connections.
  193. if hostname == "127.0.0.1" || hostname == "[::1]" {
  194. return false
  195. }
  196. self.rejected.read().await.contains(hostname)
  197. }
  198. /// Mark a peer as rejected
  199. pub async fn mark_rejected(&self, peer: &Url) {
  200. // We ignore UNIX sockets here so we will just work
  201. // with stuff that has host_str().
  202. if let Some(hostname) = peer.host_str() {
  203. // Don't reject localhost.
  204. // This however allows any Tor and Nym connections.
  205. if hostname == "127.0.0.1" || hostname == "[::1]" {
  206. return
  207. }
  208. self.rejected.write().await.insert(hostname.to_string());
  209. }
  210. }
  211. /// Unmark a rejected peer
  212. pub async fn unmark_rejected(&self, peer: &Url) {
  213. if let Some(hostname) = peer.host_str() {
  214. self.rejected.write().await.remove(hostname);
  215. }
  216. }
  217. /// Check if the host list is empty.
  218. pub async fn is_empty(&self) -> bool {
  219. self.addrs.read().await.is_empty()
  220. }
  221. /// Check if host is already in the set
  222. pub async fn contains(&self, addr: &Url) -> bool {
  223. self.addrs.read().await.contains(addr)
  224. }
  225. /// Return all known hosts
  226. pub async fn fetch_all(&self) -> Vec<Url> {
  227. self.addrs.read().await.iter().cloned().collect()
  228. }
  229. /// Get up to n random peers from the hosts set.
  230. pub async fn fetch_n_random(&self, n: u32) -> Vec<Url> {
  231. let n = n as usize;
  232. if n == 0 {
  233. return vec![]
  234. }
  235. let addrs = self.addrs.read().await;
  236. let urls = addrs.iter().choose_multiple(&mut OsRng, n.min(addrs.len()));
  237. urls.iter().map(|&url| url.clone()).collect()
  238. }
  239. /// Get up to n random peers that match the given transport schemes from the hosts set.
  240. pub async fn fetch_n_random_with_schemes(&self, schemes: &[String], n: u32) -> Vec<Url> {
  241. let n = n as usize;
  242. if n == 0 {
  243. return vec![]
  244. }
  245. // Retrieve all peers corresponding to that transport schemes
  246. let hosts = self.fetch_with_schemes(schemes, None).await;
  247. if hosts.is_empty() {
  248. return hosts
  249. }
  250. // Grab random ones
  251. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  252. urls.iter().map(|&url| url.clone()).collect()
  253. }
  254. /// Get up to n random peers that don't match the given transport schemes from the hosts set.
  255. pub async fn fetch_n_random_excluding_schemes(&self, schemes: &[String], n: u32) -> Vec<Url> {
  256. let n = n as usize;
  257. if n == 0 {
  258. return vec![]
  259. }
  260. // Retrieve all peers not corresponding to that transport schemes
  261. let hosts = self.fetch_exluding_schemes(schemes, None).await;
  262. if hosts.is_empty() {
  263. return hosts
  264. }
  265. // Grab random ones
  266. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  267. urls.iter().map(|&url| url.clone()).collect()
  268. }
  269. /// Get up to limit peers that match the given transport schemes from the hosts set.
  270. /// If limit was not provided, return all matching peers.
  271. pub async fn fetch_with_schemes(&self, schemes: &[String], limit: Option<usize>) -> Vec<Url> {
  272. let addrs = self.addrs.read().await;
  273. let mut limit = match limit {
  274. Some(l) => l.min(addrs.len()),
  275. None => addrs.len(),
  276. };
  277. let mut ret = vec![];
  278. if limit == 0 {
  279. return ret
  280. }
  281. for addr in addrs.iter() {
  282. if schemes.contains(&addr.scheme().to_string()) {
  283. ret.push(addr.clone());
  284. limit -= 1;
  285. if limit == 0 {
  286. return ret
  287. }
  288. }
  289. }
  290. // If we didn't find any, pick some from the quarantine zone
  291. if ret.is_empty() {
  292. for addr in self.quarantine.read().await.keys() {
  293. if schemes.contains(&addr.scheme().to_string()) {
  294. ret.push(addr.clone());
  295. limit -= 1;
  296. if limit == 0 {
  297. break
  298. }
  299. }
  300. }
  301. }
  302. ret
  303. }
  304. /// Get up to limit peers that don't match the given transport schemes from the hosts set.
  305. /// If limit was not provided, return all matching peers.
  306. pub async fn fetch_exluding_schemes(
  307. &self,
  308. schemes: &[String],
  309. limit: Option<usize>,
  310. ) -> Vec<Url> {
  311. let addrs = self.addrs.read().await;
  312. let mut limit = match limit {
  313. Some(l) => l.min(addrs.len()),
  314. None => addrs.len(),
  315. };
  316. let mut ret = vec![];
  317. if limit == 0 {
  318. return ret
  319. }
  320. for addr in addrs.iter() {
  321. if !schemes.contains(&addr.scheme().to_string()) {
  322. ret.push(addr.clone());
  323. limit -= 1;
  324. if limit == 0 {
  325. return ret
  326. }
  327. }
  328. }
  329. // If we didn't find any, pick some from the quarantine zone
  330. if ret.is_empty() {
  331. for addr in self.quarantine.read().await.keys() {
  332. if !schemes.contains(&addr.scheme().to_string()) {
  333. ret.push(addr.clone());
  334. limit -= 1;
  335. if limit == 0 {
  336. break
  337. }
  338. }
  339. }
  340. }
  341. ret
  342. }
  343. }
  344. #[cfg(test)]
  345. mod tests {
  346. use super::{super::settings::Settings, *};
  347. #[test]
  348. fn test_store_localnet() {
  349. smol::block_on(async {
  350. let settings = Settings {
  351. localnet: true,
  352. external_addrs: vec![
  353. Url::parse("tcp://foo.bar:123").unwrap(),
  354. Url::parse("tcp://lol.cat:321").unwrap(),
  355. ],
  356. ..Default::default()
  357. };
  358. let hosts = Hosts::new(Arc::new(settings.clone()));
  359. hosts.store(&settings.external_addrs).await;
  360. for i in settings.external_addrs {
  361. assert!(hosts.contains(&i).await);
  362. }
  363. let local_hosts = vec![
  364. Url::parse("tcp://localhost:3921").unwrap(),
  365. Url::parse("tcp://127.0.0.1:23957").unwrap(),
  366. Url::parse("tcp://[::1]:21481").unwrap(),
  367. Url::parse("tcp://192.168.10.65:311").unwrap(),
  368. Url::parse("tcp://0.0.0.0:2312").unwrap(),
  369. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  370. ];
  371. hosts.store(&local_hosts).await;
  372. for i in local_hosts {
  373. assert!(hosts.contains(&i).await);
  374. }
  375. let remote_hosts = vec![
  376. Url::parse("tcp://dark.fi:80").unwrap(),
  377. Url::parse("tcp://top.kek:111").unwrap(),
  378. Url::parse("tcp://http.cat:401").unwrap(),
  379. ];
  380. hosts.store(&remote_hosts).await;
  381. for i in remote_hosts {
  382. assert!(hosts.contains(&i).await);
  383. }
  384. });
  385. }
  386. #[test]
  387. fn test_store() {
  388. smol::block_on(async {
  389. let settings = Settings {
  390. localnet: false,
  391. external_addrs: vec![
  392. Url::parse("tcp://foo.bar:123").unwrap(),
  393. Url::parse("tcp://lol.cat:321").unwrap(),
  394. ],
  395. ..Default::default()
  396. };
  397. let hosts = Hosts::new(Arc::new(settings.clone()));
  398. hosts.store(&settings.external_addrs).await;
  399. assert!(hosts.is_empty().await);
  400. let local_hosts = vec![
  401. Url::parse("tcp://localhost:3921").unwrap(),
  402. Url::parse("tcp://127.0.0.1:23957").unwrap(),
  403. Url::parse("tor://[::1]:21481").unwrap(),
  404. Url::parse("tcp://192.168.10.65:311").unwrap(),
  405. Url::parse("tcp+tls://0.0.0.0:2312").unwrap(),
  406. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  407. ];
  408. hosts.store(&local_hosts).await;
  409. assert!(hosts.is_empty().await);
  410. let remote_hosts = vec![
  411. Url::parse("tcp://dark.fi:80").unwrap(),
  412. Url::parse("tcp://http.cat:401").unwrap(),
  413. Url::parse("tcp://foo.bar:111").unwrap(),
  414. ];
  415. hosts.store(&remote_hosts).await;
  416. assert!(hosts.contains(&remote_hosts[0]).await);
  417. assert!(hosts.contains(&remote_hosts[1]).await);
  418. assert!(!hosts.contains(&remote_hosts[2]).await);
  419. });
  420. }
  421. }