hosts.rs 60 KB

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