refine_session.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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, 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. }
  56. impl RefineSession {
  57. pub fn new(p2p: Weak<P2p>) -> RefineSessionPtr {
  58. Arc::new_cyclic(|session| Self { p2p, refinery: GreylistRefinery::new(session.clone()) })
  59. }
  60. /// Start the refinery and self handshake processes.
  61. pub(crate) async fn start(self: Arc<Self>) {
  62. if let Some(ref hostlist) = self.p2p().settings().read().await.hostlist {
  63. match self.p2p().hosts().container.load_all(hostlist) {
  64. Ok(()) => {
  65. debug!(target: "net::refine_session::start", "Load hosts successful!");
  66. }
  67. Err(e) => {
  68. warn!(target: "net::refine_session::start", "Error loading hosts {}", e);
  69. }
  70. }
  71. }
  72. match self.p2p().hosts().import_blacklist().await {
  73. Ok(()) => {
  74. debug!(target: "net::refine_session::start", "Import blacklist successful!");
  75. }
  76. Err(e) => {
  77. warn!(target: "net::refine_session::start",
  78. "Error importing blacklist from config file {}", e);
  79. }
  80. }
  81. debug!(target: "net::refine_session", "Starting greylist refinery process");
  82. self.refinery.clone().start().await;
  83. }
  84. /// Stop the refinery and self handshake processes.
  85. pub(crate) async fn stop(&self) {
  86. debug!(target: "net::refine_session", "Stopping refinery process");
  87. self.refinery.clone().stop().await;
  88. if let Some(ref hostlist) = self.p2p().settings().read().await.hostlist {
  89. match self.p2p().hosts().container.save_all(hostlist) {
  90. Ok(()) => {
  91. debug!(target: "net::refine_session::stop()", "Save hosts successful!");
  92. }
  93. Err(e) => {
  94. warn!(target: "net::refine_session::stop()", "Error saving hosts {}", e);
  95. }
  96. }
  97. }
  98. }
  99. /// Globally accessible function to perform a version exchange with a
  100. /// given address. Returns `true` if an address is accessible, false
  101. /// otherwise.
  102. pub async fn handshake_node(self: Arc<Self>, addr: Url, p2p: P2pPtr) -> bool {
  103. let self_ = Arc::downgrade(&self);
  104. let connector = Connector::new(self.p2p().settings(), self_);
  105. debug!(target: "net::refinery::handshake_node()", "Attempting to connect to {}", addr);
  106. match connector.connect(&addr).await {
  107. Ok((url, channel)) => {
  108. debug!(target: "net::refinery::handshake_node()", "Successfully created a channel with {}", url);
  109. // First initialize the version protocol and its Version, Verack subscriptions.
  110. let proto_ver = ProtocolVersion::new(channel.clone(), p2p.settings()).await;
  111. debug!(target: "net::refinery::handshake_node()", "Performing handshake protocols with {}", url);
  112. // Then run the version exchange, store the channel and subscribe to a stop signal.
  113. let handshake =
  114. self.perform_handshake_protocols(proto_ver, channel.clone(), p2p.executor());
  115. debug!(target: "net::refinery::handshake_node()", "Starting channel {}", url);
  116. channel.clone().start(p2p.executor());
  117. // Ensure the channel gets stopped by adding a timeout to the handshake. Otherwise if
  118. // the handshake does not finish channel.stop() will never get called, resulting in
  119. // zombie processes.
  120. let timeout = Timer::after(Duration::from_secs(5));
  121. pin_mut!(timeout);
  122. pin_mut!(handshake);
  123. let result = match select(handshake, timeout).await {
  124. Either::Left((Ok(_), _)) => {
  125. debug!(target: "net::refinery::handshake_node()", "Handshake success!");
  126. true
  127. }
  128. Either::Left((Err(e), _)) => {
  129. debug!(target: "net::refinery::handshake_node()", "Handshake error={}", e);
  130. false
  131. }
  132. Either::Right((_, _)) => {
  133. debug!(target: "net::refinery::handshake_node()", "Handshake timed out");
  134. false
  135. }
  136. };
  137. debug!(target: "net::refinery::handshake_node()", "Stopping channel {}", url);
  138. channel.stop().await;
  139. result
  140. }
  141. Err(e) => {
  142. debug!(target: "net::refinery::handshake_node()", "Failed to connect to {}, ({})", addr, e);
  143. false
  144. }
  145. }
  146. }
  147. }
  148. #[async_trait]
  149. impl Session for RefineSession {
  150. fn p2p(&self) -> P2pPtr {
  151. self.p2p.upgrade().unwrap()
  152. }
  153. fn type_id(&self) -> SessionBitFlag {
  154. SESSION_REFINE
  155. }
  156. }
  157. /// Periodically probes entries in the greylist.
  158. ///
  159. /// Randomly selects a greylist entry and tries to establish a local
  160. /// connection to it using the method handshake_node(), which creates a
  161. /// channel and does a version exchange using `perform_handshake_protocols()`.
  162. ///
  163. /// If successful, the entry is removed from the greylist and added to the
  164. /// whitelist with an updated last_seen timestamp. If non-successful, the
  165. /// entry is removed from the greylist.
  166. pub struct GreylistRefinery {
  167. /// Weak pointer to parent object
  168. session: Weak<RefineSession>,
  169. process: StoppableTaskPtr,
  170. }
  171. impl GreylistRefinery {
  172. pub fn new(session: Weak<RefineSession>) -> Arc<Self> {
  173. Arc::new(Self { session, process: StoppableTask::new() })
  174. }
  175. pub async fn start(self: Arc<Self>) {
  176. let ex = self.p2p().executor();
  177. self.process.clone().start(
  178. async move {
  179. self.run().await;
  180. unreachable!();
  181. },
  182. // Ignore stop handler
  183. |_| async {},
  184. Error::NetworkServiceStopped,
  185. ex,
  186. );
  187. }
  188. pub async fn stop(self: Arc<Self>) {
  189. self.process.stop().await;
  190. }
  191. // Randomly select a peer on the greylist and probe it. This method will remove from the
  192. // greylist and store on the whitelist providing the peer is responsive.
  193. async fn run(self: Arc<Self>) {
  194. let hosts = self.p2p().hosts();
  195. loop {
  196. // Acquire read lock on P2P settings and load necessary settings
  197. let settings = self.p2p().settings().read_arc().await;
  198. let greylist_refinery_interval = settings.greylist_refinery_interval;
  199. let time_with_no_connections = settings.time_with_no_connections;
  200. let allowed_transports = settings.allowed_transports.clone();
  201. drop(settings);
  202. sleep(greylist_refinery_interval).await;
  203. if hosts.container.is_empty(HostColor::Grey) {
  204. debug!(target: "net::refinery",
  205. "Greylist is empty! Cannot start refinery process");
  206. continue
  207. }
  208. // Pause the refinery if we've had zero connections for longer than the configured
  209. // limit.
  210. let offline_limit = Duration::from_secs(time_with_no_connections);
  211. let offline_timer =
  212. { Instant::now().duration_since(*hosts.last_connection.lock().unwrap()) };
  213. if !self.p2p().is_connected() && offline_timer >= offline_limit {
  214. warn!(target: "net::refinery", "No connections for {}s. GreylistRefinery paused.",
  215. offline_timer.as_secs());
  216. // It is neccessary to Free suspended hosts at this point, otherwise these
  217. // hosts cannot be connected to in Outbound Session. Failure to do this could
  218. // result in the refinery being paused forver (since connections could never be
  219. // made).
  220. let suspended_hosts = hosts.suspended();
  221. for host in suspended_hosts {
  222. hosts.unregister(&host);
  223. }
  224. continue
  225. }
  226. // Only attempt to refine peers that match our transports.
  227. match hosts.container.fetch_random_with_schemes(HostColor::Grey, &allowed_transports) {
  228. Some((entry, _)) => {
  229. let url = &entry.0;
  230. if let Err(e) = hosts.try_register(url.clone(), HostState::Refine) {
  231. debug!(target: "net::refinery", "Unable to refine addr={}, err={}",
  232. url.clone(), e);
  233. continue
  234. }
  235. if !self.session().handshake_node(url.clone(), self.p2p().clone()).await {
  236. hosts.container.remove_if_exists(HostColor::Grey, url);
  237. debug!(
  238. target: "net::refinery",
  239. "Peer {} handshake failed. Removed from greylist", url,
  240. );
  241. // Free up this addr for future operations.
  242. hosts.unregister(url);
  243. continue
  244. }
  245. debug!(
  246. target: "net::refinery",
  247. "Peer {} handshake successful. Adding to whitelist", url,
  248. );
  249. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  250. hosts.whitelist_host(url, last_seen).unwrap();
  251. debug!(target: "net::refinery", "GreylistRefinery complete!");
  252. continue
  253. }
  254. None => {
  255. debug!(target: "net::refinery", "No matching greylist entries found. Cannot proceed with refinery");
  256. continue
  257. }
  258. }
  259. }
  260. }
  261. fn session(&self) -> RefineSessionPtr {
  262. self.session.upgrade().unwrap()
  263. }
  264. fn p2p(&self) -> P2pPtr {
  265. self.session().p2p()
  266. }
  267. }