store.rs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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. fs,
  21. fs::File,
  22. sync::Arc,
  23. time::UNIX_EPOCH,
  24. };
  25. use log::{debug, error, info, trace, warn};
  26. use rand::{prelude::IteratorRandom, rngs::OsRng, Rng};
  27. use smol::lock::RwLock;
  28. use url::Url;
  29. use super::super::{p2p::P2pPtr, settings::SettingsPtr};
  30. use crate::{
  31. system::{Subscriber, SubscriberPtr, Subscription},
  32. util::{
  33. file::{load_file, save_file},
  34. path::expand_path,
  35. },
  36. Result,
  37. };
  38. /// Atomic pointer to hosts object
  39. pub type HostsPtr = Arc<Hosts>;
  40. // An array containing all possible local host strings
  41. // TODO: This could perhaps be more exhaustive?
  42. pub const LOCAL_HOST_STRS: [&str; 2] = ["localhost", "localhost.localdomain"];
  43. const WHITELIST_MAX_LEN: usize = 5000;
  44. const GREYLIST_MAX_LEN: usize = 2000;
  45. /// Manages a store of network addresses
  46. // TODO: Test the performance overhead of using vectors for white/grey/anchor lists.
  47. // TODO: Check whether anchorlist has a max size in Monero.
  48. // TODO: we can probably clean up a lot of the repetitive code in this module.
  49. pub struct Hosts {
  50. /// Intermediary node list that is periodically probed and updated to whitelist.
  51. pub greylist: RwLock<Vec<(Url, u64)>>,
  52. /// Recently seen hosts. Shared with other nodes.
  53. pub whitelist: RwLock<Vec<(Url, u64)>>,
  54. /// Nodes to which we have already been able to establish a connection.
  55. pub anchorlist: RwLock<Vec<(Url, u64)>>,
  56. /// Peers we reject from connecting to
  57. rejected: RwLock<HashSet<String>>,
  58. /// Subscriber listening for store updates
  59. store_subscriber: SubscriberPtr<usize>,
  60. /// Pointer to configured P2P settings
  61. settings: SettingsPtr,
  62. }
  63. impl Hosts {
  64. /// Create a new hosts list>
  65. pub fn new(settings: SettingsPtr) -> HostsPtr {
  66. Arc::new(Self {
  67. greylist: RwLock::new(Vec::new()),
  68. whitelist: RwLock::new(Vec::new()),
  69. anchorlist: RwLock::new(Vec::new()),
  70. rejected: RwLock::new(HashSet::new()),
  71. store_subscriber: Subscriber::new(),
  72. settings,
  73. })
  74. }
  75. /// Loops through greylist addresses to find an outbound address that we can
  76. /// connect to. Check whether the address is valid by making sure it isn't
  77. /// our own inbound address, then checks whether it is already connected
  78. /// (exists) or connecting (pending).
  79. /// Lastly adds matching address to the pending list.
  80. pub async fn greylist_fetch_address(&self, transports: &[String]) -> Vec<(Url, u64)> {
  81. trace!(target: "store", "greylist_fetch_address() [START]");
  82. // Collect hosts
  83. let mut hosts = vec![];
  84. // If transport mixing is enabled, then for example we're allowed to
  85. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  86. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  87. let transport_mixing = self.settings.transport_mixing;
  88. macro_rules! mix_transport {
  89. ($a:expr, $b:expr) => {
  90. if transports.contains(&$a.to_string()) && transport_mixing {
  91. let mut a_to_b =
  92. self.greylist_fetch_with_schemes(&[$b.to_string()], None).await;
  93. for (addr, last_seen) in a_to_b.iter_mut() {
  94. addr.set_scheme($a).unwrap();
  95. hosts.push((addr.clone(), last_seen.clone()));
  96. }
  97. }
  98. };
  99. }
  100. mix_transport!("tor", "tcp");
  101. mix_transport!("tor+tls", "tcp+tls");
  102. mix_transport!("nym", "tcp");
  103. mix_transport!("nym+tls", "tcp+tls");
  104. // And now the actual requested transports
  105. for (addr, last_seen) in self.greylist_fetch_with_schemes(transports, None).await {
  106. hosts.push((addr, last_seen));
  107. }
  108. hosts
  109. }
  110. /// Loops through whitelist addresses to find an outbound address that we can
  111. /// connect to. Check whether the address is valid by making sure it isn't
  112. /// our own inbound address, then checks whether it is already connected
  113. /// (exists) or connecting (pending).
  114. /// Lastly adds matching address to the pending list.
  115. pub async fn whitelist_fetch_address(&self, transports: &[String]) -> Vec<(Url, u64)> {
  116. trace!(target: "store", "whitelist_fetch_address() [START]");
  117. // Collect hosts
  118. let mut hosts = vec![];
  119. // If transport mixing is enabled, then for example we're allowed to
  120. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  121. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  122. let transport_mixing = self.settings.transport_mixing;
  123. macro_rules! mix_transport {
  124. ($a:expr, $b:expr) => {
  125. if transports.contains(&$a.to_string()) && transport_mixing {
  126. let mut a_to_b =
  127. self.whitelist_fetch_with_schemes(&[$b.to_string()], None).await;
  128. for (addr, last_seen) in a_to_b.iter_mut() {
  129. addr.set_scheme($a).unwrap();
  130. hosts.push((addr.clone(), last_seen.clone()));
  131. }
  132. }
  133. };
  134. }
  135. mix_transport!("tor", "tcp");
  136. mix_transport!("tor+tls", "tcp+tls");
  137. mix_transport!("nym", "tcp");
  138. mix_transport!("nym+tls", "tcp+tls");
  139. // And now the actual requested transports
  140. for (addr, last_seen) in self.whitelist_fetch_with_schemes(transports, None).await {
  141. hosts.push((addr, last_seen));
  142. }
  143. trace!(target: "store::whitelist_fetch_address()",
  144. "Grabbed hosts, length: {}", hosts.len());
  145. hosts
  146. }
  147. /// Loops through anchorlist addresses to find an outbound address that we can
  148. /// connect to. Check whether the address is valid by making sure it isn't
  149. /// our own inbound address, then checks whether it is already connected
  150. /// (exists) or connecting (pending).
  151. /// Lastly adds matching address to the pending list.
  152. pub async fn anchorlist_fetch_address(&self, transports: &[String]) -> Vec<(Url, u64)> {
  153. trace!(target: "store", "anchorlist_fetch_address() [START]");
  154. // Collect hosts
  155. let mut hosts = vec![];
  156. // If transport mixing is enabled, then for example we're allowed to
  157. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  158. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  159. let transport_mixing = self.settings.transport_mixing;
  160. macro_rules! mix_transport {
  161. ($a:expr, $b:expr) => {
  162. if transports.contains(&$a.to_string()) && transport_mixing {
  163. let mut a_to_b =
  164. self.anchorlist_fetch_with_schemes(&[$b.to_string()], None).await;
  165. for (addr, last_seen) in a_to_b.iter_mut() {
  166. addr.set_scheme($a).unwrap();
  167. hosts.push((addr.clone(), last_seen.clone()));
  168. }
  169. }
  170. };
  171. }
  172. mix_transport!("tor", "tcp");
  173. mix_transport!("tor+tls", "tcp+tls");
  174. mix_transport!("nym", "tcp");
  175. mix_transport!("nym+tls", "tcp+tls");
  176. // And now the actual requested transports
  177. for (addr, last_seen) in self.anchorlist_fetch_with_schemes(transports, None).await {
  178. hosts.push((addr, last_seen));
  179. }
  180. trace!(target: "store::anchorlist_fetch_address()",
  181. "Grabbed hosts, length: {}", hosts.len());
  182. hosts
  183. }
  184. pub async fn check_address_with_lock(
  185. &self,
  186. p2p: P2pPtr,
  187. hosts: Vec<(Url, u64)>,
  188. ) -> Option<(Url, u64)> {
  189. // Try to find an unused host in the set.
  190. for (host, last_seen) in hosts {
  191. debug!(target: "store::anchorlist_fetch_address()",
  192. "Starting checks");
  193. // Check if we already have this connection established
  194. if p2p.exists(&host).await {
  195. debug!(
  196. target: "store::anchorlist_fetch_address()",
  197. "Host '{}' exists so skipping",
  198. host
  199. );
  200. continue
  201. }
  202. // Check if we already have this configured as a manual peer
  203. if self.settings.peers.contains(&host) {
  204. debug!(
  205. target: "store::anchorlist_fetch_address()",
  206. "Host '{}' configured as manual peer so skipping",
  207. host
  208. );
  209. continue
  210. }
  211. // Obtain a lock on this address to prevent duplicate connection
  212. if !p2p.add_pending(&host).await {
  213. debug!(
  214. target: "store::anchorlist_fetch_address()",
  215. "Host '{}' pending so skipping",
  216. host
  217. );
  218. continue
  219. }
  220. debug!(
  221. target: "store::anchorlist_fetch_address()",
  222. "Found valid host '{}",
  223. host
  224. );
  225. return Some((host.clone(), last_seen))
  226. }
  227. None
  228. }
  229. /// Upgrade a connection to the anchorlist. Called after a connection has been successfully
  230. /// established in Outbound and Manual sessions.
  231. pub async fn upgrade_host(&self, addr: &Url) {
  232. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  233. self.anchorlist_store_or_update(&[(addr.clone(), last_seen)]).await;
  234. }
  235. /// Downgrade a connection. If it's on the anchorlist or the whitelist, remove it and add it
  236. /// to the greylist. Called when we cannot establish a connection to a host or when a
  237. /// pre-existing connection disconnects.
  238. pub async fn downgrade_host(&self, addr: &Url) {
  239. // Remove channel from anchorlist and add it to greylist
  240. if self.anchorlist_contains(addr).await {
  241. let (url, last_seen) = self
  242. .get_anchorlist_entry_at_addr(addr)
  243. .await
  244. .expect("Expected anchorlist entry to exist");
  245. self.greylist_store_or_update(&[(url, last_seen)]).await;
  246. let index = self
  247. .get_anchorlist_index_at_addr(addr.clone())
  248. .await
  249. .expect("Expected anchorlist index to exist");
  250. self.anchorlist_remove(addr, index).await;
  251. }
  252. // Remove channel from whitelist and add to greylist
  253. if self.whitelist_contains(addr).await {
  254. let (url, last_seen) = self
  255. .get_whitelist_entry_at_addr(addr)
  256. .await
  257. .expect("Expected whitelist entry to exist");
  258. self.greylist_store_or_update(&[(url, last_seen)]).await;
  259. let index = self
  260. .get_whitelist_index_at_addr(addr.clone())
  261. .await
  262. .expect("Expected whitelist index to exist");
  263. self.whitelist_remove(addr, index).await;
  264. }
  265. }
  266. /// Stores an address on the greylist or updates its last_seen field if we already
  267. /// have the address.
  268. pub async fn greylist_store_or_update(&self, addrs: &[(Url, u64)]) {
  269. trace!(target: "store::greylist_store_or_update()", "[START]");
  270. // Filter addresses before writing to the greylist.
  271. let filtered_addrs = self.filter_addresses(addrs).await;
  272. let filtered_addrs_len = filtered_addrs.len();
  273. for (addr, last_seen) in filtered_addrs {
  274. if !self.greylist_contains(&addr).await {
  275. debug!(target: "store::greylist_store_or_update()",
  276. "We do not have this entry in the hostlist. Adding to store...");
  277. self.greylist_store(addr.clone(), last_seen).await;
  278. } else {
  279. debug!(target: "store::greylist_store_or_update()",
  280. "We have this entry in the greylist. Updating last seen...");
  281. let index = self
  282. .get_greylist_index_at_addr(addr.clone())
  283. .await
  284. .expect("Expected greylist entry to exist");
  285. self.greylist_update_last_seen(&addr, last_seen, index).await;
  286. self.store_subscriber.notify(filtered_addrs_len).await;
  287. }
  288. }
  289. }
  290. /// Stores an address on the whitelist or updates its last_seen field if we already
  291. /// have the address.
  292. pub async fn whitelist_store_or_update(&self, addrs: &[(Url, u64)]) {
  293. trace!(target: "store::whitelist_store_or_update()", "[START]");
  294. // No address filtering for whitelist (whitelist is created from greylist)
  295. for (addr, last_seen) in addrs {
  296. if !self.whitelist_contains(addr).await {
  297. debug!(target: "store::whitelist_store_or_update()",
  298. "We do not have this entry in the whitelist. Adding to store...");
  299. self.whitelist_store(addr.clone(), *last_seen).await;
  300. } else {
  301. debug!(target: "store::whitelist_store_or_update()",
  302. "We have this entry in the whitelist. Updating last seen...");
  303. let index = self
  304. .get_whitelist_index_at_addr(addr.clone())
  305. .await
  306. .expect("Expected whitelist entry to exist");
  307. self.whitelist_update_last_seen(addr, *last_seen, index).await;
  308. }
  309. }
  310. }
  311. /// Stores an address on the anchorlist or updates its last_seen field if we already
  312. /// have the address.
  313. pub async fn anchorlist_store_or_update(&self, addrs: &[(Url, u64)]) {
  314. trace!(target: "store::anchor_store_or_update()", "[START]");
  315. // No address filtering for anchorlist (contains addresses we have already connected to)
  316. for (addr, last_seen) in addrs {
  317. if !self.anchorlist_contains(addr).await {
  318. debug!(target: "store::anchorlist_store_or_update()",
  319. "We do not have this entry in the whitelist. Adding to store...");
  320. self.anchorlist_store(addr.clone(), *last_seen).await;
  321. } else {
  322. debug!(target: "store::anchorlist_store_or_update()",
  323. "We have this entry in the anchorlist. Updating last seen...");
  324. let index = self
  325. .get_anchorlist_index_at_addr(addr.clone())
  326. .await
  327. .expect("Expected anchorlist entry to exist");
  328. self.anchorlist_update_last_seen(addr, *last_seen, index).await;
  329. }
  330. }
  331. }
  332. /// Append host to the greylist. Called on learning of a new peer.
  333. pub async fn greylist_store(&self, addr: Url, last_seen: u64) {
  334. trace!(target: "store::greylist_store()", "hosts::greylist_store() [START]");
  335. let mut greylist = self.greylist.write().await;
  336. // Remove oldest element if the greylist reaches max size.
  337. if greylist.len() == GREYLIST_MAX_LEN {
  338. let last_entry = greylist.pop().unwrap();
  339. debug!(target: "store::greylist_store()", "Greylist reached max size. Removed {:?}", last_entry);
  340. }
  341. debug!(target: "store::greylist_store()", "Inserting {}", addr);
  342. greylist.push((addr, last_seen));
  343. // Sort the list by last_seen.
  344. greylist.sort_by_key(|entry| entry.1);
  345. trace!(target: "store::greylist_store()", "[END]");
  346. }
  347. /// Append host to the whitelist. Called after a successful interaction with an online peer.
  348. pub async fn whitelist_store(&self, addr: Url, last_seen: u64) {
  349. trace!(target: "store::whitelist_store()", "[START]");
  350. let mut whitelist = self.whitelist.write().await;
  351. // Remove oldest element if the whitelist reaches max size.
  352. if whitelist.len() == WHITELIST_MAX_LEN {
  353. let last_entry = whitelist.pop().unwrap();
  354. debug!(target: "store::whitelist_store()", "Whitelist reached max size. Removed {:?}", last_entry);
  355. }
  356. trace!(target: "store::whitelist_store()", "Inserting {}. Last seen {:?}", addr, last_seen);
  357. whitelist.push((addr, last_seen));
  358. // Sort the list by last_seen.
  359. whitelist.sort_by_key(|entry| entry.1);
  360. trace!(target: "store::whitelist_store()", "[END]");
  361. }
  362. /// Append host to the anchorlist. Called after we have successfully established a connection
  363. /// to a peer.
  364. pub async fn anchorlist_store(&self, addr: Url, last_seen: u64) {
  365. trace!(target: "store::anchorlist_store()", "[START]");
  366. let mut anchorlist = self.anchorlist.write().await;
  367. trace!(target: "store::anchorlist_store()", "Inserting {}", addr);
  368. anchorlist.push((addr, last_seen));
  369. // Sort the list by last_seen.
  370. anchorlist.sort_by_key(|entry| entry.1);
  371. trace!(target: "store::anchorlist_store()", "[END]");
  372. }
  373. /// Update the last_seen field of a peer on the greylist.
  374. pub async fn greylist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  375. trace!(target: "store::greylist_update_last_seen()", "[START]");
  376. let mut greylist = self.greylist.write().await;
  377. greylist[index] = (addr.clone(), last_seen);
  378. // Sort the list by last_seen.
  379. greylist.sort_by_key(|entry| entry.1);
  380. trace!(target: "store::greylist_update_last_seen()", "[END]");
  381. }
  382. /// Update the last_seen field of a peer on the whitelist.
  383. pub async fn whitelist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  384. trace!(target: "store::whitelist_update_last_seen()", "[START]");
  385. let mut whitelist = self.whitelist.write().await;
  386. whitelist[index] = (addr.clone(), last_seen);
  387. // Sort the list by last_seen.
  388. whitelist.sort_by_key(|entry| entry.1);
  389. trace!(target: "store::whitelist_update_last_seen()", "[END]");
  390. }
  391. /// Update the last_seen field of a peer on the anchorlist.
  392. pub async fn anchorlist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  393. trace!(target: "store::anchorlist_update_last_seen()", "[START]");
  394. let mut anchorlist = self.anchorlist.write().await;
  395. anchorlist[index] = (addr.clone(), last_seen);
  396. // Sort the list by last_seen.
  397. anchorlist.sort_by_key(|entry| entry.1);
  398. trace!(target: "store::anchorlist_update_last_seen()", "[END]");
  399. }
  400. /// Remove an entry from the greylist.
  401. pub async fn greylist_remove(&self, addr: &Url, index: usize) {
  402. debug!(target: "net::refinery::run()", "Removing peer {} from greylist", addr);
  403. self.greylist.write().await.remove(index);
  404. }
  405. /// Remove an entry from the whitelist.
  406. pub async fn whitelist_remove(&self, addr: &Url, index: usize) {
  407. debug!(target: "net::refinery::run()", "Removing peer {} from whitelist", addr);
  408. self.whitelist.write().await.remove(index);
  409. }
  410. /// Remove an entry from the anchorlist.
  411. pub async fn anchorlist_remove(&self, addr: &Url, index: usize) {
  412. debug!(target: "net::refinery::run()", "Removing peer {} from anchorlist", addr);
  413. self.anchorlist.write().await.remove(index);
  414. }
  415. pub async fn subscribe_store(&self) -> Result<Subscription<usize>> {
  416. let sub = self.store_subscriber.clone().subscribe().await;
  417. Ok(sub)
  418. }
  419. // Verify whether a URL is local.
  420. // NOTE: This function is stateless and not specific to
  421. // `Hosts`. For this reason, it might make more sense
  422. // to move this function to a more appropriate location
  423. // in the codebase.
  424. /// Check whether a URL is local host
  425. pub async fn is_local_host(&self, url: Url) -> bool {
  426. // Reject Urls without host strings.
  427. if url.host_str().is_none() {
  428. return false
  429. }
  430. // We do this hack in order to parse IPs properly.
  431. // https://github.com/whatwg/url/issues/749
  432. let addr = Url::parse(&url.as_str().replace(url.scheme(), "http")).unwrap();
  433. // Filter private IP ranges
  434. match addr.host().unwrap() {
  435. url::Host::Ipv4(ip) => {
  436. if !ip.is_global() {
  437. return true
  438. }
  439. }
  440. url::Host::Ipv6(ip) => {
  441. if !ip.is_global() {
  442. return true
  443. }
  444. }
  445. url::Host::Domain(d) => {
  446. if LOCAL_HOST_STRS.contains(&d) {
  447. return true
  448. }
  449. }
  450. }
  451. false
  452. }
  453. /// Filter given addresses based on certain rulesets and validity.
  454. async fn filter_addresses(&self, addrs: &[(Url, u64)]) -> Vec<(Url, u64)> {
  455. trace!(target: "store::filter_addresses()", "Filtering addrs: {:?}", addrs);
  456. let mut ret = vec![];
  457. let localnet = self.settings.localnet;
  458. 'addr_loop: for (addr_, last_seen) in addrs {
  459. // Validate that the format is `scheme://host_str:port`
  460. if addr_.host_str().is_none() ||
  461. addr_.port().is_none() ||
  462. addr_.cannot_be_a_base() ||
  463. addr_.path_segments().is_some()
  464. {
  465. continue
  466. }
  467. if self.is_rejected(addr_).await {
  468. debug!(target: "store::filter_addresses()", "Peer {} is rejected", addr_);
  469. continue
  470. }
  471. let host_str = addr_.host_str().unwrap();
  472. if !localnet {
  473. // Our own external addresses should never enter the hosts set.
  474. for ext in &self.settings.external_addrs {
  475. if host_str == ext.host_str().unwrap() {
  476. continue 'addr_loop
  477. }
  478. }
  479. }
  480. // On localnet, make sure ours ports don't enter the host set.
  481. for ext in &self.settings.external_addrs {
  482. if addr_.port() == ext.port() {
  483. continue 'addr_loop
  484. }
  485. }
  486. // We do this hack in order to parse IPs properly.
  487. // https://github.com/whatwg/url/issues/749
  488. let addr = Url::parse(&addr_.as_str().replace(addr_.scheme(), "http")).unwrap();
  489. // Filter non-global ranges if we're not allowing localnet.
  490. // Should never be allowed in production, so we don't really care
  491. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  492. if !localnet && self.is_local_host(addr).await {
  493. continue
  494. }
  495. match addr_.scheme() {
  496. // Validate that the address is an actual onion.
  497. #[cfg(feature = "p2p-tor")]
  498. "tor" | "tor+tls" => {
  499. use std::str::FromStr;
  500. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  501. continue
  502. }
  503. trace!(target: "store::filter_addresses()", "[Tor] Valid: {}", host_str);
  504. }
  505. #[cfg(feature = "p2p-nym")]
  506. "nym" | "nym+tls" => continue, // <-- Temp skip
  507. #[cfg(feature = "p2p-tcp")]
  508. "tcp" | "tcp+tls" => {
  509. trace!(target: "store::filter_addresses()", "[TCP] Valid: {}", host_str);
  510. }
  511. _ => continue,
  512. }
  513. ret.push((addr_.clone(), *last_seen));
  514. }
  515. ret
  516. }
  517. /// Check if a given peer (URL) is in the set of rejected hosts
  518. pub async fn is_rejected(&self, peer: &Url) -> bool {
  519. // Skip lookup for UNIX sockets and localhost connections
  520. // as they should never belong to the list of rejected URLs.
  521. let Some(hostname) = peer.host_str() else { return false };
  522. if self.is_local_host(peer.clone()).await {
  523. return false
  524. }
  525. self.rejected.read().await.contains(hostname)
  526. }
  527. /// Mark a peer as rejected by adding it to the set of rejected URLs.
  528. pub async fn mark_rejected(&self, peer: &Url) {
  529. // We ignore UNIX sockets here so we will just work
  530. // with stuff that has host_str().
  531. if let Some(hostname) = peer.host_str() {
  532. // Localhost connections should not be rejected
  533. // This however allows any Tor and Nym connections.
  534. if self.is_local_host(peer.clone()).await {
  535. return
  536. }
  537. self.rejected.write().await.insert(hostname.to_string());
  538. }
  539. }
  540. /// Unmark a rejected peer
  541. pub async fn unmark_rejected(&self, peer: &Url) {
  542. if let Some(hostname) = peer.host_str() {
  543. self.rejected.write().await.remove(hostname);
  544. }
  545. }
  546. /// Check if the greylist is empty.
  547. pub async fn is_empty_greylist(&self) -> bool {
  548. self.greylist.read().await.is_empty()
  549. }
  550. /// Check if the whitelist is empty.
  551. pub async fn is_empty_whitelist(&self) -> bool {
  552. self.whitelist.read().await.is_empty()
  553. }
  554. /// Check if the anchorlist is empty.
  555. pub async fn is_empty_anchorlist(&self) -> bool {
  556. self.anchorlist.read().await.is_empty()
  557. }
  558. /// Check if the hostlist is empty.
  559. pub async fn is_empty_hostlist(&self) -> bool {
  560. self.is_empty_greylist().await &&
  561. self.is_empty_whitelist().await &&
  562. self.is_empty_anchorlist().await
  563. }
  564. /// Check if host is in the greylist
  565. pub async fn greylist_contains(&self, addr: &Url) -> bool {
  566. self.greylist.read().await.iter().any(|(u, _t)| u == addr)
  567. }
  568. /// Check if host is in the whitelist
  569. pub async fn whitelist_contains(&self, addr: &Url) -> bool {
  570. self.whitelist.read().await.iter().any(|(u, _t)| u == addr)
  571. }
  572. /// Check if host is in the anchorlist
  573. pub async fn anchorlist_contains(&self, addr: &Url) -> bool {
  574. self.anchorlist.read().await.iter().any(|(u, _t)| u == addr)
  575. }
  576. /// Get the index for a given addr on the greylist.
  577. pub async fn get_greylist_index_at_addr(&self, addr: Url) -> Option<usize> {
  578. self.greylist.read().await.iter().position(|a| a.0 == addr)
  579. }
  580. /// Get the index for a given addr on the whitelist.
  581. pub async fn get_whitelist_index_at_addr(&self, addr: Url) -> Option<usize> {
  582. self.whitelist.read().await.iter().position(|a| a.0 == addr)
  583. }
  584. /// Get the index for a given addr on the anchorlist.
  585. pub async fn get_anchorlist_index_at_addr(&self, addr: Url) -> Option<usize> {
  586. self.anchorlist.read().await.iter().position(|a| a.0 == addr)
  587. }
  588. /// Get the entry for a given addr on the whitelist.
  589. pub async fn get_whitelist_entry_at_addr(&self, addr: &Url) -> Option<(Url, u64)> {
  590. self.whitelist
  591. .read()
  592. .await
  593. .iter()
  594. .find(|(url, _)| url == addr)
  595. .map(|(url, time)| (url.clone(), *time))
  596. }
  597. /// Get the entry for a given addr on the anchorlist.
  598. pub async fn get_anchorlist_entry_at_addr(&self, addr: &Url) -> Option<(Url, u64)> {
  599. self.anchorlist
  600. .read()
  601. .await
  602. .iter()
  603. .find(|(url, _)| url == addr)
  604. .map(|(url, time)| (url.clone(), *time))
  605. }
  606. /// Return all known whitelisted hosts
  607. pub async fn whitelist_fetch_all(&self) -> Vec<(Url, u64)> {
  608. self.whitelist.read().await.iter().cloned().collect()
  609. }
  610. /// Return all greylist and anchorlist hosts. Called on stop().
  611. /// Note: we do not return whitelist entries here since whitelist entries must go via the
  612. /// greylist refinery in the lifetime of the p2p network.
  613. pub async fn hostlist_fetch_safe(&self) -> HashMap<String, Vec<(Url, u64)>> {
  614. let mut hostlist = HashMap::new();
  615. hostlist.insert(
  616. "anchorlist".to_string(),
  617. self.anchorlist.read().await.iter().cloned().collect(),
  618. );
  619. hostlist
  620. .insert("greylist".to_string(), self.greylist.read().await.iter().cloned().collect());
  621. hostlist
  622. }
  623. /// Get up to n random peers from the whitelist.
  624. pub async fn whitelist_fetch_n_random(&self, n: u32) -> Vec<(Url, u64)> {
  625. let n = n as usize;
  626. if n == 0 {
  627. return vec![]
  628. }
  629. let addrs = self.whitelist.read().await;
  630. let urls = addrs.iter().choose_multiple(&mut OsRng, n.min(addrs.len()));
  631. urls.iter().map(|&url| url.clone()).collect()
  632. }
  633. /// Get a random peer from the greylist.
  634. pub async fn greylist_fetch_random(&self) -> ((Url, u64), usize) {
  635. let greylist = self.greylist.read().await;
  636. let position = rand::thread_rng().gen_range(0..greylist.len());
  637. let entry = &greylist[position];
  638. (entry.clone(), position)
  639. }
  640. /// Get a random peer from the whitelist.
  641. pub async fn whitelist_fetch_random(&self) -> ((Url, u64), usize) {
  642. let whitelist = self.whitelist.read().await;
  643. let position = rand::thread_rng().gen_range(0..whitelist.len());
  644. let entry = &whitelist[position];
  645. (entry.clone(), position)
  646. }
  647. /// Get up to n random whitelisted peers that match the given transport schemes from the hosts set.
  648. pub async fn whitelist_fetch_n_random_with_schemes(
  649. &self,
  650. schemes: &[String],
  651. n: u32,
  652. ) -> Vec<(Url, u64)> {
  653. let n = n as usize;
  654. if n == 0 {
  655. return vec![]
  656. }
  657. trace!(target: "store::whitelist_fetch_n_random_with_schemes", "[START]");
  658. // Retrieve all peers corresponding to that transport schemes
  659. let hosts = self.whitelist_fetch_with_schemes(schemes, None).await;
  660. if hosts.is_empty() {
  661. trace!(target: "store::whitelist_fetch_n_random_with_schemes",
  662. "Whitelist is empty {:?}! Exiting...", hosts);
  663. return hosts
  664. }
  665. // Grab random ones
  666. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  667. urls.iter().map(|&url| url.clone()).collect()
  668. }
  669. /// Get up to limit peers that don't match the given transport schemes from the whitelist.
  670. /// If limit was not provided, return all matching peers.
  671. pub async fn whitelist_fetch_excluding_schemes(
  672. &self,
  673. schemes: &[String],
  674. limit: Option<usize>,
  675. ) -> Vec<(Url, u64)> {
  676. let addrs = self.whitelist.read().await;
  677. let mut limit = match limit {
  678. Some(l) => l.min(addrs.len()),
  679. None => addrs.len(),
  680. };
  681. let mut ret = vec![];
  682. if limit == 0 {
  683. return ret
  684. }
  685. for (addr, last_seen) in addrs.iter() {
  686. if !schemes.contains(&addr.scheme().to_string()) {
  687. ret.push((addr.clone(), *last_seen));
  688. limit -= 1;
  689. if limit == 0 {
  690. return ret
  691. }
  692. }
  693. }
  694. // If we didn't find any, pick some from the greylist
  695. if ret.is_empty() {
  696. for (addr, last_seen) in self.greylist.read().await.iter() {
  697. if !schemes.contains(&addr.scheme().to_string()) {
  698. ret.push((addr.clone(), *last_seen));
  699. limit -= 1;
  700. if limit == 0 {
  701. break
  702. }
  703. }
  704. }
  705. }
  706. ret
  707. }
  708. /// Get up to n random whitelisted peers that don't match the given transport schemes from the
  709. /// hosts set.
  710. pub async fn whitelist_fetch_n_random_excluding_schemes(
  711. &self,
  712. schemes: &[String],
  713. n: u32,
  714. ) -> Vec<(Url, u64)> {
  715. let n = n as usize;
  716. if n == 0 {
  717. return vec![]
  718. }
  719. trace!(target: "store::whitelist_fetch_excluding_schemes", "[START]");
  720. // Retrieve all peers not corresponding to that transport schemes
  721. let hosts = self.whitelist_fetch_excluding_schemes(schemes, None).await;
  722. if hosts.is_empty() {
  723. debug!(target: "store::whitelist_fetch_n_random_excluding_schemes",
  724. "No address without schemes found! Exiting...");
  725. return hosts
  726. }
  727. // Grab random ones
  728. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  729. urls.iter().map(|&url| url.clone()).collect()
  730. }
  731. /// Get up to limit peers that match the given transport schemes from the greylist.
  732. /// If limit was not provided, return all matching peers.
  733. async fn greylist_fetch_with_schemes(
  734. &self,
  735. schemes: &[String],
  736. limit: Option<usize>,
  737. ) -> Vec<(Url, u64)> {
  738. debug!(target: "store::greylist_fetch_with_schemes", "[START]");
  739. let greylist = self.greylist.read().await;
  740. let mut limit = match limit {
  741. Some(l) => l.min(greylist.len()),
  742. None => greylist.len(),
  743. };
  744. let mut ret = vec![];
  745. if limit == 0 {
  746. return ret
  747. }
  748. for (addr, last_seen) in greylist.iter() {
  749. if schemes.contains(&addr.scheme().to_string()) {
  750. ret.push((addr.clone(), *last_seen));
  751. limit -= 1;
  752. if limit == 0 {
  753. debug!(target: "store::greylist_fetch_with_schemes", "Found matching greylist entry, returning");
  754. return ret
  755. }
  756. }
  757. }
  758. trace!(target: "store::greylist_fetch_with_schemes", "END");
  759. ret
  760. }
  761. /// Get up to limit peers that match the given transport schemes from the whitelist.
  762. /// If limit was not provided, return all matching peers.
  763. async fn whitelist_fetch_with_schemes(
  764. &self,
  765. schemes: &[String],
  766. limit: Option<usize>,
  767. ) -> Vec<(Url, u64)> {
  768. debug!(target: "store::whitelist_fetch_with_schemes", "[START]");
  769. let mut ret = vec![];
  770. if !self.is_empty_whitelist().await {
  771. let whitelist = self.whitelist.read().await;
  772. let mut parsed_limit = match limit {
  773. Some(l) => l.min(whitelist.len()),
  774. None => whitelist.len(),
  775. };
  776. for (addr, last_seen) in whitelist.iter() {
  777. if schemes.contains(&addr.scheme().to_string()) {
  778. ret.push((addr.clone(), *last_seen));
  779. parsed_limit -= 1;
  780. if parsed_limit == 0 {
  781. trace!(target: "store::whitelist_fetch_with_schemes",
  782. "Found matching white scheme, returning {:?}", ret);
  783. return ret
  784. }
  785. } else {
  786. warn!(target: "store::whitelist_fetch_with_schemes",
  787. "No matching schemes! Trying greylist...");
  788. return self.greylist_fetch_with_schemes(schemes, limit).await
  789. }
  790. }
  791. }
  792. // Whitelist is empty!
  793. if !self.is_empty_greylist().await {
  794. // Select from the greylist providing it's not empty.
  795. return self.greylist_fetch_with_schemes(schemes, limit).await
  796. }
  797. trace!(target: "store::whitelist_fetch_with_schemes", "END");
  798. ret
  799. }
  800. /// Get up to limit peers that match the given transport schemes from the anchorlist.
  801. /// If limit was not provided, return all matching peers.
  802. async fn anchorlist_fetch_with_schemes(
  803. &self,
  804. schemes: &[String],
  805. limit: Option<usize>,
  806. ) -> Vec<(Url, u64)> {
  807. trace!(target: "store::anchorlist_fetch_with_schemes", "[START]");
  808. let mut ret = vec![];
  809. // Select from the anchorlist providing it's not empty.
  810. if !self.is_empty_anchorlist().await {
  811. let anchorlist = self.anchorlist.read().await;
  812. let mut parsed_limit = match limit {
  813. Some(l) => l.min(anchorlist.len()),
  814. None => anchorlist.len(),
  815. };
  816. for (addr, last_seen) in anchorlist.iter() {
  817. if schemes.contains(&addr.scheme().to_string()) {
  818. ret.push((addr.clone(), *last_seen));
  819. parsed_limit -= 1;
  820. if parsed_limit == 0 {
  821. trace!(target: "store::anchorlist_fetch_with_schemes",
  822. "Found matching anchor scheme, returning {:?}", ret);
  823. return ret
  824. }
  825. } else {
  826. warn!(target: "store::anchorlist_fetch_with_schemes",
  827. "No matching schemes! Trying whitelist...");
  828. return self.whitelist_fetch_with_schemes(schemes, limit).await
  829. }
  830. }
  831. }
  832. // Select from the whitelist providing it's not empty.
  833. if !self.is_empty_whitelist().await {
  834. return self.whitelist_fetch_with_schemes(schemes, limit).await
  835. }
  836. // Select from the greyist providing it's not empty.
  837. if !self.is_empty_greylist().await {
  838. return self.greylist_fetch_with_schemes(schemes, limit).await
  839. }
  840. trace!(target: "store::anchorlist_fetch_with_schemes", "END");
  841. ret
  842. }
  843. /// Load the hostlist from a file.
  844. pub async fn load_hosts(&self) -> Result<()> {
  845. let path = expand_path(&self.settings.hostlist)?;
  846. if !path.exists() {
  847. if let Some(parent) = path.parent() {
  848. fs::create_dir_all(parent)?;
  849. }
  850. File::create(path.clone())?;
  851. }
  852. let contents = load_file(&path);
  853. if let Err(e) = contents {
  854. warn!(target: "store", "Failed retrieving saved hosts: {}", e);
  855. return Ok(())
  856. }
  857. for line in contents.unwrap().lines() {
  858. let data: Vec<&str> = line.split('\t').collect();
  859. let url = match Url::parse(data[1]) {
  860. Ok(u) => u,
  861. Err(e) => {
  862. debug!(target: "store", "load_hosts(): Skipping malformed URL {}", e);
  863. continue
  864. }
  865. };
  866. let last_seen = match data[2].parse::<u64>() {
  867. Ok(t) => t,
  868. Err(e) => {
  869. debug!(target: "store", "load_hosts(): Skipping malformed last seen {}", e);
  870. continue
  871. }
  872. };
  873. match data[0] {
  874. "greylist" => {
  875. self.greylist_store(url, last_seen).await;
  876. }
  877. "whitelist" => {
  878. self.whitelist_store(url, last_seen).await;
  879. }
  880. "anchorlist" => {
  881. self.anchorlist_store(url, last_seen).await;
  882. }
  883. _ => {
  884. debug!(target: "store", "load_hosts(): Malformed list name...");
  885. }
  886. }
  887. }
  888. Ok(())
  889. }
  890. /// Save the hostlist to a file. Whitelist gets written to the greylist to force
  891. /// whitelist entries through the refinery on start.
  892. pub async fn save_hosts(&self) -> Result<()> {
  893. let path = expand_path(&self.settings.hostlist)?;
  894. let mut tsv = String::new();
  895. let mut whitelist = vec![];
  896. // First gather all the whitelist entries we don't have in greylist.
  897. for (url, last_seen) in self.whitelist_fetch_all().await {
  898. if !self.greylist_contains(&url).await {
  899. whitelist.push((url, last_seen))
  900. }
  901. }
  902. // Collect the greylist and anchorlist entries, and append any whitelist entries to the
  903. // greylist before saving.
  904. for (name, mut list) in self.hostlist_fetch_safe().await {
  905. if name == *"greylist".to_string() {
  906. list.append(&mut whitelist)
  907. }
  908. for (url, last_seen) in list {
  909. tsv.push_str(&format!("{}\t{}\t{}\n", name, url, last_seen));
  910. }
  911. }
  912. if !tsv.eq("") {
  913. info!(target: "store", "Saving hosts to: {:?}",
  914. path);
  915. if let Err(e) = save_file(&path, &tsv) {
  916. error!(target: "store", "Failed saving hosts: {}", e);
  917. }
  918. }
  919. Ok(())
  920. }
  921. }
  922. #[cfg(test)]
  923. mod tests {
  924. use super::{
  925. super::super::{settings::Settings, P2p},
  926. *,
  927. };
  928. use crate::system::sleep;
  929. use smol::Executor;
  930. use std::{sync::Arc, time::UNIX_EPOCH};
  931. #[test]
  932. fn test_is_local_host() {
  933. smol::block_on(async {
  934. let settings = Settings {
  935. localnet: false,
  936. external_addrs: vec![
  937. Url::parse("tcp://foo.bar:123").unwrap(),
  938. Url::parse("tcp://lol.cat:321").unwrap(),
  939. ],
  940. ..Default::default()
  941. };
  942. let hosts = Hosts::new(Arc::new(settings.clone()));
  943. let local_hosts: Vec<Url> = vec![
  944. Url::parse("tcp://localhost").unwrap(),
  945. Url::parse("tcp://127.0.0.1").unwrap(),
  946. Url::parse("tcp+tls://[::1]").unwrap(),
  947. Url::parse("tcp://localhost.localdomain").unwrap(),
  948. Url::parse("tcp://192.168.10.65").unwrap(),
  949. ];
  950. for host in local_hosts {
  951. eprintln!("{}", host);
  952. assert!(hosts.is_local_host(host).await);
  953. }
  954. let remote_hosts: Vec<Url> = vec![
  955. Url::parse("https://dyne.org").unwrap(),
  956. Url::parse("tcp://77.168.10.65:2222").unwrap(),
  957. Url::parse("tcp://[2345:0425:2CA1:0000:0000:0567:5673:23b5]").unwrap(),
  958. Url::parse("http://eweiibe6tdjsdprb4px6rqrzzcsi22m4koia44kc5pcjr7nec2rlxyad.onion")
  959. .unwrap(),
  960. ];
  961. for host in remote_hosts {
  962. assert!(!(hosts.is_local_host(host).await))
  963. }
  964. });
  965. }
  966. #[test]
  967. fn test_greylist_store() {
  968. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  969. smol::block_on(async {
  970. let settings = Settings {
  971. localnet: false,
  972. external_addrs: vec![
  973. Url::parse("tcp://foo.bar:123").unwrap(),
  974. Url::parse("tcp://lol.cat:321").unwrap(),
  975. ],
  976. ..Default::default()
  977. };
  978. let hosts = Hosts::new(Arc::new(settings.clone()));
  979. for addr in settings.external_addrs {
  980. hosts.greylist_store(addr, last_seen).await;
  981. }
  982. assert!(!hosts.is_empty_greylist().await);
  983. let local_hosts = vec![
  984. (Url::parse("tcp://localhost:3921").unwrap()),
  985. (Url::parse("tor://[::1]:21481").unwrap()),
  986. (Url::parse("tcp://192.168.10.65:311").unwrap()),
  987. (Url::parse("tcp+tls://0.0.0.0:2312").unwrap()),
  988. (Url::parse("tcp://255.255.255.255:2131").unwrap()),
  989. ];
  990. for host in &local_hosts {
  991. hosts.greylist_store(host.clone(), last_seen).await;
  992. }
  993. assert!(!hosts.is_empty_greylist().await);
  994. let remote_hosts = vec![
  995. (Url::parse("tcp://dark.fi:80").unwrap()),
  996. (Url::parse("tcp://http.cat:401").unwrap()),
  997. (Url::parse("tcp://foo.bar:111").unwrap()),
  998. ];
  999. for host in &remote_hosts {
  1000. hosts.greylist_store(host.clone(), last_seen).await;
  1001. }
  1002. assert!(hosts.greylist_contains(&remote_hosts[0]).await);
  1003. assert!(hosts.greylist_contains(&remote_hosts[1]).await);
  1004. assert!(hosts.greylist_contains(&remote_hosts[2]).await);
  1005. });
  1006. }
  1007. #[test]
  1008. fn test_whitelist_store() {
  1009. smol::block_on(async {
  1010. let settings = Settings {
  1011. localnet: false,
  1012. external_addrs: vec![
  1013. Url::parse("tcp://foo.bar:123").unwrap(),
  1014. Url::parse("tcp://lol.cat:321").unwrap(),
  1015. ],
  1016. ..Default::default()
  1017. };
  1018. let hosts = Hosts::new(Arc::new(settings.clone()));
  1019. assert!(hosts.is_empty_whitelist().await);
  1020. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  1021. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1022. hosts.whitelist_store(url.clone(), last_seen).await;
  1023. assert!(!hosts.is_empty_whitelist().await);
  1024. assert!(hosts.whitelist_contains(&url).await);
  1025. });
  1026. }
  1027. #[test]
  1028. fn test_hostlist_get_entry() {
  1029. smol::block_on(async {
  1030. let settings = Settings {
  1031. localnet: false,
  1032. external_addrs: vec![
  1033. Url::parse("tcp://foo.bar:123").unwrap(),
  1034. Url::parse("tcp://lol.cat:321").unwrap(),
  1035. ],
  1036. ..Default::default()
  1037. };
  1038. let hosts = Hosts::new(Arc::new(settings.clone()));
  1039. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  1040. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1041. hosts.whitelist_store(url.clone(), last_seen).await;
  1042. hosts.anchorlist_store(url.clone(), last_seen).await;
  1043. assert!(hosts.get_whitelist_entry_at_addr(&url).await.is_some());
  1044. assert!(hosts.get_anchorlist_entry_at_addr(&url).await.is_some());
  1045. });
  1046. }
  1047. #[test]
  1048. fn test_remove() {
  1049. smol::block_on(async {
  1050. let settings = Settings {
  1051. outbound_connections: 8,
  1052. allowed_transports: vec!["tcp".to_string()],
  1053. ..Default::default()
  1054. };
  1055. let hosts = Hosts::new(Arc::new(settings.clone()));
  1056. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  1057. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1058. hosts.whitelist_store(url.clone(), last_seen).await;
  1059. sleep(1).await;
  1060. let url = Url::parse("tcp://milady:333").unwrap();
  1061. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1062. hosts.whitelist_store(url.clone(), last_seen).await;
  1063. sleep(1).await;
  1064. let url = Url::parse("tcp://king-ted:333").unwrap();
  1065. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1066. hosts.whitelist_store(url.clone(), last_seen).await;
  1067. for (url, last_seen) in hosts.whitelist.read().await.iter() {
  1068. println!("{}, {}", url, last_seen);
  1069. }
  1070. let position = hosts.get_whitelist_index_at_addr(url.clone()).await.unwrap();
  1071. hosts.whitelist_remove(&url, position).await;
  1072. for (url, last_seen) in hosts.whitelist.read().await.iter() {
  1073. println!("{}, {}", url, last_seen);
  1074. }
  1075. });
  1076. }
  1077. #[test]
  1078. fn test_fetch_address() {
  1079. smol::block_on(async {
  1080. let mut hostlist = vec![];
  1081. let mut grey_urls = vec![];
  1082. let mut white_urls = vec![];
  1083. let mut anchor_urls = vec![];
  1084. let ex = Arc::new(Executor::new());
  1085. let settings = Settings {
  1086. outbound_connections: 8,
  1087. allowed_transports: vec!["tcp".to_string()],
  1088. ..Default::default()
  1089. };
  1090. let p2p = P2p::new(settings, ex.clone()).await;
  1091. let hosts = p2p.hosts();
  1092. // Build up a hostlist
  1093. for i in 0..5 {
  1094. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1095. hosts
  1096. .anchorlist_store(
  1097. Url::parse(&format!("tcp://anchorlist{}:123", i)).unwrap(),
  1098. last_seen,
  1099. )
  1100. .await;
  1101. hosts
  1102. .whitelist_store(
  1103. Url::parse(&format!("tcp://whitelist{}:123", i)).unwrap(),
  1104. last_seen,
  1105. )
  1106. .await;
  1107. hosts
  1108. .greylist_store(
  1109. Url::parse(&format!("tcp://greylist{}:123", i)).unwrap(),
  1110. last_seen,
  1111. )
  1112. .await;
  1113. grey_urls
  1114. .push((Url::parse(&format!("tcp://greylist{}:123", i)).unwrap(), last_seen));
  1115. white_urls
  1116. .push((Url::parse(&format!("tcp://whitelist{}:123", i)).unwrap(), last_seen));
  1117. anchor_urls
  1118. .push((Url::parse(&format!("tcp://anchorlist{}:123", i)).unwrap(), last_seen));
  1119. }
  1120. assert!(!hosts.is_empty_anchorlist().await);
  1121. assert!(!hosts.is_empty_whitelist().await);
  1122. assert!(!hosts.is_empty_greylist().await);
  1123. let transports = &p2p.settings().allowed_transports;
  1124. let white_count =
  1125. p2p.settings().outbound_connections * p2p.settings().white_connection_percent / 100;
  1126. // Simulate the address selection logic found in outbound_session::fetch_address()
  1127. for i in 0..8 {
  1128. let addrs = {
  1129. if i < p2p.settings().anchor_connection_count {
  1130. hosts.anchorlist_fetch_address(transports).await
  1131. } else if i < white_count {
  1132. hosts.whitelist_fetch_address(transports).await
  1133. } else {
  1134. hosts.greylist_fetch_address(transports).await
  1135. }
  1136. };
  1137. hostlist.push(addrs);
  1138. }
  1139. //// Check we're returning the correct addresses.
  1140. anchor_urls.sort();
  1141. white_urls.sort();
  1142. grey_urls.sort();
  1143. hostlist[0].sort();
  1144. hostlist[4].sort();
  1145. hostlist[7].sort();
  1146. assert!(anchor_urls == hostlist[0]);
  1147. assert!(white_urls == hostlist[4]);
  1148. assert!(grey_urls == hostlist[7]);
  1149. // Now clear the anchorlist.
  1150. // anchorlist_fetch_address should return whitelist entries if
  1151. // the anchorlist is empty.
  1152. let mut anchorlist = hosts.anchorlist.write().await;
  1153. anchorlist.clear();
  1154. drop(anchorlist);
  1155. let mut addrs = hosts.anchorlist_fetch_address(transports).await;
  1156. addrs.sort();
  1157. assert!(white_urls == addrs);
  1158. // Now clear the whitelist.
  1159. // anchorlist_fetch_address should return greylist entries if
  1160. // both the anchorlist and the whitelist are empty.
  1161. let mut whitelist = hosts.whitelist.write().await;
  1162. whitelist.clear();
  1163. drop(whitelist);
  1164. let mut addrs = hosts.anchorlist_fetch_address(transports).await;
  1165. addrs.sort();
  1166. assert!(grey_urls == addrs);
  1167. })
  1168. }
  1169. }