mod.rs 8.6 KB

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