hosts.rs 69 KB

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