refine_session.rs 12 KB

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