mod.rs 8.8 KB

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