hosts.rs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::HashMap, fmt, fs, fs::File, sync::Arc, time::Instant};
  19. use log::{debug, error, info, trace, warn};
  20. use rand::{prelude::IteratorRandom, rngs::OsRng, Rng};
  21. use smol::lock::RwLock;
  22. use url::Url;
  23. use super::{settings::SettingsPtr, ChannelPtr};
  24. use crate::{
  25. system::{Subscriber, SubscriberPtr, Subscription},
  26. util::{
  27. file::{load_file, save_file},
  28. path::expand_path,
  29. },
  30. Error, Result,
  31. };
  32. /// The main interface for interacting with the hostlist. Contains the following:
  33. ///
  34. /// `Hosts`: the main parent class that manages HostRegistry and HostContainer. It is also
  35. /// responsible for filtering addresses before writing to the hostlist.
  36. ///
  37. /// `HostRegistry`: A locked HashMap that maps peer addresses onto mutually exclusive
  38. /// states (`HostState`). Prevents race conditions by dictating a strict flow of logically
  39. /// acceptable states.
  40. ///
  41. /// `HostContainer`: A wrapper for the hostlists. Each hostlist is represented by a `HostColor`,
  42. /// which can be Grey, White, Gold or Black. Exposes a common interface for hostlist queries and
  43. /// utilities.
  44. ///
  45. /// `HostColor`: White hosts have been seen recently. Gold hosts we have been able to establish
  46. /// a connection to. Grey hosts are recently received hosts that are periodically refreshed
  47. /// using the greylist refinery. Black hosts are considered hostile and are strictly avoided
  48. /// for the duration of the program. Dark hosts are hosts that do not match our transports, but
  49. /// that we continue to share with other peers. They are otherwise ignored.
  50. ///
  51. /// `HostState`: a set of mutually exclusive states that can be Insert, Refine, Connect, Suspend
  52. /// or Connected. The state is `None` when the corresponding host has been removed from the
  53. /// HostRegistry.
  54. // An array containing all possible local host strings
  55. // TODO: This could perhaps be more exhaustive?
  56. pub const LOCAL_HOST_STRS: [&str; 2] = ["localhost", "localhost.localdomain"];
  57. const WHITELIST_MAX_LEN: usize = 5000;
  58. const GREYLIST_MAX_LEN: usize = 2000;
  59. const DARKLIST_MAX_LEN: usize = 1000;
  60. /// Atomic pointer to hosts object
  61. pub type HostsPtr = Arc<Hosts>;
  62. /// Keeps track of hosts and their current state. Prevents race conditions
  63. /// where multiple threads are simultaneously trying to change the state of
  64. /// a given host.
  65. pub(in crate::net) type HostRegistry = RwLock<HashMap<Url, HostState>>;
  66. /// HostState is a set of mutually exclusive states that can be Insert,
  67. /// Refine, Move, Connect, Suspend or Connected. The state is `None` when the
  68. /// corresponding host has been removed from the HostRegistry.
  69. /// ```
  70. /// +------+
  71. /// | None |
  72. /// +------+
  73. /// ^
  74. /// |
  75. /// +------+ +---------+
  76. /// +------> | move | ---> | suspend |
  77. /// | +------+ +---------+
  78. /// | | |
  79. /// | | v +--------+
  80. /// +---------+ | +--------+ | insert |
  81. /// | connect | | | refine | +--------+
  82. /// +---------+ | +--------+ |
  83. /// | v | v
  84. /// | +-----------+ | +------+
  85. /// +---> | connected | <-------+-------> | None |
  86. /// +-----------+ +------+
  87. /// |
  88. /// v
  89. /// +------+
  90. /// | None |
  91. /// +------+
  92. ///
  93. /// ```
  94. /* NOTE: Currently if a user loses connectivity, they will be deleted from
  95. our hostlist by the refinery process and forgotten about until they regain
  96. connectivity and share their external address with the p2p network again.
  97. We may want to keep nodes with patchy connections in a `Red` list
  98. and periodically try to connect to them in Outbound Session, rather
  99. than sending them to the refinery (which will delete them if they are
  100. offline) as we do using `Suspend`. The current design favors reliability
  101. of connections but this may come at a risk for security since an attacker
  102. is likely to have good uptime. We want to insure that users with patchy
  103. connections or on mobile are still likely to be connected to.*/
  104. #[derive(Clone, Debug)]
  105. pub(in crate::net) enum HostState {
  106. /// Hosts that are currently being inserting into the hostlist.
  107. Insert,
  108. /// Hosts that are migrating from the greylist to the whitelist or being
  109. /// removed from the greylist, as defined in `refinery.rs`.
  110. Refine,
  111. /// Hosts that are being connected to in Outbound and Manual Session.
  112. Connect,
  113. /// Hosts that we have just failed to connect to. Marking a host as
  114. /// Suspend effectively sends this host to refinery, since Suspend->
  115. /// Refine is an acceptable state transition. Being marked as Suspend does
  116. /// not increase a host's probability of being refined, since the refinery
  117. /// selects its subjects randomly (with the caveat that we cannot refine
  118. /// nodes marked as Connect, Connected, Insert or Move). It does however
  119. /// mean this host cannot be connected to unless it passes through the
  120. /// refinery successfully.
  121. Suspend,
  122. /// Hosts that have been successfully connected to.
  123. Connected(ChannelPtr),
  124. /// Host that are moving between hostlists, implemented in
  125. /// store::move_host().
  126. Move,
  127. }
  128. impl HostState {
  129. // Try to change state to Insert. Only possible if we are not yet
  130. // tracking this host in the HostRegistry.
  131. fn try_insert(&self) -> Result<Self> {
  132. let start = self.to_string();
  133. let end = HostState::Insert.to_string();
  134. match self {
  135. HostState::Insert => Err(Error::HostStateBlocked(start, end)),
  136. HostState::Refine => Err(Error::HostStateBlocked(start, end)),
  137. HostState::Connect => Err(Error::HostStateBlocked(start, end)),
  138. HostState::Suspend => Err(Error::HostStateBlocked(start, end)),
  139. HostState::Connected(_) => Err(Error::HostStateBlocked(start, end)),
  140. HostState::Move => Err(Error::HostStateBlocked(start, end)),
  141. }
  142. }
  143. // Try to change state to Refine. Only possible if we are not yet
  144. // tracking this host in the HostRegistry or if the host is marked as
  145. // Suspend i.e. we have failed to connect to it.
  146. fn try_refine(&self) -> Result<Self> {
  147. let start = self.to_string();
  148. let end = HostState::Refine.to_string();
  149. match self {
  150. HostState::Insert => Err(Error::HostStateBlocked(start, end)),
  151. HostState::Refine => Err(Error::HostStateBlocked(start, end)),
  152. HostState::Connect => Err(Error::HostStateBlocked(start, end)),
  153. HostState::Suspend => Ok(HostState::Refine),
  154. HostState::Connected(_) => Err(Error::HostStateBlocked(start, end)),
  155. HostState::Move => Err(Error::HostStateBlocked(start, end)),
  156. }
  157. }
  158. // Try to change state to Connect. Only possible if we are not yet
  159. // tracking this host in the HostRegistry.
  160. fn try_connect(&self) -> Result<Self> {
  161. let start = self.to_string();
  162. let end = HostState::Connect.to_string();
  163. match self {
  164. HostState::Insert => Err(Error::HostStateBlocked(start, end)),
  165. HostState::Refine => Err(Error::HostStateBlocked(start, end)),
  166. HostState::Connect => Err(Error::HostStateBlocked(start, end)),
  167. HostState::Suspend => Err(Error::HostStateBlocked(start, end)),
  168. HostState::Connected(_) => Err(Error::HostStateBlocked(start, end)),
  169. HostState::Move => Err(Error::HostStateBlocked(start, end)),
  170. }
  171. }
  172. // Try to change state to Connected. Possible if this peer's state
  173. // is currently Connect or Refine, or Move. Refine is necessary since the
  174. // refinery process requires us to establish a connection to a peer.
  175. // Move is necessary due to the upgrade to Gold sequence in
  176. // `session::perform_handshake_protocols`.
  177. fn try_connected(&self, channel: ChannelPtr) -> Result<Self> {
  178. let start = self.to_string();
  179. let end = HostState::Connected(channel.clone()).to_string();
  180. match self {
  181. HostState::Insert => Err(Error::HostStateBlocked(start, end)),
  182. HostState::Refine => Ok(HostState::Connected(channel)),
  183. HostState::Connect => Ok(HostState::Connected(channel)),
  184. HostState::Suspend => Err(Error::HostStateBlocked(start, end)),
  185. HostState::Connected(_) => Err(Error::HostStateBlocked(start, end)),
  186. HostState::Move => Ok(HostState::Connected(channel)),
  187. }
  188. }
  189. // Try to change state to Move. Possibly if this host is currently
  190. // Connect i.e. it is being connected to, or if we are currently Connected
  191. // to this peer (due to host Downgrade sequence in `session::remove_sub_on_stop`)
  192. fn try_move(&self) -> Result<Self> {
  193. let start = self.to_string();
  194. let end = HostState::Move.to_string();
  195. match self {
  196. HostState::Insert => Err(Error::HostStateBlocked(start, end)),
  197. HostState::Refine => Err(Error::HostStateBlocked(start, end)),
  198. HostState::Connect => Ok(HostState::Move),
  199. HostState::Suspend => Err(Error::HostStateBlocked(start, end)),
  200. HostState::Connected(_) => Ok(HostState::Move),
  201. HostState::Move => Err(Error::HostStateBlocked(start, end)),
  202. }
  203. }
  204. // Try to change the state to Suspend. Only possible when we are
  205. // currently moving this host, since we suspend a host after failing
  206. // to connect to it in `outbound_session::try_connect` and then downgrading
  207. // in `hosts::move_host`.
  208. fn try_suspend(&self) -> Result<Self> {
  209. let start = self.to_string();
  210. let end = HostState::Suspend.to_string();
  211. match self {
  212. HostState::Insert => Err(Error::HostStateBlocked(start, end)),
  213. HostState::Refine => Err(Error::HostStateBlocked(start, end)),
  214. HostState::Connect => Err(Error::HostStateBlocked(start, end)),
  215. HostState::Suspend => Err(Error::HostStateBlocked(start, end)),
  216. HostState::Connected(_) => Err(Error::HostStateBlocked(start, end)),
  217. HostState::Move => Ok(HostState::Suspend),
  218. }
  219. }
  220. }
  221. impl fmt::Display for HostState {
  222. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  223. fmt::Debug::fmt(self, f)
  224. }
  225. }
  226. #[repr(u8)]
  227. #[derive(Clone, Debug)]
  228. pub enum HostColor {
  229. /// Intermediary nodes that are periodically probed and updated
  230. /// to White.
  231. Grey = 0,
  232. /// Recently seen hosts. Shared with other nodes.
  233. White = 1,
  234. /// Nodes to which we have already been able to establish a
  235. /// connection.
  236. Gold = 2,
  237. /// Hostile peers that can neither be connected to nor establish
  238. /// connections to us for the duration of the program.
  239. Black = 3,
  240. /// Peers that do not match our accepted transports. We are blind
  241. /// to these nodes (we do not use them) but we send them around
  242. /// the network anyway to ensure all transports are propagated.
  243. Dark = 4,
  244. }
  245. impl TryFrom<usize> for HostColor {
  246. type Error = Error;
  247. fn try_from(value: usize) -> Result<Self> {
  248. match value {
  249. 0 => Ok(HostColor::Grey),
  250. 1 => Ok(HostColor::White),
  251. 2 => Ok(HostColor::Gold),
  252. 3 => Ok(HostColor::Black),
  253. 4 => Ok(HostColor::Dark),
  254. _ => Err(Error::InvalidHostColor),
  255. }
  256. }
  257. }
  258. /// A Container for managing Grey, White, Gold and Black hostlists. Exposes
  259. /// a common interface for writing to and querying hostlists.
  260. // TODO: Benchmark hostlist operations when the hostlist is at max size.
  261. pub struct HostContainer {
  262. pub(in crate::net) hostlists: [RwLock<Vec<(Url, u64)>>; 5],
  263. }
  264. impl HostContainer {
  265. fn new() -> Self {
  266. let hostlists: [RwLock<Vec<(Url, u64)>>; 5] = [
  267. RwLock::new(Vec::new()),
  268. RwLock::new(Vec::new()),
  269. RwLock::new(Vec::new()),
  270. RwLock::new(Vec::new()),
  271. RwLock::new(Vec::new()),
  272. ];
  273. Self { hostlists }
  274. }
  275. /// Append host to a hostlist. Called when initalizing the hostlist in load_hosts().
  276. async fn store(&self, color: usize, addr: Url, last_seen: u64) {
  277. trace!(target: "net::hosts::store()", "[START] list={:?}",
  278. HostColor::try_from(color).unwrap());
  279. let mut list = self.hostlists[color].write().await;
  280. list.push((addr.clone(), last_seen));
  281. debug!(target: "net::hosts::store()", "Added [{}] to {:?} list",
  282. addr, HostColor::try_from(color).unwrap());
  283. if color == 0 && list.len() == GREYLIST_MAX_LEN {
  284. let last_entry = list.pop().unwrap();
  285. debug!(
  286. target: "net::hosts::store()",
  287. "Greylist reached max size. Removed {:?}", last_entry,
  288. );
  289. }
  290. if color == 1 && list.len() == WHITELIST_MAX_LEN {
  291. let last_entry = list.pop().unwrap();
  292. debug!(
  293. target: "net::hosts::store()",
  294. "Whitelist reached max size. Removed {:?}", last_entry,
  295. );
  296. }
  297. if color == 4 && list.len() == DARKLIST_MAX_LEN {
  298. let last_entry = list.pop().unwrap();
  299. debug!(
  300. target: "net::hosts::store()",
  301. "Darklist reached max size. Removed {:?}", last_entry,
  302. );
  303. }
  304. // Sort the list by last_seen.
  305. list.sort_by_key(|entry| entry.1);
  306. list.reverse();
  307. trace!(target: "net::hosts::store()", "[END] list={:?}",
  308. HostColor::try_from(color).unwrap());
  309. }
  310. /// Stores an address on a hostlist or updates its last_seen field if
  311. /// we already have the address.
  312. async fn store_or_update(&self, color: HostColor, addr: Url, last_seen: u64) {
  313. trace!(target: "net::hosts::store_or_update()", "[START]");
  314. let color_code = color.clone() as usize;
  315. let mut list = self.hostlists[color_code].write().await;
  316. if let Some(position) = list.iter().position(|(u, _)| u == &addr) {
  317. list[position] = (addr.clone(), last_seen);
  318. debug!(target: "net::hosts::store_or_update()", "Updated [{}] entry on {:?} list",
  319. addr, color.clone());
  320. } else {
  321. list.push((addr.clone(), last_seen));
  322. debug!(target: "net::hosts::store_or_update()", "Added [{}] to {:?} list", addr, color);
  323. if color_code == 0 && list.len() == GREYLIST_MAX_LEN {
  324. let last_entry = list.pop().unwrap();
  325. debug!(
  326. target: "net::hosts::store_or_update()",
  327. "Greylist reached max size. Removed {:?}", last_entry,
  328. );
  329. }
  330. if color_code == 1 && list.len() == WHITELIST_MAX_LEN {
  331. let last_entry = list.pop().unwrap();
  332. debug!(
  333. target: "net::hosts::store_or_update()",
  334. "Whitelist reached max size. Removed {:?}", last_entry,
  335. );
  336. }
  337. if color_code == 4 && list.len() == DARKLIST_MAX_LEN {
  338. let last_entry = list.pop().unwrap();
  339. debug!(
  340. target: "net::hosts::store_or_update()",
  341. "Darklist reached max size. Removed {:?}", last_entry,
  342. );
  343. }
  344. // Sort the list by last_seen.
  345. list.sort_by_key(|entry| entry.1);
  346. list.reverse();
  347. }
  348. trace!(target: "net::hosts::store_or_update()", "[STOP]");
  349. }
  350. /// Update the last_seen field of a peer on a hostlist.
  351. pub async fn update_last_seen(
  352. &self,
  353. color: usize,
  354. addr: &Url,
  355. last_seen: u64,
  356. position: Option<usize>,
  357. ) {
  358. trace!(target: "net::hosts::update_last_seen()", "[START] list={:?}",
  359. HostColor::try_from(color).unwrap());
  360. let i = match position {
  361. Some(i) => i,
  362. None => self.get_index_at_addr(color, addr.clone()).await.unwrap(),
  363. };
  364. let mut list = self.hostlists[color].write().await;
  365. list[i] = (addr.clone(), last_seen);
  366. list.sort_by_key(|entry| entry.1);
  367. list.reverse();
  368. trace!(target: "net::hosts::update_last_seen()", "[END] list={:?}",
  369. HostColor::try_from(color).unwrap());
  370. }
  371. /// Return all known hosts on a hostlist.
  372. pub async fn fetch_all(&self, color: HostColor) -> Vec<(Url, u64)> {
  373. self.hostlists[color as usize].read().await.iter().cloned().collect()
  374. }
  375. /// Get the oldest entry from a hostlist.
  376. pub async fn fetch_last(&self, color: HostColor) -> ((Url, u64), usize) {
  377. let list = self.hostlists[color as usize].read().await;
  378. let position = list.len() - 1;
  379. let entry = &list[position];
  380. (entry.clone(), position)
  381. }
  382. /// Fetch addresses that match the provided transports or acceptable
  383. /// mixed transports. Will return an empty Vector if no such addresses
  384. /// were found.
  385. pub(in crate::net) async fn fetch(
  386. &self,
  387. color: HostColor,
  388. transports: &[String],
  389. transport_mixing: bool,
  390. ) -> Vec<(Url, u64)> {
  391. trace!(target: "net::hosts::fetch_addrs()", "[START] {:?}", color);
  392. let mut hosts = vec![];
  393. let index = color as usize;
  394. // If transport mixing is enabled, then for example we're allowed to
  395. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  396. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  397. macro_rules! mix_transport {
  398. ($a:expr, $b:expr) => {
  399. if transports.contains(&$a.to_string()) && transport_mixing {
  400. let mut a_to_b = self.fetch_with_schemes(index, &[$b.to_string()], None).await;
  401. for (addr, last_seen) in a_to_b.iter_mut() {
  402. addr.set_scheme($a).unwrap();
  403. hosts.push((addr.clone(), last_seen.clone()));
  404. }
  405. }
  406. };
  407. }
  408. mix_transport!("tor", "tcp");
  409. mix_transport!("tor+tls", "tcp+tls");
  410. mix_transport!("nym", "tcp");
  411. mix_transport!("nym+tls", "tcp+tls");
  412. // And now the actual requested transports
  413. for (addr, last_seen) in self.fetch_with_schemes(index, transports, None).await {
  414. hosts.push((addr, last_seen));
  415. }
  416. trace!(target: "net::hosts::fetch_addrs()", "Grabbed hosts, length: {}", hosts.len());
  417. hosts
  418. }
  419. /// Get up to limit peers that match the given transport schemes from
  420. /// a hostlist. If limit was not provided, return all matching peers.
  421. async fn fetch_with_schemes(
  422. &self,
  423. color: usize,
  424. schemes: &[String],
  425. limit: Option<usize>,
  426. ) -> Vec<(Url, u64)> {
  427. trace!(target: "net::hosts::fetch_with_schemes()", "[START] {:?}",
  428. HostColor::try_from(color).unwrap());
  429. let list = self.hostlists[color].read().await;
  430. let mut limit = match limit {
  431. Some(l) => l.min(list.len()),
  432. None => list.len(),
  433. };
  434. let mut ret = vec![];
  435. if limit == 0 {
  436. return ret
  437. }
  438. for (addr, last_seen) in list.iter() {
  439. if schemes.contains(&addr.scheme().to_string()) {
  440. ret.push((addr.clone(), *last_seen));
  441. limit -= 1;
  442. if limit == 0 {
  443. debug!(target: "net::hosts::fetch_with_schemes()",
  444. "Found matching addr on list={:?}, returning {} addresses",
  445. HostColor::try_from(color).unwrap(), ret.len());
  446. return ret
  447. }
  448. }
  449. }
  450. if ret.is_empty() {
  451. debug!(target: "net::hosts::fetch_with_schemes()",
  452. "No matching schemes found on list={:?}!", HostColor::try_from(color).unwrap())
  453. }
  454. ret
  455. }
  456. /// Get up to limit peers that don't match the given transport schemes
  457. /// from a hostlist. If limit was not provided, return all matching
  458. /// peers.
  459. async fn fetch_excluding_schemes(
  460. &self,
  461. color: usize,
  462. schemes: &[String],
  463. limit: Option<usize>,
  464. ) -> Vec<(Url, u64)> {
  465. trace!(target: "net::hosts::fetch_with_schemes()", "[START] {:?}",
  466. HostColor::try_from(color).unwrap());
  467. let list = self.hostlists[color].read().await;
  468. let mut limit = match limit {
  469. Some(l) => l.min(list.len()),
  470. None => list.len(),
  471. };
  472. let mut ret = vec![];
  473. if limit == 0 {
  474. return ret
  475. }
  476. for (addr, last_seen) in list.iter() {
  477. if !schemes.contains(&addr.scheme().to_string()) {
  478. ret.push((addr.clone(), *last_seen));
  479. limit -= 1;
  480. if limit == 0 {
  481. return ret
  482. }
  483. }
  484. }
  485. if ret.is_empty() {
  486. debug!(target: "net::hosts::fetch_excluding_schemes()", "No such schemes found!");
  487. }
  488. ret
  489. }
  490. /// Get a random peer from a hostlist that matches the given transport
  491. /// schemes.
  492. pub(in crate::net) async fn fetch_random_with_schemes(
  493. &self,
  494. color: HostColor,
  495. schemes: &[String],
  496. ) -> Option<((Url, u64), usize)> {
  497. // Retrieve all peers corresponding to that transport schemes
  498. trace!(target: "net::hosts::fetch_random_with_schemes()", "[START] {:?}", color);
  499. let list = self.fetch_with_schemes(color as usize, schemes, None).await;
  500. if list.is_empty() {
  501. return None
  502. }
  503. let position = rand::thread_rng().gen_range(0..list.len());
  504. let entry = &list[position];
  505. Some((entry.clone(), position))
  506. }
  507. /// Get up to n random peers. Schemes are not taken into account.
  508. pub(in crate::net) async fn fetch_n_random(&self, color: HostColor, n: u32) -> Vec<(Url, u64)> {
  509. trace!(target: "net::hosts::fetch_n_random()", "[START] {:?}", color);
  510. let n = n as usize;
  511. if n == 0 {
  512. return vec![]
  513. }
  514. let mut hosts = vec![];
  515. let list = self.hostlists[color as usize].read().await;
  516. for (addr, last_seen) in list.iter() {
  517. hosts.push((addr.clone(), *last_seen));
  518. }
  519. if hosts.is_empty() {
  520. debug!(target: "net::hosts::fetch_n_random()", "No entries found!");
  521. return hosts
  522. }
  523. // Grab random ones
  524. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  525. urls.iter().map(|&url| url.clone()).collect()
  526. }
  527. /// Get up to n random peers that match the given transport schemes.
  528. pub(in crate::net) async fn fetch_n_random_with_schemes(
  529. &self,
  530. color: HostColor,
  531. schemes: &[String],
  532. n: u32,
  533. ) -> Vec<(Url, u64)> {
  534. trace!(target: "net::hosts::fetch_n_random_with_schemes()", "[START] {:?}", color);
  535. let index = color as usize;
  536. let n = n as usize;
  537. if n == 0 {
  538. return vec![]
  539. }
  540. // Retrieve all peers corresponding to that transport schemes
  541. let hosts = self.fetch_with_schemes(index, schemes, None).await;
  542. if hosts.is_empty() {
  543. debug!(target: "net::hosts::fetch_n_random_with_schemes()",
  544. "No such schemes found!");
  545. return hosts
  546. }
  547. // Grab random ones
  548. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  549. urls.iter().map(|&url| url.clone()).collect()
  550. }
  551. /// Get up to n random peers that don't match the given transport schemes
  552. /// from a hostlist.
  553. pub(in crate::net) async fn fetch_n_random_excluding_schemes(
  554. &self,
  555. color: HostColor,
  556. schemes: &[String],
  557. n: u32,
  558. ) -> Vec<(Url, u64)> {
  559. trace!(target: "net::hosts::fetch_excluding_schemes()", "[START] {:?}", color);
  560. let index = color as usize;
  561. let n = n as usize;
  562. if n == 0 {
  563. return vec![]
  564. }
  565. // Retrieve all peers not corresponding to that transport schemes
  566. let hosts = self.fetch_excluding_schemes(index, schemes, None).await;
  567. if hosts.is_empty() {
  568. debug!(target: "net::hosts::fetch_n_random_excluding_schemes()",
  569. "No such schemes found!");
  570. return hosts
  571. }
  572. // Grab random ones
  573. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  574. urls.iter().map(|&url| url.clone()).collect()
  575. }
  576. /// Remove an entry from a hostlist if it exists.
  577. async fn remove_if_exists(&self, color: HostColor, addr: &Url) {
  578. let color_code = color.clone() as usize;
  579. let mut list = self.hostlists[color_code].write().await;
  580. if let Some(position) = list.iter().position(|(u, _)| u == addr) {
  581. debug!(target: "net::hosts::remove_if_exists()", "Removing addr={} list={:?}", addr, color);
  582. list.remove(position);
  583. }
  584. }
  585. /// Check if a hostlist is empty.
  586. pub async fn is_empty(&self, color: HostColor) -> bool {
  587. self.hostlists[color as usize].read().await.is_empty()
  588. }
  589. /// Check if host is in a hostlist
  590. pub async fn contains(&self, color: usize, addr: &Url) -> bool {
  591. self.hostlists[color].read().await.iter().any(|(u, _t)| u == addr)
  592. }
  593. /// Get the index for a given addr on a hostlist.
  594. async fn get_index_at_addr(&self, color: usize, addr: Url) -> Option<usize> {
  595. self.hostlists[color].read().await.iter().position(|a| a.0 == addr)
  596. }
  597. /// Get the last_seen field for a given entry on a hostlist.
  598. pub async fn get_last_seen(&self, color: usize, addr: &Url) -> Option<u64> {
  599. self.hostlists[color]
  600. .read()
  601. .await
  602. .iter()
  603. .find(|(url, _)| url == addr)
  604. .map(|(_, last_seen)| *last_seen)
  605. }
  606. /// Load the hostlists from a file.
  607. pub(in crate::net) async fn load_all(&self, path: &str) -> Result<()> {
  608. let path = expand_path(path)?;
  609. if !path.exists() {
  610. if let Some(parent) = path.parent() {
  611. fs::create_dir_all(parent)?;
  612. }
  613. File::create(path.clone())?;
  614. }
  615. let contents = load_file(&path);
  616. if let Err(e) = contents {
  617. warn!(target: "net::hosts::load_hosts()", "Failed retrieving saved hosts: {}", e);
  618. return Ok(())
  619. }
  620. for line in contents.unwrap().lines() {
  621. let data: Vec<&str> = line.split('\t').collect();
  622. let url = match Url::parse(data[1]) {
  623. Ok(u) => u,
  624. Err(e) => {
  625. debug!(target: "net::hosts::load_hosts()", "Skipping malformed URL {}", e);
  626. continue
  627. }
  628. };
  629. let last_seen = match data[2].parse::<u64>() {
  630. Ok(t) => t,
  631. Err(e) => {
  632. debug!(target: "net::hosts::load_hosts()", "Skipping malformed last seen {}", e);
  633. continue
  634. }
  635. };
  636. match data[0] {
  637. "gold" => {
  638. self.store(HostColor::Gold as usize, url, last_seen).await;
  639. }
  640. "white" => {
  641. self.store(HostColor::White as usize, url, last_seen).await;
  642. }
  643. "grey" => {
  644. self.store(HostColor::Grey as usize, url, last_seen).await;
  645. }
  646. "dark" => {
  647. self.store(HostColor::Dark as usize, url, last_seen).await;
  648. }
  649. _ => {
  650. debug!(target: "net::hosts::load_hosts()", "Malformed list name...");
  651. }
  652. }
  653. }
  654. Ok(())
  655. }
  656. /// Save the hostlist to a file.
  657. pub(in crate::net) async fn save_all(&self, path: &str) -> Result<()> {
  658. let path = expand_path(path)?;
  659. let mut tsv = String::new();
  660. let mut hostlist: HashMap<String, Vec<(Url, u64)>> = HashMap::new();
  661. hostlist.insert("dark".to_string(), self.fetch_all(HostColor::Dark).await);
  662. hostlist.insert("grey".to_string(), self.fetch_all(HostColor::Grey).await);
  663. hostlist.insert("white".to_string(), self.fetch_all(HostColor::White).await);
  664. hostlist.insert("gold".to_string(), self.fetch_all(HostColor::Gold).await);
  665. for (name, list) in hostlist {
  666. for (url, last_seen) in list {
  667. tsv.push_str(&format!("{}\t{}\t{}\n", name, url, last_seen));
  668. }
  669. }
  670. if !tsv.eq("") {
  671. info!(target: "net::hosts::save_hosts()", "Saving hosts to: {:?}",
  672. path);
  673. if let Err(e) = save_file(&path, &tsv) {
  674. error!(target: "net::hosts::save_hosts()", "Failed saving hosts: {}", e);
  675. }
  676. }
  677. Ok(())
  678. }
  679. }
  680. /// Main parent class for the management and manipulation of
  681. /// hostlists. Keeps track of hosts and their current state via the
  682. /// HostRegistry, and stores hostlists and associated methods in the
  683. /// HostContainer. Also operates two subscribers to notify other parts
  684. /// of the code base when new channels have been created or new hosts
  685. /// have been added to the hostlist.
  686. pub struct Hosts {
  687. /// A registry that tracks hosts and their current state.
  688. registry: HostRegistry,
  689. /// Hostlists and associated methods.
  690. pub container: HostContainer,
  691. /// Subscriber listening for store updates
  692. store_subscriber: SubscriberPtr<usize>,
  693. /// Subscriber for notifications of new channels
  694. pub(in crate::net) channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  695. /// Keeps track of the last time a connection was made.
  696. pub(in crate::net) last_connection: RwLock<Instant>,
  697. /// Pointer to configured P2P settings
  698. settings: SettingsPtr,
  699. }
  700. impl Hosts {
  701. /// Create a new hosts list
  702. pub(in crate::net) fn new(settings: SettingsPtr) -> HostsPtr {
  703. Arc::new(Self {
  704. registry: RwLock::new(HashMap::new()),
  705. container: HostContainer::new(),
  706. store_subscriber: Subscriber::new(),
  707. channel_subscriber: Subscriber::new(),
  708. last_connection: RwLock::new(Instant::now()),
  709. settings,
  710. })
  711. }
  712. /// Safely insert into the HostContainer. Filters the addresses first before storing and
  713. /// notifies the subscriber. Must be called when first receiving greylist addresses.
  714. pub(in crate::net) async fn insert(&self, color: HostColor, addrs: &[(Url, u64)]) {
  715. trace!(target: "net::hosts:insert()", "[START]");
  716. // First filter these address to ensure this peer doesn't exist in our black, gold or
  717. // whitelist and apply transport filtering. If we don't support this transport,
  718. // store the peer on our dark list to broadcast to other nodes.
  719. let filtered_addrs = self.filter_addresses(self.settings.clone(), addrs).await;
  720. let mut addrs_len = 0;
  721. if filtered_addrs.is_empty() {
  722. debug!(target: "net::hosts::insert()", "Filtered out all addresses");
  723. }
  724. // Then ensure we aren't currently trying to add this peer to the hostlist.
  725. for (i, (addr, last_seen)) in filtered_addrs.iter().enumerate() {
  726. if let Err(e) = self.try_register(addr.clone(), HostState::Insert).await {
  727. debug!(target: "net::hosts::store_or_update", "Cannot insert addr={}, err={}",
  728. addr.clone(), e);
  729. continue
  730. }
  731. addrs_len += i + 1;
  732. self.container.store_or_update(color.clone(), addr.clone(), *last_seen).await;
  733. // Free up this peer for usage by other parts of the code base.
  734. // This is a safe since the hostlist modification is now complete.
  735. self.unregister(addr).await;
  736. }
  737. self.store_subscriber.notify(addrs_len).await;
  738. trace!(target: "net::hosts:insert()", "[END]");
  739. }
  740. /// Check whether a peer is available to be refined currently. Returns true
  741. /// if available, false otherwise.
  742. pub async fn refinable(&self, addr: Url) -> bool {
  743. self.try_register(addr.clone(), HostState::Refine).await.is_ok()
  744. }
  745. /// Try to update the registry. If the host already exists, try to update its state.
  746. /// Otherwise add the host to the registry along with its state.
  747. pub(in crate::net) async fn try_register(
  748. &self,
  749. addr: Url,
  750. new_state: HostState,
  751. ) -> Result<HostState> {
  752. let mut registry = self.registry.write().await;
  753. trace!(target: "net::hosts::try_update_registry()", "Try register addr={}, state={}",
  754. addr, &new_state);
  755. if registry.contains_key(&addr) {
  756. let current_state = registry.get(&addr).unwrap().clone();
  757. let result: Result<HostState> = match new_state {
  758. HostState::Insert => current_state.try_insert(),
  759. HostState::Refine => current_state.try_refine(),
  760. HostState::Connect => current_state.try_connect(),
  761. HostState::Suspend => current_state.try_suspend(),
  762. HostState::Connected(c) => current_state.try_connected(c),
  763. HostState::Move => current_state.try_move(),
  764. };
  765. if let Ok(state) = &result {
  766. registry.insert(addr.clone(), state.clone());
  767. }
  768. trace!(target: "net::hosts::try_update_registry()", "Returning result {:?}", result);
  769. result
  770. } else {
  771. // We don't know this peer. We can safely update the state.
  772. debug!(target: "net::hosts::try_update_registry()", "Inserting addr={}, state={}",
  773. addr, &new_state);
  774. registry.insert(addr.clone(), new_state.clone());
  775. Ok(new_state)
  776. }
  777. }
  778. // Loop through hosts selected by Outbound Session and see if any of them are
  779. // free to connect to.
  780. pub(in crate::net) async fn check_addrs(&self, hosts: Vec<(Url, u64)>) -> Option<(Url, u64)> {
  781. trace!(target: "net::hosts::check_addrs()", "[START]");
  782. for (host, last_seen) in hosts {
  783. // Print a warning if we are trying to connect to a seed node in
  784. // Outbound session. This shouldn't happen as we reject configured
  785. // seed nodes from entering our hostlist in filter_addrs().
  786. if self.settings.seeds.contains(&host) {
  787. warn!(target: "net::hosts::check_addrs",
  788. "Seed addr={} has entered the hostlist! Skipping",
  789. host.clone());
  790. continue
  791. }
  792. if let Err(e) = self.try_register(host.clone(), HostState::Connect).await {
  793. trace!(target: "net::hosts::check_addrs", "Skipping addr={}, err={}",
  794. host.clone(), e);
  795. continue
  796. }
  797. debug!(target: "net::hosts::check_addrs()", "Found valid host {}", host);
  798. return Some((host.clone(), last_seen))
  799. }
  800. None
  801. }
  802. /// Remove a host from the HostRegistry. Must be called after move(), when the refinery
  803. /// process fails, or when a channel stops. Prevents hosts from getting trapped in the
  804. /// HostState logical machinery.
  805. ///
  806. /// Misuse of this call is dangerous since it frees up the peer to be used by
  807. /// the refinery or outbound connect loop, and may result in invalid states. It should
  808. /// only be called when it is completely safe to do so.
  809. pub(in crate::net) async fn unregister(&self, addr: &Url) {
  810. self.registry.write().await.remove(addr);
  811. debug!(target: "net::hosts::unregister()", "Removed {} from HostRegistry", addr);
  812. }
  813. /// Returns the list of connected channels.
  814. pub async fn channels(&self) -> Vec<ChannelPtr> {
  815. let registry = self.registry.read().await;
  816. let mut channels = Vec::new();
  817. for (_, state) in registry.iter() {
  818. if let HostState::Connected(c) = state {
  819. channels.push(c.clone());
  820. }
  821. }
  822. channels
  823. }
  824. /// Returns the list of suspended channels.
  825. pub(in crate::net) async fn suspended(&self) -> Vec<Url> {
  826. let registry = self.registry.read().await;
  827. let mut addrs = Vec::new();
  828. for (url, state) in registry.iter() {
  829. if let HostState::Suspend = state {
  830. addrs.push(url.clone());
  831. }
  832. }
  833. addrs
  834. }
  835. /// Retrieve a random connected channel
  836. pub async fn random_channel(&self) -> ChannelPtr {
  837. let channels = self.channels().await;
  838. let position = rand::thread_rng().gen_range(0..channels.len());
  839. channels[position].clone()
  840. }
  841. /// Add a channel to the set of connected channels
  842. pub(in crate::net) async fn register_channel(&self, channel: ChannelPtr) {
  843. let address = channel.address().clone();
  844. // This will panic if we are already connected to this peer, this peer
  845. // is suspended, or this peer is currently being inserted into the hostlist.
  846. // None of these scenarios should ever happen.
  847. self.try_register(address.clone(), HostState::Connected(channel.clone())).await.unwrap();
  848. // Notify that channel processing was successful
  849. self.channel_subscriber.notify(Ok(channel.clone())).await;
  850. let mut last_online = self.last_connection.write().await;
  851. *last_online = Instant::now();
  852. }
  853. pub async fn subscribe_store(&self) -> Subscription<usize> {
  854. self.store_subscriber.clone().subscribe().await
  855. }
  856. pub async fn subscribe_channel(&self) -> Subscription<Result<ChannelPtr>> {
  857. self.channel_subscriber.clone().subscribe().await
  858. }
  859. // Verify whether a URL is local.
  860. // NOTE: This function is stateless and not specific to
  861. // `Hosts`. For this reason, it might make more sense
  862. // to move this function to a more appropriate location
  863. // in the codebase.
  864. /// Check whether a URL is local host
  865. pub async fn is_local_host(&self, url: Url) -> bool {
  866. // Reject Urls without host strings.
  867. if url.host_str().is_none() {
  868. return false
  869. }
  870. // We do this hack in order to parse IPs properly.
  871. // https://github.com/whatwg/url/issues/749
  872. let addr = Url::parse(&url.as_str().replace(url.scheme(), "http")).unwrap();
  873. // Filter private IP ranges
  874. match addr.host().unwrap() {
  875. url::Host::Ipv4(ip) => {
  876. if !ip.is_global() {
  877. return true
  878. }
  879. }
  880. url::Host::Ipv6(ip) => {
  881. if !ip.is_global() {
  882. return true
  883. }
  884. }
  885. url::Host::Domain(d) => {
  886. if LOCAL_HOST_STRS.contains(&d) {
  887. return true
  888. }
  889. }
  890. }
  891. false
  892. }
  893. /// Import blacklisted peers specified in the config file.
  894. pub(in crate::net) async fn import_blacklist(&self) -> Result<()> {
  895. for (mut host, ports) in self.settings.blacklist.clone() {
  896. // If the ports are empty, simply store the host_str. We will use this to
  897. // blacklist all ports of a given peer in `block_all_ports()`.
  898. if ports.is_empty() {
  899. self.container.store(HostColor::Black as usize, host.clone(), 0).await;
  900. }
  901. // Otherwise, store all the specified ports.
  902. else {
  903. for port in ports {
  904. host.set_port(Some(port))?;
  905. self.container.store(HostColor::Black as usize, host.clone(), 0).await;
  906. }
  907. }
  908. }
  909. Ok(())
  910. }
  911. /// If we have the Host of the Url in the hostlist, and there are no ports stored,
  912. /// we should block all ports of this peer.
  913. pub(in crate::net) async fn block_all_ports(&self, addr: String) -> bool {
  914. self.container.hostlists[HostColor::Black as usize]
  915. .read()
  916. .await
  917. .iter()
  918. .any(|(u, _t)| u.host_str().unwrap() == addr && u.port().is_none())
  919. }
  920. /// Filter given addresses based on certain rulesets and validity. Strictly called only on
  921. /// the first time learning of a new peer.
  922. async fn filter_addresses(
  923. &self,
  924. settings: SettingsPtr,
  925. addrs: &[(Url, u64)],
  926. ) -> Vec<(Url, u64)> {
  927. debug!(target: "net::hosts::filter_addresses()", "Filtering addrs: {:?}", addrs);
  928. let mut ret = vec![];
  929. let localnet = self.settings.localnet;
  930. 'addr_loop: for (addr_, last_seen) in addrs {
  931. // Validate that the format is `scheme://host_str:port`
  932. if addr_.host_str().is_none() ||
  933. addr_.port().is_none() ||
  934. addr_.cannot_be_a_base() ||
  935. addr_.path_segments().is_some()
  936. {
  937. debug!(target: "net::hosts::filter_addresses()",
  938. "[{}] has invalid addr format. Skipping", addr_);
  939. continue
  940. }
  941. // Configured seeds should never enter the hostlist.
  942. if self.settings.seeds.contains(addr_) {
  943. debug!(target: "net::hosts::filter_addresses()",
  944. "[{}] is a configured seed. Skipping", addr_);
  945. continue
  946. }
  947. // Blacklist peers should never enter the hostlist.
  948. if self.container.contains(HostColor::Black as usize, addr_).await ||
  949. self.block_all_ports(addr_.host_str().unwrap().to_string()).await
  950. {
  951. warn!(target: "net::hosts::filter_addresses()",
  952. "[{}] is blacklisted", addr_);
  953. continue
  954. }
  955. let host_str = addr_.host_str().unwrap();
  956. if !localnet {
  957. // Our own external addresses should never enter the hosts set.
  958. for ext in &settings.external_addrs {
  959. if host_str == ext.host_str().unwrap() {
  960. debug!(target: "net::hosts::filter_addresses()",
  961. "[{}] is our own external addr. Skipping", addr_);
  962. continue 'addr_loop
  963. }
  964. }
  965. } else {
  966. // On localnet, make sure ours ports don't enter the host set.
  967. for ext in &settings.external_addrs {
  968. if addr_.port() == ext.port() {
  969. debug!(target: "net::hosts::filter_addresses()",
  970. "[{}] is our own localnet port. Skipping", addr_);
  971. continue 'addr_loop
  972. }
  973. }
  974. }
  975. // We do this hack in order to parse IPs properly.
  976. // https://github.com/whatwg/url/issues/749
  977. let addr = Url::parse(&addr_.as_str().replace(addr_.scheme(), "http")).unwrap();
  978. // Filter non-global ranges if we're not allowing localnet.
  979. // Should never be allowed in production, so we don't really care
  980. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  981. if !localnet && self.is_local_host(addr).await {
  982. debug!(target: "net::hosts::filter_addresses()",
  983. "[{}] Filtering non-global ranges", addr_);
  984. continue
  985. }
  986. match addr_.scheme() {
  987. // Validate that the address is an actual onion.
  988. #[cfg(feature = "p2p-tor")]
  989. "tor" | "tor+tls" => {
  990. use std::str::FromStr;
  991. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  992. continue
  993. }
  994. trace!(target: "net::hosts::filter_addresses()",
  995. "[Tor] Valid: {}", host_str);
  996. }
  997. #[cfg(feature = "p2p-nym")]
  998. "nym" | "nym+tls" => continue, // <-- Temp skip
  999. #[cfg(feature = "p2p-tcp")]
  1000. "tcp" | "tcp+tls" => {
  1001. trace!(target: "net::hosts::filter_addresses()",
  1002. "[TCP] Valid: {}", host_str);
  1003. }
  1004. _ => continue,
  1005. }
  1006. // Store this peer on Dark list if we do not support this transport.
  1007. // We will personally ignore this peer but still send it to others in
  1008. // Protocol Addr to ensure all transports get propagated.
  1009. if !settings.allowed_transports.contains(&addr_.scheme().to_string()) {
  1010. self.container.store_or_update(HostColor::Dark, addr_.clone(), *last_seen).await;
  1011. continue
  1012. }
  1013. // Reject this peer if it's already stored on the Gold, White or Grey list.
  1014. //
  1015. // We do this last since it is the most expensive operation.
  1016. if self.container.contains(HostColor::Gold as usize, addr_).await ||
  1017. self.container.contains(HostColor::White as usize, addr_).await ||
  1018. self.container.contains(HostColor::Grey as usize, addr_).await
  1019. {
  1020. debug!(target: "net::hosts::filter_addresses()", "[{}] exists! Skipping", addr_);
  1021. continue
  1022. }
  1023. ret.push((addr_.clone(), *last_seen));
  1024. }
  1025. ret
  1026. }
  1027. /// Method to fetch the last_seen field for a give address when we do
  1028. /// not know what hostlist it is on.
  1029. pub async fn fetch_last_seen(&self, addr: &Url) -> Option<u64> {
  1030. if self.container.contains(HostColor::Gold as usize, addr).await {
  1031. self.container.get_last_seen(HostColor::Gold as usize, addr).await
  1032. } else if self.container.contains(HostColor::White as usize, addr).await {
  1033. self.container.get_last_seen(HostColor::White as usize, addr).await
  1034. } else if self.container.contains(HostColor::Grey as usize, addr).await {
  1035. self.container.get_last_seen(HostColor::Grey as usize, addr).await
  1036. } else {
  1037. None
  1038. }
  1039. }
  1040. /// Downgrade host to Greylist, remove from Gold or White list.
  1041. pub async fn greylist_host(&self, addr: &Url, last_seen: u64) -> Result<()> {
  1042. debug!(target: "net::hosts:greylist_host()", "Downgrading addr={}", addr);
  1043. self.move_host(addr, last_seen, HostColor::Grey).await?;
  1044. // Free up this addr for future operations.
  1045. self.unregister(addr).await;
  1046. Ok(())
  1047. }
  1048. /// A single atomic function for moving hosts between hostlists. Called on the following occasions:
  1049. ///
  1050. /// * When we cannot connect to a peer: move to grey, remove from white and gold.
  1051. /// * When a peer disconnects from us: move to grey, remove from white and gold.
  1052. /// * When the refinery passes successfully: move to white, remove from greylist.
  1053. /// * When we connect to a peer, move to gold, remove from white or grey.
  1054. /// * When we add a peer to the black list: move to black, remove from all other lists.
  1055. pub(in crate::net) async fn move_host(
  1056. &self,
  1057. addr: &Url,
  1058. last_seen: u64,
  1059. destination: HostColor,
  1060. ) -> Result<()> {
  1061. debug!(target: "net::hosts::move_host()", "Trying to move addr={} destination={:?}",
  1062. addr, destination);
  1063. // This should never panic. Failure indicates a misuse of the HostState API.
  1064. self.try_register(addr.clone(), HostState::Move).await.unwrap();
  1065. match destination {
  1066. // Downgrade to grey. Remove from white and gold.
  1067. HostColor::Grey => {
  1068. self.container.remove_if_exists(HostColor::Gold, addr).await;
  1069. self.container.remove_if_exists(HostColor::White, addr).await;
  1070. self.container.store_or_update(HostColor::Grey, addr.clone(), last_seen).await;
  1071. }
  1072. // Remove from Greylist, add to Whitelist. Called by the Refinery.
  1073. HostColor::White => {
  1074. self.container.remove_if_exists(HostColor::Grey, addr).await;
  1075. self.container.store_or_update(HostColor::White, addr.clone(), last_seen).await;
  1076. }
  1077. // Upgrade to gold. Remove from white or grey.
  1078. HostColor::Gold => {
  1079. self.container.remove_if_exists(HostColor::Grey, addr).await;
  1080. self.container.remove_if_exists(HostColor::White, addr).await;
  1081. self.container.store_or_update(HostColor::Gold, addr.clone(), last_seen).await;
  1082. }
  1083. // Move to black. Remove from all other lists.
  1084. HostColor::Black => {
  1085. // We ignore UNIX sockets here so we will just work
  1086. // with stuff that has host_str().
  1087. if addr.host_str().is_some() {
  1088. // Localhost connections should never enter the blacklist
  1089. // This however allows any Tor and Nym connections.
  1090. if self.is_local_host(addr.clone()).await {
  1091. return Ok(());
  1092. }
  1093. self.container.remove_if_exists(HostColor::Grey, addr).await;
  1094. self.container.remove_if_exists(HostColor::White, addr).await;
  1095. self.container.remove_if_exists(HostColor::Gold, addr).await;
  1096. self.container.store_or_update(HostColor::Black, addr.clone(), last_seen).await;
  1097. }
  1098. }
  1099. HostColor::Dark => return Err(Error::InvalidHostColor),
  1100. }
  1101. Ok(())
  1102. }
  1103. }
  1104. #[cfg(test)]
  1105. mod tests {
  1106. use std::time::UNIX_EPOCH;
  1107. use super::{super::settings::Settings, *};
  1108. use crate::system::sleep;
  1109. #[test]
  1110. fn test_is_local_host() {
  1111. smol::block_on(async {
  1112. let settings = Settings {
  1113. localnet: false,
  1114. external_addrs: vec![
  1115. Url::parse("tcp://foo.bar:123").unwrap(),
  1116. Url::parse("tcp://lol.cat:321").unwrap(),
  1117. ],
  1118. ..Default::default()
  1119. };
  1120. let hosts = Hosts::new(Arc::new(settings.clone()));
  1121. let local_hosts: Vec<Url> = vec![
  1122. Url::parse("tcp://localhost").unwrap(),
  1123. Url::parse("tcp://127.0.0.1").unwrap(),
  1124. Url::parse("tcp+tls://[::1]").unwrap(),
  1125. Url::parse("tcp://localhost.localdomain").unwrap(),
  1126. Url::parse("tcp://192.168.10.65").unwrap(),
  1127. ];
  1128. for host in local_hosts {
  1129. eprintln!("{}", host);
  1130. assert!(hosts.is_local_host(host).await);
  1131. }
  1132. let remote_hosts: Vec<Url> = vec![
  1133. Url::parse("https://dyne.org").unwrap(),
  1134. Url::parse("tcp://77.168.10.65:2222").unwrap(),
  1135. Url::parse("tcp://[2345:0425:2CA1:0000:0000:0567:5673:23b5]").unwrap(),
  1136. Url::parse("http://eweiibe6tdjsdprb4px6rqrzzcsi22m4koia44kc5pcjr7nec2rlxyad.onion")
  1137. .unwrap(),
  1138. ];
  1139. for host in remote_hosts {
  1140. assert!(!hosts.is_local_host(host).await)
  1141. }
  1142. });
  1143. }
  1144. #[test]
  1145. fn test_block_all_ports() {
  1146. smol::block_on(async {
  1147. let settings = Settings { ..Default::default() };
  1148. let hosts = Hosts::new(Arc::new(settings.clone()));
  1149. let blacklist1 = Url::parse("tcp+tls://nietzsche.king:333").unwrap();
  1150. let blacklist2 = Url::parse("tcp+tls://agorism.xyz").unwrap();
  1151. hosts.container.store(HostColor::Black as usize, blacklist1.clone(), 0).await;
  1152. hosts.container.store(HostColor::Black as usize, blacklist2.clone(), 0).await;
  1153. assert!(hosts.block_all_ports(blacklist2.host_str().unwrap().to_string()).await);
  1154. assert!(!hosts.block_all_ports(blacklist1.host_str().unwrap().to_string()).await);
  1155. });
  1156. }
  1157. #[test]
  1158. fn test_store() {
  1159. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1160. smol::block_on(async {
  1161. let settings = Settings { ..Default::default() };
  1162. let hosts = Hosts::new(Arc::new(settings.clone()));
  1163. let grey_hosts = vec![
  1164. Url::parse("tcp://localhost:3921").unwrap(),
  1165. Url::parse("tor://[::1]:21481").unwrap(),
  1166. Url::parse("tcp://192.168.10.65:311").unwrap(),
  1167. Url::parse("tcp+tls://0.0.0.0:2312").unwrap(),
  1168. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  1169. ];
  1170. for addr in &grey_hosts {
  1171. hosts.container.store(HostColor::Grey as usize, addr.clone(), last_seen).await;
  1172. }
  1173. assert!(!hosts.container.is_empty(HostColor::Grey).await);
  1174. let white_hosts = vec![
  1175. Url::parse("tcp://localhost:3921").unwrap(),
  1176. Url::parse("tor://[::1]:21481").unwrap(),
  1177. Url::parse("tcp://192.168.10.65:311").unwrap(),
  1178. Url::parse("tcp+tls://0.0.0.0:2312").unwrap(),
  1179. Url::parse("tcp://255.255.255.255:2131").unwrap(),
  1180. ];
  1181. for host in &white_hosts {
  1182. hosts.container.store(HostColor::White as usize, host.clone(), last_seen).await;
  1183. }
  1184. assert!(!hosts.container.is_empty(HostColor::White).await);
  1185. let gold_hosts = vec![
  1186. Url::parse("tcp://dark.fi:80").unwrap(),
  1187. Url::parse("tcp://http.cat:401").unwrap(),
  1188. Url::parse("tcp://foo.bar:111").unwrap(),
  1189. ];
  1190. for host in &gold_hosts {
  1191. hosts.container.store(HostColor::Gold as usize, host.clone(), last_seen).await;
  1192. }
  1193. assert!(hosts.container.contains(HostColor::Grey as usize, &grey_hosts[0]).await);
  1194. assert!(hosts.container.contains(HostColor::White as usize, &white_hosts[1]).await);
  1195. assert!(hosts.container.contains(HostColor::Gold as usize, &gold_hosts[2]).await);
  1196. });
  1197. }
  1198. #[test]
  1199. fn test_get_last() {
  1200. smol::block_on(async {
  1201. let settings = Settings { ..Default::default() };
  1202. let hosts = Hosts::new(Arc::new(settings.clone()));
  1203. // Build up a hostlist
  1204. for i in 0..10 {
  1205. sleep(1).await;
  1206. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1207. let url = Url::parse(&format!("tcp://whitelist{}:123", i)).unwrap();
  1208. hosts.container.store(HostColor::White as usize, url.clone(), last_seen).await;
  1209. }
  1210. for (url, last_seen) in
  1211. hosts.container.hostlists[HostColor::White as usize].read().await.iter()
  1212. {
  1213. println!("{} {}", url, last_seen);
  1214. }
  1215. let (entry, _position) = hosts.container.fetch_last(HostColor::White).await;
  1216. println!("last entry: {} {}", entry.0, entry.1);
  1217. });
  1218. }
  1219. }