hosts.rs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. time::SystemTime,
  22. };
  23. use log::debug;
  24. use rand::{prelude::IteratorRandom, rngs::OsRng, Rng};
  25. use smol::{lock::RwLock, Executor};
  26. use url::Url;
  27. use super::{
  28. connector::Connector, p2p::P2pPtr, protocol::ProtocolVersion, session::Session,
  29. settings::SettingsPtr,
  30. };
  31. use crate::{
  32. system::{Subscriber, SubscriberPtr, Subscription},
  33. Result,
  34. };
  35. /// Atomic pointer to hosts object
  36. pub type HostsPtr = Arc<Hosts>;
  37. // An array containing all possible local host strings
  38. // TODO: This could perhaps be more exhaustive?
  39. pub const LOCAL_HOST_STRS: [&str; 2] = ["localhost", "localhost.localdomain"];
  40. /// Manages a store of network addresses
  41. pub struct Hosts {
  42. // Intermediary node list that is periodically probed and updated to whitelist.
  43. greylist: RwLock<Vec<(Url, u64)>>,
  44. // Recently seen nodes.
  45. whitelist: RwLock<Vec<(Url, u64)>>,
  46. /// Set of stored addresses
  47. addrs: RwLock<HashSet<Url>>,
  48. /// Set of stored addresses that are quarantined.
  49. /// We quarantine peers we've been unable to connect to, but we keep them
  50. /// around so we can potentially try them again, up to n tries. This should
  51. /// be helpful in order to self-heal the p2p connections in case we have an
  52. /// Internet interrupt (goblins unplugging cables)
  53. quarantine: RwLock<HashMap<Url, usize>>,
  54. /// Peers we reject from connecting
  55. rejected: RwLock<HashSet<String>>,
  56. /// Subscriber listening for store updates
  57. store_subscriber: SubscriberPtr<usize>,
  58. /// Pointer to configured P2P settings
  59. settings: SettingsPtr,
  60. }
  61. impl Hosts {
  62. /// Create a new hosts list>
  63. pub fn new(settings: SettingsPtr) -> HostsPtr {
  64. Arc::new(Self {
  65. whitelist: RwLock::new(Vec::new()),
  66. greylist: RwLock::new(Vec::new()),
  67. addrs: RwLock::new(HashSet::new()),
  68. quarantine: RwLock::new(HashMap::new()),
  69. rejected: RwLock::new(HashSet::new()),
  70. store_subscriber: Subscriber::new(),
  71. settings,
  72. })
  73. }
  74. /// Append given addrs to the known set.
  75. pub async fn store(&self, addrs: &[Url]) {
  76. debug!(target: "net::hosts::store()", "hosts::store() [START]");
  77. let filtered_addrs = self.filter_addresses(addrs).await;
  78. let filtered_addrs_len = filtered_addrs.len();
  79. if !filtered_addrs.is_empty() {
  80. let mut addrs_map = self.addrs.write().await;
  81. for addr in filtered_addrs {
  82. debug!(target: "net::hosts::store()", "Inserting {}", addr);
  83. addrs_map.insert(addr);
  84. }
  85. }
  86. self.store_subscriber.notify(filtered_addrs_len).await;
  87. debug!(target: "net::hosts::store()", "hosts::store() [END]");
  88. }
  89. // Store the address in the whitelist if we don't have it.
  90. // Otherwise, update the last_seen field.
  91. // TODO: test the performance of this method. It might be costly.
  92. pub async fn whitelist_store_or_update(&self, addr: &Url, last_seen: u64) {
  93. debug!(target: "net::hosts::whitelist_store_or_update()", "hosts::whitelist_store_or_update() [START]");
  94. if !self.whitelist_contains(addr).await {
  95. self.whitelist_store(addr, last_seen).await;
  96. } else {
  97. let index = self.get_whitelist_index_at_addr(addr).await;
  98. self.whitelist_update_last_seen(addr, last_seen, index).await;
  99. }
  100. }
  101. // Update the last_seen field for a Url on the whitelist.
  102. pub async fn whitelist_update(&self, addr: &Url, last_seen: u64) {
  103. let index = self.get_whitelist_index_at_addr(addr).await;
  104. self.whitelist_update_last_seen(addr, last_seen, index).await;
  105. }
  106. // Append host to the greylist. Called on learning of a new peer.
  107. pub async fn greylist_store(&self, addrs: &[(Url, u64)]) {
  108. debug!(target: "net::hosts::greylist_store()", "hosts::greylist_store() [START]");
  109. let filtered_addrs = self.filter_addresses2(addrs).await;
  110. let filtered_addrs_len = filtered_addrs.len();
  111. if !filtered_addrs.is_empty() {
  112. let mut greylist = self.greylist.write().await;
  113. // Remove oldest element if the greylist reaches max size.
  114. if greylist.len() == 5000 {
  115. let last_entry = greylist.pop().unwrap();
  116. debug!(target: "net::hosts::greylist_store()", "Greylist reached max size. Removed {:?}", last_entry);
  117. }
  118. for (addr, last_seen) in filtered_addrs {
  119. debug!(target: "net::hosts::greylist_store()", "Inserting {}", addr);
  120. greylist.push((addr.clone(), last_seen.clone()))
  121. }
  122. // Sort the list by last_seen.
  123. greylist.sort_unstable_by_key(|entry| entry.1);
  124. }
  125. self.store_subscriber.notify(filtered_addrs_len).await;
  126. debug!(target: "net::hosts::greylist_store()", "hosts::greylist_store() [END]");
  127. }
  128. // Append host to the whitelist. Called after a successful interaction with an online peer.
  129. pub async fn whitelist_store(&self, addr: &Url, last_seen: u64) {
  130. debug!(target: "net::hosts::whitelist_store()", "hosts::whitelist_store() [START]");
  131. let mut whitelist = self.whitelist.write().await;
  132. debug!(target: "net::hosts::whitelist_store()", "Inserting {}. Last seen {:?}", addr, last_seen);
  133. // Remove oldest element if the whitelist reaches max size.
  134. if whitelist.len() == 1000 {
  135. let last_entry = whitelist.pop().unwrap();
  136. debug!(target: "net::hosts::whitelist_store()", "Whitelist reached max size. Removed {:?}", last_entry);
  137. }
  138. whitelist.push((addr.clone(), last_seen));
  139. // Sort the list by last_seen.
  140. whitelist.sort_unstable_by_key(|entry| entry.1);
  141. debug!(target: "net::hosts::whitelist_store()", "hosts::greylist_store() [END]");
  142. }
  143. // Update the last_seen field of a peer on the whitelist.
  144. pub async fn whitelist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  145. debug!(target: "net::hosts::update_last_seen()", "hosts::update_last_seen() [START]");
  146. let mut whitelist = self.whitelist.write().await;
  147. whitelist[index] = (addr.clone(), last_seen);
  148. }
  149. pub async fn subscribe_store(&self) -> Result<Subscription<usize>> {
  150. let sub = self.store_subscriber.clone().subscribe().await;
  151. Ok(sub)
  152. }
  153. // Verify whether a URL is local.
  154. // NOTE: This function is stateless and not specific to
  155. // `Hosts`. For this reason, it might make more sense
  156. // to move this function to a more appropriate location
  157. // in the codebase.
  158. pub async fn is_local_host(&self, url: Url) -> bool {
  159. // Reject Urls without host strings.
  160. if url.host_str().is_none() {
  161. return false
  162. }
  163. // We do this hack in order to parse IPs properly.
  164. // https://github.com/whatwg/url/issues/749
  165. let addr = Url::parse(&url.as_str().replace(url.scheme(), "http")).unwrap();
  166. // Filter private IP ranges
  167. match addr.host().unwrap() {
  168. url::Host::Ipv4(ip) => {
  169. if !ip.is_global() {
  170. return true
  171. }
  172. }
  173. url::Host::Ipv6(ip) => {
  174. if !ip.is_global() {
  175. return true
  176. }
  177. }
  178. url::Host::Domain(d) => {
  179. if LOCAL_HOST_STRS.contains(&d) {
  180. return true
  181. }
  182. }
  183. }
  184. false
  185. }
  186. /// Filter given addresses based on certain rulesets and validity.
  187. async fn filter_addresses(&self, addrs: &[Url]) -> Vec<Url> {
  188. debug!(target: "net::hosts::filter_addresses()", "Filtering addrs: {:?}", addrs);
  189. let mut ret = vec![];
  190. let localnet = self.settings.localnet;
  191. 'addr_loop: for addr_ in addrs {
  192. // Validate that the format is `scheme://host_str:port`
  193. if addr_.host_str().is_none() ||
  194. addr_.port().is_none() ||
  195. addr_.cannot_be_a_base() ||
  196. addr_.path_segments().is_some()
  197. {
  198. continue
  199. }
  200. if self.is_rejected(addr_).await {
  201. debug!(target: "net::hosts::filter_addresses()", "Peer {} is rejected", addr_);
  202. continue
  203. }
  204. let host_str = addr_.host_str().unwrap();
  205. if !localnet {
  206. // Our own external addresses should never enter the hosts set.
  207. for ext in &self.settings.external_addrs {
  208. if host_str == ext.host_str().unwrap() {
  209. continue 'addr_loop
  210. }
  211. }
  212. }
  213. // We do this hack in order to parse IPs properly.
  214. // https://github.com/whatwg/url/issues/749
  215. let addr = Url::parse(&addr_.as_str().replace(addr_.scheme(), "http")).unwrap();
  216. // Filter non-global ranges if we're not allowing localnet.
  217. // Should never be allowed in production, so we don't really care
  218. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  219. if !localnet && self.is_local_host(addr).await {
  220. continue
  221. }
  222. match addr_.scheme() {
  223. // Validate that the address is an actual onion.
  224. #[cfg(feature = "p2p-tor")]
  225. "tor" | "tor+tls" => {
  226. use std::str::FromStr;
  227. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  228. continue
  229. }
  230. debug!(target: "net::hosts::filter_addresses()", "[Tor] Valid: {}", host_str);
  231. }
  232. #[cfg(feature = "p2p-nym")]
  233. "nym" | "nym+tls" => continue, // <-- Temp skip
  234. #[cfg(feature = "p2p-tcp")]
  235. "tcp" | "tcp+tls" => {
  236. debug!(target: "net::hosts::filter_addresses()", "[TCP] Valid: {}", host_str);
  237. }
  238. _ => continue,
  239. }
  240. ret.push(addr_.clone());
  241. }
  242. ret
  243. }
  244. async fn filter_addresses2(&self, addrs: &[(Url, u64)]) -> Vec<(Url, u64)> {
  245. debug!(target: "net::hosts::filter_addresses()", "Filtering addrs: {:?}", addrs);
  246. let mut ret = vec![];
  247. let localnet = self.settings.localnet;
  248. 'addr_loop: for (addr_, last_seen) in addrs {
  249. // Validate that the format is `scheme://host_str:port`
  250. if addr_.host_str().is_none() ||
  251. addr_.port().is_none() ||
  252. addr_.cannot_be_a_base() ||
  253. addr_.path_segments().is_some()
  254. {
  255. continue
  256. }
  257. if self.is_rejected(addr_).await {
  258. debug!(target: "net::hosts::filter_addresses()", "Peer {} is rejected", addr_);
  259. continue
  260. }
  261. let host_str = addr_.host_str().unwrap();
  262. if !localnet {
  263. // Our own external addresses should never enter the hosts set.
  264. for ext in &self.settings.external_addrs {
  265. if host_str == ext.host_str().unwrap() {
  266. continue 'addr_loop
  267. }
  268. }
  269. }
  270. // We do this hack in order to parse IPs properly.
  271. // https://github.com/whatwg/url/issues/749
  272. let addr = Url::parse(&addr_.as_str().replace(addr_.scheme(), "http")).unwrap();
  273. // Filter non-global ranges if we're not allowing localnet.
  274. // Should never be allowed in production, so we don't really care
  275. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  276. if !localnet && self.is_local_host(addr).await {
  277. continue
  278. }
  279. match addr_.scheme() {
  280. // Validate that the address is an actual onion.
  281. #[cfg(feature = "p2p-tor")]
  282. "tor" | "tor+tls" => {
  283. use std::str::FromStr;
  284. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  285. continue
  286. }
  287. debug!(target: "net::hosts::filter_addresses()", "[Tor] Valid: {}", host_str);
  288. }
  289. #[cfg(feature = "p2p-nym")]
  290. "nym" | "nym+tls" => continue, // <-- Temp skip
  291. #[cfg(feature = "p2p-tcp")]
  292. "tcp" | "tcp+tls" => {
  293. debug!(target: "net::hosts::filter_addresses()", "[TCP] Valid: {}", host_str);
  294. }
  295. _ => continue,
  296. }
  297. ret.push((addr_.clone(), last_seen.clone()));
  298. }
  299. ret
  300. }
  301. // Probe random peers on the greylist. If a peer is responsive, update the last_seen field and
  302. // add it to the whitelist. If a node does not respond, remove it from the greylist.
  303. // Called periodically.
  304. pub async fn refresh_greylist(&self, p2p: P2pPtr, ex: Arc<Executor<'_>>) {
  305. let mut greylist = self.greylist.write().await;
  306. let mut whitelist = self.whitelist.write().await;
  307. // Randomly select an entry from the greylist.
  308. let position = rand::thread_rng().gen_range(0..greylist.len());
  309. let entry = &greylist[position];
  310. let url = &entry.0;
  311. // Probe node to see if it's active.
  312. let online: bool = self.probe_node(url, p2p.clone(), ex.clone()).await;
  313. if online {
  314. // Peer is responsive. Update last_seen and add it to the whitelist.
  315. let last_seen =
  316. SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
  317. // Remove oldest element if the whitelist reaches max size.
  318. if whitelist.len() == 1000 {
  319. // Last element in vector should have the oldest timestamp.
  320. // This should never crash as only returns None when whitelist len() == 0.
  321. let entry = whitelist.pop().unwrap();
  322. debug!(target: "net::hosts::refresh_greylist()", "Whitelist reached max size. Removed host {}", entry.0);
  323. }
  324. // Append to the whitelist.
  325. debug!(target: "net::hosts::refresh_greylist()", "Adding peer {} to whitelist", url);
  326. whitelist.push((url.clone(), last_seen));
  327. // Sort whitelist by last_seen.
  328. whitelist.sort_unstable_by_key(|entry| entry.1);
  329. // Remove whitelisted peer from the greylist.
  330. debug!(target: "net::hosts::refresh_greylist()", "Removing whitelisted peer {} from greylist", url);
  331. greylist.remove(position);
  332. } else {
  333. // Peer is not responsive. Remove it from the greylist.
  334. debug!(target: "net::hosts::refresh_greylist()", "Peer {} is not response. Removing from greylist", url);
  335. greylist.remove(position);
  336. }
  337. }
  338. async fn probe_node(&self, host: &Url, p2p: P2pPtr, ex: Arc<Executor<'_>>) -> bool {
  339. let p2p_ = p2p.clone();
  340. let ex_ = ex.clone();
  341. let session_out = p2p_.session_outbound();
  342. let session_weak = Arc::downgrade(&session_out);
  343. let connector = Connector::new(p2p_.settings(), session_weak);
  344. debug!(target: "net::hosts::probe_node()", "Connecting to {}", host);
  345. match connector.connect(host).await {
  346. Ok((_url, channel)) => {
  347. debug!(target: "net::hosts::probe_node()", "Connected successfully!");
  348. let proto_ver = ProtocolVersion::new(
  349. channel.clone(),
  350. p2p_.settings().clone(),
  351. p2p_.hosts().clone(),
  352. )
  353. .await;
  354. let handshake_task = session_out.perform_handshake_protocols(
  355. proto_ver,
  356. channel.clone(),
  357. ex_.clone(),
  358. );
  359. channel.clone().start(ex_.clone());
  360. match handshake_task.await {
  361. Ok(()) => {
  362. debug!(target: "net::hosts::probe_node()", "Handshake success! Stopping channel.");
  363. channel.stop().await;
  364. return true
  365. }
  366. Err(e) => {
  367. debug!(target: "net::hosts::probe_node()", "Handshake failure! {}", e);
  368. return false
  369. }
  370. }
  371. }
  372. Err(e) => {
  373. debug!(target: "net::hosts::probe_node()", "Failed to connect to {}, ({})", host, e);
  374. return false
  375. }
  376. }
  377. }
  378. pub async fn remove(&self, url: &Url) {
  379. debug!(target: "net::hosts::remove()", "Removing peer {}", url);
  380. self.addrs.write().await.remove(url);
  381. self.quarantine.write().await.remove(url);
  382. }
  383. /// Quarantine a peer.
  384. /// If they've been quarantined for more than a configured limit, forget them.
  385. pub async fn quarantine(&self, url: &Url) {
  386. debug!(target: "net::hosts::remove()", "Quarantining peer {}", url);
  387. // Remove from main hosts set
  388. self.addrs.write().await.remove(url);
  389. let mut q = self.quarantine.write().await;
  390. if let Some(retries) = q.get_mut(url) {
  391. *retries += 1;
  392. debug!(target: "net::hosts::quarantine()", "Peer {} quarantined {} times", url, retries);
  393. if *retries == self.settings.hosts_quarantine_limit {
  394. debug!(target: "net::hosts::quarantine()", "Banning peer {}", url);
  395. q.remove(url);
  396. self.mark_rejected(url).await;
  397. }
  398. } else {
  399. debug!(target: "net::hosts::remove()", "Added peer {} to quarantine", url);
  400. q.insert(url.clone(), 0);
  401. }
  402. }
  403. /// Check if a given peer (URL) is in the set of rejected hosts
  404. pub async fn is_rejected(&self, peer: &Url) -> bool {
  405. // Skip lookup for UNIX sockets and localhost connections
  406. // as they should never belong to the list of rejected URLs.
  407. let Some(hostname) = peer.host_str() else { return false };
  408. if self.is_local_host(peer.clone()).await {
  409. return false
  410. }
  411. self.rejected.read().await.contains(hostname)
  412. }
  413. /// Mark a peer as rejected by adding it to the set of rejected URLs.
  414. pub async fn mark_rejected(&self, peer: &Url) {
  415. // We ignore UNIX sockets here so we will just work
  416. // with stuff that has host_str().
  417. if let Some(hostname) = peer.host_str() {
  418. // Localhost connections should not be rejected
  419. // This however allows any Tor and Nym connections.
  420. if self.is_local_host(peer.clone()).await {
  421. return
  422. }
  423. self.rejected.write().await.insert(hostname.to_string());
  424. }
  425. }
  426. /// Unmark a rejected peer
  427. pub async fn unmark_rejected(&self, peer: &Url) {
  428. if let Some(hostname) = peer.host_str() {
  429. self.rejected.write().await.remove(hostname);
  430. }
  431. }
  432. /// Check if the host list is empty.
  433. pub async fn is_empty(&self) -> bool {
  434. self.addrs.read().await.is_empty()
  435. }
  436. // Check if the greylist is empty.
  437. pub async fn is_empty_greylist(&self) -> bool {
  438. self.greylist.read().await.is_empty()
  439. }
  440. // Check if the whitelist is empty.
  441. pub async fn is_empty_whitelist(&self) -> bool {
  442. self.whitelist.read().await.is_empty()
  443. }
  444. // Check if host is in the greylist
  445. pub async fn greylist_contains(&self, addr: &Url) -> bool {
  446. let greylist = self.greylist.read().await;
  447. if greylist.iter().any(|(u, _t)| u == addr) {
  448. return true
  449. }
  450. return false
  451. }
  452. // Check if host is in the whitelist
  453. pub async fn whitelist_contains(&self, addr: &Url) -> bool {
  454. let whitelist = self.whitelist.read().await;
  455. if whitelist.iter().any(|(u, _t)| u == addr) {
  456. return true
  457. }
  458. return false
  459. }
  460. // Get the index for a given addr on the whitelist.
  461. pub async fn get_whitelist_index_at_addr(&self, addr: &Url) -> usize {
  462. let whitelist = self.whitelist.read().await;
  463. for (i, (url, _time)) in whitelist.iter().enumerate() {
  464. if url == addr {
  465. return i
  466. }
  467. }
  468. // TODO: FIXME: This should never happen.
  469. return 0
  470. }
  471. /// Check if host is already in the set
  472. pub async fn contains(&self, addr: &Url) -> bool {
  473. self.addrs.read().await.contains(addr)
  474. }
  475. /// Return all known hosts
  476. pub async fn fetch_all(&self) -> Vec<Url> {
  477. self.addrs.read().await.iter().cloned().collect()
  478. }
  479. /// Get up to n random peers from the hosts set.
  480. pub async fn fetch_n_random(&self, n: u32) -> Vec<Url> {
  481. let n = n as usize;
  482. if n == 0 {
  483. return vec![]
  484. }
  485. let addrs = self.addrs.read().await;
  486. let urls = addrs.iter().choose_multiple(&mut OsRng, n.min(addrs.len()));
  487. urls.iter().map(|&url| url.clone()).collect()
  488. }
  489. /// Get up to n random peers that match the given transport schemes from the hosts set.
  490. pub async fn fetch_n_random_with_schemes(&self, schemes: &[String], n: u32) -> Vec<Url> {
  491. let n = n as usize;
  492. if n == 0 {
  493. return vec![]
  494. }
  495. // Retrieve all peers corresponding to that transport schemes
  496. let hosts = self.fetch_with_schemes(schemes, None).await;
  497. if hosts.is_empty() {
  498. return hosts
  499. }
  500. // Grab random ones
  501. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  502. urls.iter().map(|&url| url.clone()).collect()
  503. }
  504. pub async fn whitelist_fetch_n_random_with_schemes(
  505. &self,
  506. schemes: &[String],
  507. n: u32,
  508. ) -> Vec<(Url, u64)> {
  509. let n = n as usize;
  510. if n == 0 {
  511. return vec![]
  512. }
  513. // Retrieve all peers corresponding to that transport schemes
  514. let hosts = self.whitelist_fetch_with_schemes(schemes, None).await;
  515. if hosts.is_empty() {
  516. return hosts
  517. }
  518. // Grab random ones
  519. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  520. urls.iter().map(|&url| url.clone()).collect()
  521. }
  522. /// Get up to n random peers that don't match the given transport schemes from the hosts set.
  523. pub async fn fetch_n_random_excluding_schemes(&self, schemes: &[String], n: u32) -> Vec<Url> {
  524. let n = n as usize;
  525. if n == 0 {
  526. return vec![]
  527. }
  528. // Retrieve all peers not corresponding to that transport schemes
  529. let hosts = self.fetch_exluding_schemes(schemes, None).await;
  530. if hosts.is_empty() {
  531. return hosts
  532. }
  533. // Grab random ones
  534. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  535. urls.iter().map(|&url| url.clone()).collect()
  536. }
  537. pub async fn whitelist_fetch_n_random_excluding_schemes(
  538. &self,
  539. schemes: &[String],
  540. n: u32,
  541. ) -> Vec<(Url, u64)> {
  542. let n = n as usize;
  543. if n == 0 {
  544. return vec![]
  545. }
  546. // Retrieve all peers not corresponding to that transport schemes
  547. let hosts = self.whitelist_fetch_excluding_schemes(schemes, None).await;
  548. if hosts.is_empty() {
  549. return hosts
  550. }
  551. // Grab random ones
  552. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  553. urls.iter().map(|&url| url.clone()).collect()
  554. }
  555. /// Get up to limit peers that match the given transport schemes from the hosts set.
  556. /// If limit was not provided, return all matching peers.
  557. pub async fn fetch_with_schemes(&self, schemes: &[String], limit: Option<usize>) -> Vec<Url> {
  558. let addrs = self.addrs.read().await;
  559. let mut limit = match limit {
  560. Some(l) => l.min(addrs.len()),
  561. None => addrs.len(),
  562. };
  563. let mut ret = vec![];
  564. if limit == 0 {
  565. return ret
  566. }
  567. for addr in addrs.iter() {
  568. if schemes.contains(&addr.scheme().to_string()) {
  569. ret.push(addr.clone());
  570. limit -= 1;
  571. if limit == 0 {
  572. return ret
  573. }
  574. }
  575. }
  576. // If we didn't find any, pick some from the quarantine zone
  577. if ret.is_empty() {
  578. for addr in self.quarantine.read().await.keys() {
  579. if schemes.contains(&addr.scheme().to_string()) {
  580. ret.push(addr.clone());
  581. limit -= 1;
  582. if limit == 0 {
  583. break
  584. }
  585. }
  586. }
  587. }
  588. ret
  589. }
  590. pub async fn whitelist_fetch_with_schemes(
  591. &self,
  592. schemes: &[String],
  593. limit: Option<usize>,
  594. ) -> Vec<(Url, u64)> {
  595. let whitelist = self.whitelist.read().await;
  596. let mut limit = match limit {
  597. Some(l) => l.min(whitelist.len()),
  598. None => whitelist.len(),
  599. };
  600. let mut ret = vec![];
  601. if limit == 0 {
  602. return ret
  603. }
  604. for (addr, last_seen) in whitelist.iter() {
  605. if schemes.contains(&addr.scheme().to_string()) {
  606. ret.push((addr.clone(), *last_seen));
  607. limit -= 1;
  608. if limit == 0 {
  609. return ret
  610. }
  611. }
  612. }
  613. // If we didn't find any, pick some from the greylist
  614. if ret.is_empty() {
  615. for (addr, last_seen) in self.greylist.read().await.iter() {
  616. if schemes.contains(&addr.scheme().to_string()) {
  617. ret.push((addr.clone(), *last_seen));
  618. limit -= 1;
  619. if limit == 0 {
  620. break
  621. }
  622. }
  623. }
  624. }
  625. ret
  626. }
  627. /// Get up to limit peers that don't match the given transport schemes from the hosts set.
  628. /// If limit was not provided, return all matching peers.
  629. pub async fn fetch_exluding_schemes(
  630. &self,
  631. schemes: &[String],
  632. limit: Option<usize>,
  633. ) -> Vec<Url> {
  634. let addrs = self.addrs.read().await;
  635. let mut limit = match limit {
  636. Some(l) => l.min(addrs.len()),
  637. None => addrs.len(),
  638. };
  639. let mut ret = vec![];
  640. if limit == 0 {
  641. return ret
  642. }
  643. for addr in addrs.iter() {
  644. if !schemes.contains(&addr.scheme().to_string()) {
  645. ret.push(addr.clone());
  646. limit -= 1;
  647. if limit == 0 {
  648. return ret
  649. }
  650. }
  651. }
  652. // If we didn't find any, pick some from the quarantine zone
  653. if ret.is_empty() {
  654. for addr in self.quarantine.read().await.keys() {
  655. if !schemes.contains(&addr.scheme().to_string()) {
  656. ret.push(addr.clone());
  657. limit -= 1;
  658. if limit == 0 {
  659. break
  660. }
  661. }
  662. }
  663. }
  664. ret
  665. }
  666. pub async fn whitelist_fetch_excluding_schemes(
  667. &self,
  668. schemes: &[String],
  669. limit: Option<usize>,
  670. ) -> Vec<(Url, u64)> {
  671. let addrs = self.whitelist.read().await;
  672. let mut limit = match limit {
  673. Some(l) => l.min(addrs.len()),
  674. None => addrs.len(),
  675. };
  676. let mut ret = vec![];
  677. if limit == 0 {
  678. return ret
  679. }
  680. for (addr, last_seen) in addrs.iter() {
  681. if !schemes.contains(&addr.scheme().to_string()) {
  682. ret.push((addr.clone(), *last_seen));
  683. limit -= 1;
  684. if limit == 0 {
  685. return ret
  686. }
  687. }
  688. }
  689. // If we didn't find any, pick some from the greylist
  690. if ret.is_empty() {
  691. for (addr, last_seen) in self.greylist.read().await.iter() {
  692. if !schemes.contains(&addr.scheme().to_string()) {
  693. ret.push((addr.clone(), *last_seen));
  694. limit -= 1;
  695. if limit == 0 {
  696. break
  697. }
  698. }
  699. }
  700. }
  701. ret
  702. }
  703. }
  704. #[cfg(test)]
  705. mod tests {
  706. use super::{super::settings::Settings, *};
  707. use std::time::SystemTime;
  708. #[test]
  709. fn test_store_localnet() {
  710. smol::block_on(async {
  711. let settings = Settings {
  712. localnet: true,
  713. external_addrs: vec![
  714. Url::parse("tcp://foo.bar:123").unwrap(),
  715. Url::parse("tcp://lol.cat:321").unwrap(),
  716. ],
  717. ..Default::default()
  718. };
  719. let hosts = Hosts::new(Arc::new(settings.clone()));
  720. hosts.store(&settings.external_addrs).await;
  721. for i in settings.external_addrs {
  722. assert!(hosts.contains(&i).await);
  723. }
  724. let local_hosts = vec![
  725. Url::parse("tcp://localhost:3921").unwrap(),
  726. Url::parse("tcp://127.0.0.1:23957").unwrap(),
  727. Url::parse("tcp://[::1]:21481").unwrap(),
  728. Url::parse("tcp://192.168.10.65:311").unwrap(),
  729. Url::parse("tcp://0.0.0.0:2312").unwrap(),
  730. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  731. ];
  732. hosts.store(&local_hosts).await;
  733. for i in local_hosts {
  734. assert!(hosts.contains(&i).await);
  735. }
  736. let remote_hosts = vec![
  737. Url::parse("tcp://dark.fi:80").unwrap(),
  738. Url::parse("tcp://top.kek:111").unwrap(),
  739. Url::parse("tcp://http.cat:401").unwrap(),
  740. ];
  741. hosts.store(&remote_hosts).await;
  742. for i in remote_hosts {
  743. assert!(hosts.contains(&i).await);
  744. }
  745. });
  746. }
  747. #[test]
  748. fn test_store() {
  749. smol::block_on(async {
  750. let settings = Settings {
  751. localnet: false,
  752. external_addrs: vec![
  753. Url::parse("tcp://foo.bar:123").unwrap(),
  754. Url::parse("tcp://lol.cat:321").unwrap(),
  755. ],
  756. ..Default::default()
  757. };
  758. let hosts = Hosts::new(Arc::new(settings.clone()));
  759. hosts.store(&settings.external_addrs).await;
  760. assert!(hosts.is_empty().await);
  761. let local_hosts = vec![
  762. Url::parse("tcp://localhost:3921").unwrap(),
  763. Url::parse("tor://[::1]:21481").unwrap(),
  764. Url::parse("tcp://192.168.10.65:311").unwrap(),
  765. Url::parse("tcp+tls://0.0.0.0:2312").unwrap(),
  766. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  767. ];
  768. hosts.store(&local_hosts).await;
  769. assert!(hosts.is_empty().await);
  770. let remote_hosts = vec![
  771. Url::parse("tcp://dark.fi:80").unwrap(),
  772. Url::parse("tcp://http.cat:401").unwrap(),
  773. Url::parse("tcp://foo.bar:111").unwrap(),
  774. ];
  775. hosts.store(&remote_hosts).await;
  776. assert!(hosts.contains(&remote_hosts[0]).await);
  777. assert!(hosts.contains(&remote_hosts[1]).await);
  778. assert!(!hosts.contains(&remote_hosts[2]).await);
  779. });
  780. }
  781. #[test]
  782. fn test_is_local_host() {
  783. smol::block_on(async {
  784. let settings = Settings {
  785. localnet: false,
  786. external_addrs: vec![
  787. Url::parse("tcp://foo.bar:123").unwrap(),
  788. Url::parse("tcp://lol.cat:321").unwrap(),
  789. ],
  790. ..Default::default()
  791. };
  792. let hosts = Hosts::new(Arc::new(settings.clone()));
  793. let local_hosts: Vec<Url> = vec![
  794. Url::parse("tcp://localhost").unwrap(),
  795. Url::parse("tcp://127.0.0.1").unwrap(),
  796. Url::parse("tcp+tls://[::1]").unwrap(),
  797. Url::parse("tcp://localhost.localdomain").unwrap(),
  798. Url::parse("tcp://192.168.10.65").unwrap(),
  799. ];
  800. for host in local_hosts {
  801. eprintln!("{}", host);
  802. assert!(hosts.is_local_host(host).await);
  803. }
  804. let remote_hosts: Vec<Url> = vec![
  805. Url::parse("https://dyne.org").unwrap(),
  806. Url::parse("tcp://77.168.10.65:2222").unwrap(),
  807. Url::parse("tcp://[2345:0425:2CA1:0000:0000:0567:5673:23b5]").unwrap(),
  808. Url::parse("http://eweiibe6tdjsdprb4px6rqrzzcsi22m4koia44kc5pcjr7nec2rlxyad.onion")
  809. .unwrap(),
  810. ];
  811. for host in remote_hosts {
  812. assert!(!(hosts.is_local_host(host).await))
  813. }
  814. });
  815. }
  816. #[test]
  817. fn test_greylist_store() {
  818. let last_seen =
  819. SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
  820. smol::block_on(async {
  821. let settings = Settings {
  822. localnet: false,
  823. external_addrs: vec![
  824. Url::parse("tcp://foo.bar:123").unwrap(),
  825. Url::parse("tcp://lol.cat:321").unwrap(),
  826. ],
  827. ..Default::default()
  828. };
  829. let hosts = Hosts::new(Arc::new(settings.clone()));
  830. let mut external_addrs = vec![];
  831. for addr in settings.external_addrs {
  832. external_addrs.push((addr, last_seen))
  833. }
  834. hosts.greylist_store(&external_addrs).await;
  835. assert!(hosts.is_empty_greylist().await);
  836. let local_hosts = vec![
  837. (Url::parse("tcp://localhost:3921").unwrap(), last_seen),
  838. (Url::parse("tor://[::1]:21481").unwrap(), last_seen),
  839. (Url::parse("tcp://192.168.10.65:311").unwrap(), last_seen),
  840. (Url::parse("tcp+tls://0.0.0.0:2312").unwrap(), last_seen),
  841. (Url::parse("tcp://255.255.255.255:2131").unwrap(), last_seen),
  842. ];
  843. hosts.greylist_store(&local_hosts).await;
  844. assert!(hosts.is_empty_greylist().await);
  845. let remote_hosts = vec![
  846. (Url::parse("tcp://dark.fi:80").unwrap(), last_seen),
  847. (Url::parse("tcp://http.cat:401").unwrap(), last_seen),
  848. (Url::parse("tcp://foo.bar:111").unwrap(), last_seen),
  849. ];
  850. hosts.greylist_store(&remote_hosts).await;
  851. assert!(hosts.greylist_contains(&remote_hosts[0].0).await);
  852. assert!(hosts.greylist_contains(&remote_hosts[1].0).await);
  853. assert!(!hosts.greylist_contains(&remote_hosts[2].0).await);
  854. });
  855. }
  856. #[test]
  857. fn test_whitelist_store() {
  858. smol::block_on(async {
  859. let settings = Settings {
  860. localnet: false,
  861. external_addrs: vec![
  862. Url::parse("tcp://foo.bar:123").unwrap(),
  863. Url::parse("tcp://lol.cat:321").unwrap(),
  864. ],
  865. ..Default::default()
  866. };
  867. let hosts = Hosts::new(Arc::new(settings.clone()));
  868. assert!(hosts.is_empty_whitelist().await);
  869. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  870. let last_seen =
  871. SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
  872. hosts.whitelist_store(&url, last_seen).await;
  873. assert!(!hosts.is_empty_whitelist().await);
  874. assert!(hosts.whitelist_contains(&url).await);
  875. });
  876. }
  877. }