mod.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 std::{
  19. sync::{Arc, Weak},
  20. time::UNIX_EPOCH,
  21. };
  22. use async_trait::async_trait;
  23. use smol::Executor;
  24. use tracing::{debug, error, trace};
  25. use super::{
  26. channel::ChannelPtr,
  27. dnet::{self, dnetev, DnetEvent},
  28. hosts::HostColor,
  29. p2p::P2pPtr,
  30. protocol::ProtocolVersion,
  31. };
  32. use crate::{system::Subscription, util::logger::verbose, Error, Result};
  33. pub mod inbound_session;
  34. pub use inbound_session::{InboundSession, InboundSessionPtr};
  35. pub mod manual_session;
  36. pub use manual_session::{ManualSession, ManualSessionPtr};
  37. pub mod outbound_session;
  38. pub use outbound_session::{OutboundSession, OutboundSessionPtr};
  39. pub mod seedsync_session;
  40. pub use seedsync_session::{SeedSyncSession, SeedSyncSessionPtr};
  41. pub mod refine_session;
  42. pub use refine_session::{RefineSession, RefineSessionPtr};
  43. pub mod direct_session;
  44. pub use direct_session::{DirectSession, DirectSessionPtr};
  45. /// Bitwise selectors for the `protocol_registry`
  46. pub type SessionBitFlag = u32;
  47. pub const SESSION_INBOUND: SessionBitFlag = 0b000001;
  48. pub const SESSION_OUTBOUND: SessionBitFlag = 0b000010;
  49. pub const SESSION_MANUAL: SessionBitFlag = 0b000100;
  50. pub const SESSION_SEED: SessionBitFlag = 0b001000;
  51. pub const SESSION_REFINE: SessionBitFlag = 0b010000;
  52. pub const SESSION_DIRECT: SessionBitFlag = 0b100000;
  53. pub const SESSION_DEFAULT: SessionBitFlag = 0b100111;
  54. pub const SESSION_ALL: SessionBitFlag = 0b111111;
  55. pub type SessionWeakPtr = Weak<dyn Session + Send + Sync + 'static>;
  56. /// Removes channel from the list of connected channels when a stop signal
  57. /// is received.
  58. pub async fn remove_sub_on_stop(
  59. p2p: P2pPtr,
  60. channel: ChannelPtr,
  61. type_id: SessionBitFlag,
  62. stop_sub: Subscription<Error>,
  63. ) {
  64. debug!(target: "net::session::remove_sub_on_stop", "[START]");
  65. let hosts = p2p.hosts();
  66. let addr = channel.address();
  67. stop_sub.receive().await;
  68. debug!(
  69. target: "net::session::remove_sub_on_stop",
  70. "Received stop event. Removing channel {}",
  71. channel.display_address()
  72. );
  73. // Downgrade to greylist if this is a outbound session.
  74. if type_id & (SESSION_OUTBOUND | SESSION_DIRECT) != 0 {
  75. debug!(
  76. target: "net::session::remove_sub_on_stop",
  77. "Downgrading {}",
  78. channel.display_address()
  79. );
  80. // If the host we are downgrading has been moved to blacklist,
  81. // fetch_last_seen(addr) can return None. We simply print an
  82. // error in this case.
  83. match hosts.fetch_last_seen(addr) {
  84. Some(last_seen) => {
  85. if let Err(e) = hosts.move_host(addr, last_seen, HostColor::Grey).await {
  86. error!(target: "net::session::remove_sub_on_stop",
  87. "Failed to move host {} to Greylist! Err={e}", channel.display_address());
  88. }
  89. }
  90. None => {
  91. error!(target: "net::session::remove_sub_on_stop",
  92. "Failed to fetch last seen for {}", channel.display_address());
  93. }
  94. }
  95. }
  96. // For all sessions that are not refine sessions, mark this addr as
  97. // Free. `unregister()` frees up this addr for any future operation. We
  98. // don't call this on refine sessions since the unregister() call
  99. // happens in the refinery directly.
  100. if type_id & SESSION_REFINE == 0 {
  101. if let Err(e) = hosts.unregister(channel.address()) {
  102. error!(target: "net::session::remove_sub_on_stop", "Error while unregistering addr={}, err={e}", channel.display_address());
  103. }
  104. }
  105. if type_id & SESSION_DIRECT != 0 {
  106. dnetev!(p2p.session_direct(), DirectDisconnected, {
  107. connect_addr: channel.info.connect_addr.clone(),
  108. err: "Channel stopped".to_string()
  109. });
  110. verbose!(
  111. target: "net::direct_session",
  112. "[P2P] Direct outbound disconnected [{}]",
  113. channel.display_address()
  114. );
  115. }
  116. if !p2p.is_connected() {
  117. hosts.disconnect_publisher.notify(Error::NetworkNotConnected).await;
  118. }
  119. debug!(target: "net::session::remove_sub_on_stop", "[END]");
  120. }
  121. /// Session trait. Defines methods that are used across sessions.
  122. /// Implements registering the channel and initializing the channel by
  123. /// performing a network handshake.
  124. #[async_trait]
  125. pub trait Session: Sync {
  126. /// Registers a new channel with the session.
  127. /// Performs a network handshake and starts the channel.
  128. /// If we need to pass `Self` as an `Arc` we can do so like this:
  129. /// ```
  130. /// pub trait MyTrait: Send + Sync {
  131. /// async fn foo(&self, self_: Arc<dyn MyTrait>) {}
  132. /// }
  133. /// ```
  134. async fn register_channel(
  135. &self,
  136. channel: ChannelPtr,
  137. executor: Arc<Executor<'_>>,
  138. ) -> Result<()> {
  139. trace!(target: "net::session::register_channel", "[START]");
  140. // Protocols should all be initialized but not started.
  141. // We do this so that the protocols can begin receiving and buffering
  142. // messages while the handshake protocol is ongoing. They are currently
  143. // in sleep mode.
  144. let p2p = self.p2p();
  145. let protocols =
  146. p2p.protocol_registry().attach(self.type_id(), channel.clone(), p2p.clone()).await;
  147. // Perform the handshake protocol
  148. let protocol_version = ProtocolVersion::new(channel.clone(), p2p.settings().clone()).await;
  149. debug!(
  150. target: "net::session::register_channel",
  151. "Performing handshake protocols {}", channel.clone().display_address(),
  152. );
  153. let handshake_task =
  154. self.perform_handshake_protocols(protocol_version, channel.clone(), executor.clone());
  155. // Switch on the channel
  156. channel.clone().start(executor.clone());
  157. // Wait for handshake to finish.
  158. match handshake_task.await {
  159. Ok(()) => {
  160. debug!(target: "net::session::register_channel",
  161. "Handshake successful {}", channel.clone().display_address());
  162. }
  163. Err(e) => {
  164. debug!(target: "net::session::register_channel",
  165. "Handshake error {e} {}", channel.clone().display_address());
  166. return Err(e)
  167. }
  168. }
  169. // Now the channel is ready
  170. debug!(target: "net::session::register_channel", "Session handshake complete");
  171. debug!(target: "net::session::register_channel", "Activating remaining protocols");
  172. // Now start all the protocols. They are responsible for managing their own
  173. // lifetimes and correctly selfdestructing when the channel ends.
  174. for protocol in protocols {
  175. protocol.start(executor.clone()).await?;
  176. }
  177. trace!(target: "net::session::register_channel", "[END]");
  178. Ok(())
  179. }
  180. /// Performs network handshake to initialize channel. Adds the channel to
  181. /// the list of connected channels, and prepares to remove the channel when
  182. /// a stop signal is received.
  183. async fn perform_handshake_protocols(
  184. &self,
  185. protocol_version: Arc<ProtocolVersion>,
  186. channel: ChannelPtr,
  187. executor: Arc<Executor<'_>>,
  188. ) -> Result<()> {
  189. // Subscribe to stop events
  190. let stop_sub = channel.clone().subscribe_stop().await?;
  191. // Perform handshake
  192. match protocol_version.run(executor.clone()).await {
  193. Ok(()) => {
  194. // Upgrade to goldlist if this is a outbound session.
  195. if self.type_id() & (SESSION_OUTBOUND | SESSION_DIRECT) != 0 {
  196. debug!(
  197. target: "net::session::perform_handshake_protocols",
  198. "Upgrading {}", channel.display_address(),
  199. );
  200. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  201. self.p2p()
  202. .hosts()
  203. .move_host(channel.address(), last_seen, HostColor::Gold)
  204. .await?;
  205. }
  206. // Attempt to add channel to registry
  207. self.p2p().hosts().register_channel(channel.clone()).await;
  208. // Subscribe to stop, so we can remove from registry
  209. executor
  210. .spawn(remove_sub_on_stop(self.p2p(), channel, self.type_id(), stop_sub))
  211. .detach();
  212. // Channel is ready for use
  213. Ok(())
  214. }
  215. Err(e) => return Err(e),
  216. }
  217. }
  218. /// Returns a pointer to the p2p network interface
  219. fn p2p(&self) -> P2pPtr;
  220. /// Return the session bit flag for the session type
  221. fn type_id(&self) -> SessionBitFlag;
  222. /// Reload settings for this session
  223. async fn reload(self: Arc<Self>);
  224. }