refine_session.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. //! `RefineSession` manages the `GreylistRefinery`, which randomly selects
  19. //! entries on the greylist and updates them to whitelist if active,
  20. //!
  21. //! `GreylistRefinery` makes use of a `RefineSession` method called
  22. //! `handshake_node()`, which uses a `Connector` to establish a `Channel` with
  23. //! a provided address, and then does a version exchange across the channel
  24. //! (`perform_handshake_protocols`). `handshake_node()` can either succeed,
  25. //! fail, or timeout.
  26. use futures::{
  27. future::{select, Either},
  28. pin_mut,
  29. };
  30. use smol::Timer;
  31. use std::{
  32. sync::{Arc, Mutex, Weak},
  33. time::{Duration, Instant, UNIX_EPOCH},
  34. };
  35. use async_trait::async_trait;
  36. use log::{debug, warn};
  37. use url::Url;
  38. use super::super::p2p::{P2p, P2pPtr};
  39. use crate::{
  40. net::{
  41. connector::Connector,
  42. hosts::{HostColor, HostState},
  43. protocol::ProtocolVersion,
  44. session::{Session, SessionBitFlag, SESSION_REFINE},
  45. },
  46. system::{sleep, StoppableTask, StoppableTaskPtr},
  47. Error,
  48. };
  49. pub type RefineSessionPtr = Arc<RefineSession>;
  50. pub struct RefineSession {
  51. /// Weak pointer to parent p2p object
  52. pub(in crate::net) p2p: Weak<P2p>,
  53. /// Task that periodically checks entries in the greylist.
  54. pub(in crate::net) refinery: Arc<GreylistRefinery>,
  55. /// Task that clears the darklist once daily.
  56. darklist_clear_task: Mutex<Option<smol::Task<()>>>,
  57. }
  58. impl RefineSession {
  59. pub fn new(p2p: Weak<P2p>) -> RefineSessionPtr {
  60. Arc::new_cyclic(|session| Self {
  61. p2p,
  62. refinery: GreylistRefinery::new(session.clone()),
  63. darklist_clear_task: Mutex::new(None),
  64. })
  65. }
  66. /// Start the refinery and self handshake processes.
  67. pub(crate) async fn start(self: Arc<Self>) {
  68. if let Some(ref hostlist) = self.p2p().settings().read().await.hostlist {
  69. match self.p2p().hosts().container.load_all(hostlist) {
  70. Ok(()) => {
  71. debug!(target: "net::refine_session::start", "Load hosts successful!");
  72. }
  73. Err(e) => {
  74. warn!(target: "net::refine_session::start", "Error loading hosts {}", e);
  75. }
  76. }
  77. }
  78. match self.p2p().hosts().import_blacklist().await {
  79. Ok(()) => {
  80. debug!(target: "net::refine_session::start", "Import blacklist successful!");
  81. }
  82. Err(e) => {
  83. warn!(target: "net::refine_session::start",
  84. "Error importing blacklist from config file {}", e);
  85. }
  86. }
  87. debug!(target: "net::refine_session", "Starting greylist refinery process");
  88. self.refinery.clone().start().await;
  89. // Clear the darklist every 86400 seconds, i.e. once a day.
  90. debug!(target: "net::refine_session", "Starting darklist clear task");
  91. let one_day = 86400;
  92. *self.darklist_clear_task.lock().unwrap() =
  93. Some(self.p2p().executor().spawn(self.clone().clear_darklist(one_day)));
  94. }
  95. /// Sleep for a specified time period, then delete all entries from the darklist.
  96. async fn clear_darklist(self: Arc<Self>, clear_period: u64) {
  97. let hosts = &self.p2p().hosts().container;
  98. loop {
  99. sleep(clear_period).await;
  100. debug!(target: "net::refine_session::clear_darklist",
  101. "{} seconds has passed, clearing darklist...", clear_period);
  102. let mut darklist = hosts.hostlists[HostColor::Dark as usize].write().unwrap();
  103. darklist.clear();
  104. drop(darklist);
  105. }
  106. }
  107. /// Stop the refinery and self handshake processes.
  108. pub(crate) async fn stop(&self) {
  109. debug!(target: "net::refine_session", "Stopping refinery process");
  110. self.refinery.clone().stop().await;
  111. debug!(target: "net::refine_session", "Stopping darklist clear process");
  112. let task = std::mem::take(&mut *self.darklist_clear_task.lock().unwrap());
  113. if task.is_some() {
  114. task.unwrap().cancel().await;
  115. }
  116. if let Some(ref hostlist) = self.p2p().settings().read().await.hostlist {
  117. match self.p2p().hosts().container.save_all(hostlist) {
  118. Ok(()) => {
  119. debug!(target: "net::refine_session::stop()", "Save hosts successful!");
  120. }
  121. Err(e) => {
  122. warn!(target: "net::refine_session::stop()", "Error saving hosts {}", e);
  123. }
  124. }
  125. }
  126. }
  127. /// Globally accessible function to perform a version exchange with a
  128. /// given address. Returns `true` if an address is accessible, false
  129. /// otherwise.
  130. pub async fn handshake_node(self: Arc<Self>, addr: Url, p2p: P2pPtr) -> bool {
  131. let self_ = Arc::downgrade(&self);
  132. let connector = Connector::new(self.p2p().settings(), self_);
  133. debug!(target: "net::refinery::handshake_node()", "Attempting to connect to {}", addr);
  134. match connector.connect(&addr).await {
  135. Ok((url, channel)) => {
  136. debug!(target: "net::refinery::handshake_node()", "Successfully created a channel with {}", url);
  137. // First initialize the version protocol and its Version, Verack subscriptions.
  138. let proto_ver = ProtocolVersion::new(channel.clone(), p2p.settings()).await;
  139. debug!(target: "net::refinery::handshake_node()", "Performing handshake protocols with {}", url);
  140. // Then run the version exchange, store the channel and subscribe to a stop signal.
  141. let handshake =
  142. self.perform_handshake_protocols(proto_ver, channel.clone(), p2p.executor());
  143. debug!(target: "net::refinery::handshake_node()", "Starting channel {}", url);
  144. channel.clone().start(p2p.executor());
  145. // Ensure the channel gets stopped by adding a timeout to the handshake. Otherwise if
  146. // the handshake does not finish channel.stop() will never get called, resulting in
  147. // zombie processes.
  148. let timeout = Timer::after(Duration::from_secs(5));
  149. pin_mut!(timeout);
  150. pin_mut!(handshake);
  151. let result = match select(handshake, timeout).await {
  152. Either::Left((Ok(_), _)) => {
  153. debug!(target: "net::refinery::handshake_node()", "Handshake success!");
  154. true
  155. }
  156. Either::Left((Err(e), _)) => {
  157. debug!(target: "net::refinery::handshake_node()", "Handshake error={}", e);
  158. false
  159. }
  160. Either::Right((_, _)) => {
  161. debug!(target: "net::refinery::handshake_node()", "Handshake timed out");
  162. false
  163. }
  164. };
  165. debug!(target: "net::refinery::handshake_node()", "Stopping channel {}", url);
  166. channel.stop().await;
  167. result
  168. }
  169. Err(e) => {
  170. debug!(target: "net::refinery::handshake_node()", "Failed to connect to {}, ({})", addr, e);
  171. false
  172. }
  173. }
  174. }
  175. }
  176. #[async_trait]
  177. impl Session for RefineSession {
  178. fn p2p(&self) -> P2pPtr {
  179. self.p2p.upgrade().unwrap()
  180. }
  181. fn type_id(&self) -> SessionBitFlag {
  182. SESSION_REFINE
  183. }
  184. }
  185. /// Periodically probes entries in the greylist.
  186. ///
  187. /// Randomly selects a greylist entry and tries to establish a local
  188. /// connection to it using the method handshake_node(), which creates a
  189. /// channel and does a version exchange using `perform_handshake_protocols()`.
  190. ///
  191. /// If successful, the entry is removed from the greylist and added to the
  192. /// whitelist with an updated last_seen timestamp. If non-successful, the
  193. /// entry is removed from the greylist.
  194. pub struct GreylistRefinery {
  195. /// Weak pointer to parent object
  196. session: Weak<RefineSession>,
  197. process: StoppableTaskPtr,
  198. }
  199. impl GreylistRefinery {
  200. pub fn new(session: Weak<RefineSession>) -> Arc<Self> {
  201. Arc::new(Self { session, process: StoppableTask::new() })
  202. }
  203. pub async fn start(self: Arc<Self>) {
  204. let ex = self.p2p().executor();
  205. self.process.clone().start(
  206. async move {
  207. self.run().await;
  208. unreachable!();
  209. },
  210. // Ignore stop handler
  211. |_| async {},
  212. Error::NetworkServiceStopped,
  213. ex,
  214. );
  215. }
  216. pub async fn stop(self: Arc<Self>) {
  217. self.process.stop().await;
  218. }
  219. // Randomly select a peer on the greylist and probe it. This method will remove from the
  220. // greylist and store on the whitelist providing the peer is responsive.
  221. async fn run(self: Arc<Self>) {
  222. let hosts = self.p2p().hosts();
  223. loop {
  224. // Acquire read lock on P2P settings and load necessary settings
  225. let settings = self.p2p().settings().read_arc().await;
  226. let greylist_refinery_interval = settings.greylist_refinery_interval;
  227. let time_with_no_connections = settings.time_with_no_connections;
  228. let allowed_transports = settings.allowed_transports.clone();
  229. drop(settings);
  230. sleep(greylist_refinery_interval).await;
  231. if hosts.container.is_empty(HostColor::Grey) {
  232. debug!(target: "net::refinery",
  233. "Greylist is empty! Cannot start refinery process");
  234. continue
  235. }
  236. // Pause the refinery if we've had zero connections for longer than the configured
  237. // limit.
  238. let offline_limit = Duration::from_secs(time_with_no_connections);
  239. let offline_timer =
  240. { Instant::now().duration_since(*hosts.last_connection.lock().unwrap()) };
  241. if !self.p2p().is_connected() && offline_timer >= offline_limit {
  242. warn!(target: "net::refinery", "No connections for {}s. GreylistRefinery paused.",
  243. offline_timer.as_secs());
  244. // It is neccessary to Free suspended hosts at this point, otherwise these
  245. // hosts cannot be connected to in Outbound Session. Failure to do this could
  246. // result in the refinery being paused forver (since connections could never be
  247. // made).
  248. let suspended_hosts = hosts.suspended();
  249. for host in suspended_hosts {
  250. hosts.unregister(&host);
  251. }
  252. continue
  253. }
  254. // Only attempt to refine peers that match our transports.
  255. match hosts.container.fetch_random_with_schemes(HostColor::Grey, &allowed_transports) {
  256. Some((entry, _)) => {
  257. let url = &entry.0;
  258. if let Err(e) = hosts.try_register(url.clone(), HostState::Refine) {
  259. debug!(target: "net::refinery", "Unable to refine addr={}, err={}",
  260. url.clone(), e);
  261. continue
  262. }
  263. if !self.session().handshake_node(url.clone(), self.p2p().clone()).await {
  264. hosts.container.remove_if_exists(HostColor::Grey, url);
  265. debug!(
  266. target: "net::refinery",
  267. "Peer {} handshake failed. Removed from greylist", url,
  268. );
  269. // Free up this addr for future operations.
  270. hosts.unregister(url);
  271. continue
  272. }
  273. debug!(
  274. target: "net::refinery",
  275. "Peer {} handshake successful. Adding to whitelist", url,
  276. );
  277. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  278. hosts.whitelist_host(url, last_seen).unwrap();
  279. debug!(target: "net::refinery", "GreylistRefinery complete!");
  280. continue
  281. }
  282. None => {
  283. debug!(target: "net::refinery", "No matching greylist entries found. Cannot proceed with refinery");
  284. continue
  285. }
  286. }
  287. }
  288. }
  289. fn session(&self) -> RefineSessionPtr {
  290. self.session.upgrade().unwrap()
  291. }
  292. fn p2p(&self) -> P2pPtr {
  293. self.session().p2p()
  294. }
  295. }