hosts.rs 64 KB

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