hosts.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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, sync::Arc};
  19. use log::{debug, trace};
  20. use rand::{
  21. prelude::{IteratorRandom, SliceRandom},
  22. rngs::OsRng,
  23. };
  24. use smol::lock::RwLock;
  25. use url::Url;
  26. use super::{p2p::P2pPtr, 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. // An array containing all possible local host strings
  34. // TODO: This could perhaps be more exhaustive?
  35. pub const LOCAL_HOST_STRS: [&str; 2] = ["localhost", "localhost.localdomain"];
  36. /// Manages a store of network addresses
  37. pub struct Hosts {
  38. // Intermediary node list that is periodically probed and updated to whitelist.
  39. pub greylist: RwLock<Vec<(Url, u64)>>,
  40. // Recently seen nodes.
  41. pub whitelist: RwLock<Vec<(Url, u64)>>,
  42. /// Peers we reject from connecting
  43. rejected: RwLock<HashSet<String>>,
  44. /// Subscriber listening for store updates
  45. store_subscriber: SubscriberPtr<usize>,
  46. /// Pointer to configured P2P settings
  47. settings: SettingsPtr,
  48. }
  49. impl Hosts {
  50. /// Create a new hosts list>
  51. pub fn new(settings: SettingsPtr) -> HostsPtr {
  52. Arc::new(Self {
  53. whitelist: RwLock::new(Vec::new()),
  54. greylist: RwLock::new(Vec::new()),
  55. rejected: RwLock::new(HashSet::new()),
  56. store_subscriber: Subscriber::new(),
  57. settings,
  58. })
  59. }
  60. /// Loops through whitelist addresses to find an outbound address that we can
  61. /// connect to. Check whether the address is valid by making sure it isn't
  62. /// our own inbound address, then checks whether it is already connected
  63. /// (exists) or connecting (pending).
  64. /// Lastly adds matching address to the pending list.
  65. pub async fn whitelist_fetch_address_with_lock(
  66. &self,
  67. p2p: P2pPtr,
  68. transports: &[String],
  69. ) -> Option<(Url, u64)> {
  70. // Collect hosts
  71. let mut hosts = vec![];
  72. // If transport mixing is enabled, then for example we're allowed to
  73. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  74. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  75. let transport_mixing = self.settings.transport_mixing;
  76. macro_rules! mix_transport {
  77. ($a:expr, $b:expr) => {
  78. if transports.contains(&$a.to_string()) && transport_mixing {
  79. let mut a_to_b =
  80. self.whitelist_fetch_with_schemes(&[$b.to_string()], None).await;
  81. for (addr, last_seen) in a_to_b.iter_mut() {
  82. addr.set_scheme($a).unwrap();
  83. hosts.push((addr.clone(), last_seen.clone()));
  84. }
  85. }
  86. };
  87. }
  88. mix_transport!("tor", "tcp");
  89. mix_transport!("tor+tls", "tcp+tls");
  90. mix_transport!("nym", "tcp");
  91. mix_transport!("nym+tls", "tcp+tls");
  92. // And now the actual requested transports
  93. for (addr, last_seen) in self.whitelist_fetch_with_schemes(transports, None).await {
  94. hosts.push((addr, last_seen));
  95. }
  96. // Randomize hosts list. Do not try to connect in a deterministic order.
  97. // This is healthier for multiple slots to not compete for the same addrs.
  98. hosts.shuffle(&mut OsRng);
  99. // Try to find an unused host in the set.
  100. for (host, last_seen) in hosts.iter() {
  101. // Check if we already have this connection established
  102. if p2p.exists(host).await {
  103. trace!(
  104. target: "net::hosts::whitelist_fetch_address_with_lock()",
  105. "Host '{}' exists so skipping",
  106. host
  107. );
  108. continue
  109. }
  110. // Check if we already have this configured as a manual peer
  111. if self.settings.peers.contains(host) {
  112. trace!(
  113. target: "net::hosts::whitelist_fetch_address_with_lock()",
  114. "Host '{}' configured as manual peer so skipping",
  115. host
  116. );
  117. continue
  118. }
  119. // Obtain a lock on this address to prevent duplicate connection
  120. if !p2p.add_pending(host).await {
  121. trace!(
  122. target: "net::hosts::whitelist_fetch_address_with_lock()",
  123. "Host '{}' pending so skipping",
  124. host
  125. );
  126. continue
  127. }
  128. trace!(
  129. target: "net::hosts::whitelist_fetch_address_with_lock()",
  130. "Found valid host '{}",
  131. host
  132. );
  133. return Some((host.clone(), last_seen.clone()))
  134. }
  135. None
  136. }
  137. // Store the address in the whitelist if we don't have it.
  138. // Otherwise, update the last_seen field.
  139. // TODO: test the performance of this method. It might be costly.
  140. pub async fn whitelist_store_or_update(&self, addr: &Url, last_seen: u64) {
  141. debug!(target: "net::hosts::whitelist_store_or_update()", "hosts::whitelist_store_or_update() [START]");
  142. if !self.whitelist_contains(addr).await {
  143. self.whitelist_store(addr, last_seen).await;
  144. } else {
  145. let index = self.get_whitelist_index_at_addr(addr).await;
  146. self.whitelist_update_last_seen(addr, last_seen, index).await;
  147. }
  148. }
  149. // Update the last_seen field for a Url on the whitelist.
  150. pub async fn whitelist_update(&self, addr: &Url, last_seen: u64) {
  151. let index = self.get_whitelist_index_at_addr(addr).await;
  152. self.whitelist_update_last_seen(addr, last_seen, index).await;
  153. }
  154. // Append host to the greylist. Called on learning of a new peer.
  155. pub async fn greylist_store(&self, addrs: &[(Url, u64)]) {
  156. debug!(target: "net::hosts::greylist_store()", "hosts::greylist_store() [START]");
  157. let filtered_addrs = self.filter_addresses(addrs).await;
  158. let filtered_addrs_len = filtered_addrs.len();
  159. if !filtered_addrs.is_empty() {
  160. let mut greylist = self.greylist.write().await;
  161. // Remove oldest element if the greylist reaches max size.
  162. if greylist.len() == 5000 {
  163. let last_entry = greylist.pop().unwrap();
  164. debug!(target: "net::hosts::greylist_store()", "Greylist reached max size. Removed {:?}", last_entry);
  165. }
  166. for (addr, last_seen) in filtered_addrs {
  167. debug!(target: "net::hosts::greylist_store()", "Inserting {}", addr);
  168. greylist.push((addr.clone(), last_seen.clone()))
  169. }
  170. // Sort the list by last_seen.
  171. greylist.sort_unstable_by_key(|entry| entry.1);
  172. debug!(target: "net::hosts::greylist_store()", "Sorted greylist: {:?}", greylist)
  173. }
  174. self.store_subscriber.notify(filtered_addrs_len).await;
  175. debug!(target: "net::hosts::greylist_store()", "hosts::greylist_store() [END]");
  176. }
  177. // Append host to the whitelist. Called after a successful interaction with an online peer.
  178. pub async fn whitelist_store(&self, addr: &Url, last_seen: u64) {
  179. debug!(target: "net::hosts::whitelist_store()", "hosts::whitelist_store() [START]");
  180. let mut whitelist = self.whitelist.write().await;
  181. debug!(target: "net::hosts::whitelist_store()", "Inserting {}. Last seen {:?}", addr, last_seen);
  182. // Remove oldest element if the whitelist reaches max size.
  183. if whitelist.len() == 1000 {
  184. let last_entry = whitelist.pop().unwrap();
  185. debug!(target: "net::hosts::whitelist_store()", "Whitelist reached max size. Removed {:?}", last_entry);
  186. }
  187. whitelist.push((addr.clone(), last_seen));
  188. // Sort the list by last_seen.
  189. whitelist.sort_unstable_by_key(|entry| entry.1);
  190. debug!(target: "net::hosts::whitelist_store()", "Sorted whitelist: {:?}", whitelist);
  191. debug!(target: "net::hosts::whitelist_store()", "hosts::whitelist_store() [END]");
  192. }
  193. // Update the last_seen field of a peer on the whitelist.
  194. pub async fn whitelist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  195. debug!(target: "net::hosts::update_last_seen()", "hosts::update_last_seen() [START]");
  196. let mut whitelist = self.whitelist.write().await;
  197. whitelist[index] = (addr.clone(), last_seen);
  198. }
  199. pub async fn whitelist_downgrade(&self, addr: &Url) {
  200. // First lookup the entry using its addr.
  201. let mut entry = vec![];
  202. let whitelist = self.whitelist.read().await;
  203. for (url, time) in whitelist.iter() {
  204. if url == addr {
  205. entry.push((url.clone(), time.clone()));
  206. }
  207. }
  208. // TODO: This is for testing purposes.
  209. assert!(entry.len() == 1);
  210. // Remove this item from the whitelist.
  211. let mut whitelist = self.whitelist.write().await;
  212. // TODO: test!
  213. let index = whitelist.iter().position(|x| *x == entry[0]);
  214. // This should never fail since the entry exists.
  215. whitelist.remove(index.unwrap());
  216. // Add it to the greylist.
  217. let addr = entry[0].0.clone();
  218. let last_seen = entry[0].1.clone();
  219. self.greylist_store(&[(addr, last_seen)]).await;
  220. }
  221. pub async fn subscribe_store(&self) -> Result<Subscription<usize>> {
  222. let sub = self.store_subscriber.clone().subscribe().await;
  223. Ok(sub)
  224. }
  225. // Verify whether a URL is local.
  226. // NOTE: This function is stateless and not specific to
  227. // `Hosts`. For this reason, it might make more sense
  228. // to move this function to a more appropriate location
  229. // in the codebase.
  230. pub async fn is_local_host(&self, url: Url) -> bool {
  231. // Reject Urls without host strings.
  232. if url.host_str().is_none() {
  233. return false
  234. }
  235. // We do this hack in order to parse IPs properly.
  236. // https://github.com/whatwg/url/issues/749
  237. let addr = Url::parse(&url.as_str().replace(url.scheme(), "http")).unwrap();
  238. // Filter private IP ranges
  239. match addr.host().unwrap() {
  240. url::Host::Ipv4(ip) => {
  241. if !ip.is_global() {
  242. return true
  243. }
  244. }
  245. url::Host::Ipv6(ip) => {
  246. if !ip.is_global() {
  247. return true
  248. }
  249. }
  250. url::Host::Domain(d) => {
  251. if LOCAL_HOST_STRS.contains(&d) {
  252. return true
  253. }
  254. }
  255. }
  256. false
  257. }
  258. /// Filter given addresses based on certain rulesets and validity.
  259. async fn filter_addresses(&self, addrs: &[(Url, u64)]) -> Vec<(Url, u64)> {
  260. debug!(target: "net::hosts::filter_addresses()", "Filtering addrs: {:?}", addrs);
  261. let mut ret = vec![];
  262. let localnet = self.settings.localnet;
  263. 'addr_loop: for (addr_, last_seen) in addrs {
  264. // Validate that the format is `scheme://host_str:port`
  265. if addr_.host_str().is_none() ||
  266. addr_.port().is_none() ||
  267. addr_.cannot_be_a_base() ||
  268. addr_.path_segments().is_some()
  269. {
  270. continue
  271. }
  272. if self.is_rejected(addr_).await {
  273. debug!(target: "net::hosts::filter_addresses()", "Peer {} is rejected", addr_);
  274. continue
  275. }
  276. let host_str = addr_.host_str().unwrap();
  277. if !localnet {
  278. // Our own external addresses should never enter the hosts set.
  279. for ext in &self.settings.external_addrs {
  280. if host_str == ext.host_str().unwrap() {
  281. continue 'addr_loop
  282. }
  283. }
  284. }
  285. // We do this hack in order to parse IPs properly.
  286. // https://github.com/whatwg/url/issues/749
  287. let addr = Url::parse(&addr_.as_str().replace(addr_.scheme(), "http")).unwrap();
  288. // Filter non-global ranges if we're not allowing localnet.
  289. // Should never be allowed in production, so we don't really care
  290. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  291. if !localnet && self.is_local_host(addr).await {
  292. continue
  293. }
  294. match addr_.scheme() {
  295. // Validate that the address is an actual onion.
  296. #[cfg(feature = "p2p-tor")]
  297. "tor" | "tor+tls" => {
  298. use std::str::FromStr;
  299. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  300. continue
  301. }
  302. debug!(target: "net::hosts::filter_addresses()", "[Tor] Valid: {}", host_str);
  303. }
  304. #[cfg(feature = "p2p-nym")]
  305. "nym" | "nym+tls" => continue, // <-- Temp skip
  306. #[cfg(feature = "p2p-tcp")]
  307. "tcp" | "tcp+tls" => {
  308. debug!(target: "net::hosts::filter_addresses()", "[TCP] Valid: {}", host_str);
  309. }
  310. _ => continue,
  311. }
  312. ret.push((addr_.clone(), last_seen.clone()));
  313. }
  314. ret
  315. }
  316. /// Check if a given peer (URL) is in the set of rejected hosts
  317. pub async fn is_rejected(&self, peer: &Url) -> bool {
  318. // Skip lookup for UNIX sockets and localhost connections
  319. // as they should never belong to the list of rejected URLs.
  320. let Some(hostname) = peer.host_str() else { return false };
  321. if self.is_local_host(peer.clone()).await {
  322. return false
  323. }
  324. self.rejected.read().await.contains(hostname)
  325. }
  326. /// Mark a peer as rejected by adding it to the set of rejected URLs.
  327. pub async fn mark_rejected(&self, peer: &Url) {
  328. // We ignore UNIX sockets here so we will just work
  329. // with stuff that has host_str().
  330. if let Some(hostname) = peer.host_str() {
  331. // Localhost connections should not be rejected
  332. // This however allows any Tor and Nym connections.
  333. if self.is_local_host(peer.clone()).await {
  334. return
  335. }
  336. self.rejected.write().await.insert(hostname.to_string());
  337. }
  338. }
  339. /// Unmark a rejected peer
  340. pub async fn unmark_rejected(&self, peer: &Url) {
  341. if let Some(hostname) = peer.host_str() {
  342. self.rejected.write().await.remove(hostname);
  343. }
  344. }
  345. /// Check if the greylist is empty.
  346. pub async fn is_empty_greylist(&self) -> bool {
  347. self.greylist.read().await.is_empty()
  348. }
  349. /// Check if the whitelist is empty.
  350. pub async fn is_empty_whitelist(&self) -> bool {
  351. self.whitelist.read().await.is_empty()
  352. }
  353. /// Check if host is in the greylist
  354. pub async fn greylist_contains(&self, addr: &Url) -> bool {
  355. let greylist = self.greylist.read().await;
  356. if greylist.iter().any(|(u, _t)| u == addr) {
  357. return true
  358. }
  359. return false
  360. }
  361. /// Check if host is in the whitelist
  362. pub async fn whitelist_contains(&self, addr: &Url) -> bool {
  363. let whitelist = self.whitelist.read().await;
  364. if whitelist.iter().any(|(u, _t)| u == addr) {
  365. return true
  366. }
  367. return false
  368. }
  369. /// Get the index for a given addr on the whitelist.
  370. pub async fn get_whitelist_index_at_addr(&self, addr: &Url) -> usize {
  371. let whitelist = self.whitelist.read().await;
  372. for (i, (url, _time)) in whitelist.iter().enumerate() {
  373. if url == addr {
  374. return i
  375. }
  376. }
  377. // TODO: FIXME: This should never happen.
  378. return 0
  379. }
  380. /// Return all known whitelisted hosts
  381. pub async fn whitelist_fetch_all(&self) -> Vec<(Url, u64)> {
  382. self.whitelist.read().await.iter().cloned().collect()
  383. }
  384. /// Get up to n random peers from the whitelist.
  385. pub async fn fetch_n_random(&self, n: u32) -> Vec<(Url, u64)> {
  386. let n = n as usize;
  387. if n == 0 {
  388. return vec![]
  389. }
  390. let addrs = self.whitelist.read().await;
  391. let urls = addrs.iter().choose_multiple(&mut OsRng, n.min(addrs.len()));
  392. urls.iter().map(|&url| url.clone()).collect()
  393. }
  394. /// Get up to n random whitelisted peers that match the given transport schemes from the hosts set.
  395. pub async fn whitelist_fetch_n_random_with_schemes(
  396. &self,
  397. schemes: &[String],
  398. n: u32,
  399. ) -> Vec<(Url, u64)> {
  400. let n = n as usize;
  401. if n == 0 {
  402. return vec![]
  403. }
  404. // Retrieve all peers corresponding to that transport schemes
  405. let hosts = self.whitelist_fetch_with_schemes(schemes, None).await;
  406. if hosts.is_empty() {
  407. return hosts
  408. }
  409. // Grab random ones
  410. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  411. urls.iter().map(|&url| url.clone()).collect()
  412. }
  413. /// Get up to n random whitelisted peers that don't match the given transport schemes from the hosts set.
  414. pub async fn whitelist_fetch_n_random_excluding_schemes(
  415. &self,
  416. schemes: &[String],
  417. n: u32,
  418. ) -> Vec<(Url, u64)> {
  419. let n = n as usize;
  420. if n == 0 {
  421. return vec![]
  422. }
  423. // Retrieve all peers not corresponding to that transport schemes
  424. let hosts = self.whitelist_fetch_excluding_schemes(schemes, None).await;
  425. if hosts.is_empty() {
  426. return hosts
  427. }
  428. // Grab random ones
  429. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  430. urls.iter().map(|&url| url.clone()).collect()
  431. }
  432. /// Get up to limit peers that match the given transport schemes from the whitelist.
  433. /// If limit was not provided, return all matching peers.
  434. pub async fn whitelist_fetch_with_schemes(
  435. &self,
  436. schemes: &[String],
  437. limit: Option<usize>,
  438. ) -> Vec<(Url, u64)> {
  439. let whitelist = self.whitelist.read().await;
  440. let mut limit = match limit {
  441. Some(l) => l.min(whitelist.len()),
  442. None => whitelist.len(),
  443. };
  444. let mut ret = vec![];
  445. if limit == 0 {
  446. return ret
  447. }
  448. for (addr, last_seen) in whitelist.iter() {
  449. if schemes.contains(&addr.scheme().to_string()) {
  450. ret.push((addr.clone(), *last_seen));
  451. limit -= 1;
  452. if limit == 0 {
  453. return ret
  454. }
  455. }
  456. }
  457. // If we didn't find any, pick some from the greylist
  458. if ret.is_empty() {
  459. for (addr, last_seen) in self.greylist.read().await.iter() {
  460. if schemes.contains(&addr.scheme().to_string()) {
  461. ret.push((addr.clone(), *last_seen));
  462. limit -= 1;
  463. if limit == 0 {
  464. break
  465. }
  466. }
  467. }
  468. }
  469. ret
  470. }
  471. /// Get up to limit peers that don't match the given transport schemes from the whitelist.
  472. /// If limit was not provided, return all matching peers.
  473. pub async fn whitelist_fetch_excluding_schemes(
  474. &self,
  475. schemes: &[String],
  476. limit: Option<usize>,
  477. ) -> Vec<(Url, u64)> {
  478. let addrs = self.whitelist.read().await;
  479. let mut limit = match limit {
  480. Some(l) => l.min(addrs.len()),
  481. None => addrs.len(),
  482. };
  483. let mut ret = vec![];
  484. if limit == 0 {
  485. return ret
  486. }
  487. for (addr, last_seen) in addrs.iter() {
  488. if !schemes.contains(&addr.scheme().to_string()) {
  489. ret.push((addr.clone(), *last_seen));
  490. limit -= 1;
  491. if limit == 0 {
  492. return ret
  493. }
  494. }
  495. }
  496. // If we didn't find any, pick some from the greylist
  497. if ret.is_empty() {
  498. for (addr, last_seen) in self.greylist.read().await.iter() {
  499. if !schemes.contains(&addr.scheme().to_string()) {
  500. ret.push((addr.clone(), *last_seen));
  501. limit -= 1;
  502. if limit == 0 {
  503. break
  504. }
  505. }
  506. }
  507. }
  508. ret
  509. }
  510. }
  511. #[cfg(test)]
  512. mod tests {
  513. use super::{super::settings::Settings, *};
  514. use std::time::UNIX_EPOCH;
  515. #[test]
  516. fn test_is_local_host() {
  517. smol::block_on(async {
  518. let settings = Settings {
  519. localnet: false,
  520. external_addrs: vec![
  521. Url::parse("tcp://foo.bar:123").unwrap(),
  522. Url::parse("tcp://lol.cat:321").unwrap(),
  523. ],
  524. ..Default::default()
  525. };
  526. let hosts = Hosts::new(Arc::new(settings.clone()));
  527. let local_hosts: Vec<Url> = vec![
  528. Url::parse("tcp://localhost").unwrap(),
  529. Url::parse("tcp://127.0.0.1").unwrap(),
  530. Url::parse("tcp+tls://[::1]").unwrap(),
  531. Url::parse("tcp://localhost.localdomain").unwrap(),
  532. Url::parse("tcp://192.168.10.65").unwrap(),
  533. ];
  534. for host in local_hosts {
  535. eprintln!("{}", host);
  536. assert!(hosts.is_local_host(host).await);
  537. }
  538. let remote_hosts: Vec<Url> = vec![
  539. Url::parse("https://dyne.org").unwrap(),
  540. Url::parse("tcp://77.168.10.65:2222").unwrap(),
  541. Url::parse("tcp://[2345:0425:2CA1:0000:0000:0567:5673:23b5]").unwrap(),
  542. Url::parse("http://eweiibe6tdjsdprb4px6rqrzzcsi22m4koia44kc5pcjr7nec2rlxyad.onion")
  543. .unwrap(),
  544. ];
  545. for host in remote_hosts {
  546. assert!(!(hosts.is_local_host(host).await))
  547. }
  548. });
  549. }
  550. #[test]
  551. fn test_greylist_store() {
  552. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  553. smol::block_on(async {
  554. let settings = Settings {
  555. localnet: false,
  556. external_addrs: vec![
  557. Url::parse("tcp://foo.bar:123").unwrap(),
  558. Url::parse("tcp://lol.cat:321").unwrap(),
  559. ],
  560. ..Default::default()
  561. };
  562. let hosts = Hosts::new(Arc::new(settings.clone()));
  563. let mut external_addrs = vec![];
  564. for addr in settings.external_addrs {
  565. external_addrs.push((addr, last_seen))
  566. }
  567. hosts.greylist_store(&external_addrs).await;
  568. assert!(hosts.is_empty_greylist().await);
  569. let local_hosts = vec![
  570. (Url::parse("tcp://localhost:3921").unwrap(), last_seen),
  571. (Url::parse("tor://[::1]:21481").unwrap(), last_seen),
  572. (Url::parse("tcp://192.168.10.65:311").unwrap(), last_seen),
  573. (Url::parse("tcp+tls://0.0.0.0:2312").unwrap(), last_seen),
  574. (Url::parse("tcp://255.255.255.255:2131").unwrap(), last_seen),
  575. ];
  576. hosts.greylist_store(&local_hosts).await;
  577. assert!(hosts.is_empty_greylist().await);
  578. let remote_hosts = vec![
  579. (Url::parse("tcp://dark.fi:80").unwrap(), last_seen),
  580. (Url::parse("tcp://http.cat:401").unwrap(), last_seen),
  581. (Url::parse("tcp://foo.bar:111").unwrap(), last_seen),
  582. ];
  583. hosts.greylist_store(&remote_hosts).await;
  584. assert!(hosts.greylist_contains(&remote_hosts[0].0).await);
  585. assert!(hosts.greylist_contains(&remote_hosts[1].0).await);
  586. assert!(!hosts.greylist_contains(&remote_hosts[2].0).await);
  587. });
  588. }
  589. #[test]
  590. fn test_whitelist_store() {
  591. smol::block_on(async {
  592. let settings = Settings {
  593. localnet: false,
  594. external_addrs: vec![
  595. Url::parse("tcp://foo.bar:123").unwrap(),
  596. Url::parse("tcp://lol.cat:321").unwrap(),
  597. ],
  598. ..Default::default()
  599. };
  600. let hosts = Hosts::new(Arc::new(settings.clone()));
  601. assert!(hosts.is_empty_whitelist().await);
  602. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  603. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  604. hosts.whitelist_store(&url, last_seen).await;
  605. assert!(!hosts.is_empty_whitelist().await);
  606. assert!(hosts.whitelist_contains(&url).await);
  607. });
  608. }
  609. }