hosts.rs 58 KB

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