hosts.rs 57 KB

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