mod.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. use std::sync::{Arc, Weak};
  19. use async_trait::async_trait;
  20. use log::{debug, warn};
  21. use smol::Executor;
  22. use super::{channel::ChannelPtr, p2p::P2pPtr, protocol::ProtocolVersion};
  23. use crate::Result;
  24. pub mod inbound_session;
  25. pub use inbound_session::{InboundSession, InboundSessionPtr};
  26. pub mod manual_session;
  27. pub use manual_session::{ManualSession, ManualSessionPtr};
  28. pub mod outbound_session;
  29. pub use outbound_session::{OutboundSession, OutboundSessionPtr};
  30. pub mod seedsync_session;
  31. pub use seedsync_session::{SeedSyncSession, SeedSyncSessionPtr};
  32. /// Bitwise selectors for the `protocol_registry`
  33. pub type SessionBitFlag = u32;
  34. pub const SESSION_INBOUND: SessionBitFlag = 0b0001;
  35. pub const SESSION_OUTBOUND: SessionBitFlag = 0b0010;
  36. pub const SESSION_MANUAL: SessionBitFlag = 0b0100;
  37. pub const SESSION_SEED: SessionBitFlag = 0b1000;
  38. pub const SESSION_ALL: SessionBitFlag = 0b1111;
  39. pub type SessionWeakPtr = Weak<dyn Session + Send + Sync + 'static>;
  40. /// Removes channel from the list of connected channels when a stop signal
  41. /// is received.
  42. pub async fn remove_sub_on_stop(p2p: P2pPtr, channel: ChannelPtr) {
  43. debug!(target: "net::session::remove_sub_on_stop()", "[START]");
  44. // Subscribe to stop events
  45. let stop_sub = channel.clone().subscribe_stop().await;
  46. if let Ok(stop_sub) = stop_sub {
  47. // Wait for a stop event
  48. stop_sub.receive().await;
  49. }
  50. debug!(
  51. target: "net::session::remove_sub_on_stop()",
  52. "Received stop event. Removing channel {}", channel.address(),
  53. );
  54. // Remove channel from p2p
  55. p2p.hosts().unregister(channel.address()).await;
  56. debug!(target: "net::session::remove_sub_on_stop()", "[END]");
  57. }
  58. /// Session trait. Defines methods that are used across sessions.
  59. /// Implements registering the channel and initializing the channel by
  60. /// performing a network handshake.
  61. #[async_trait]
  62. pub trait Session: Sync {
  63. /// Registers a new channel with the session.
  64. /// Performs a network handshake and starts the channel.
  65. /// If we need to pass `Self` as an `Arc` we can do so like this:
  66. /// ```
  67. /// pub trait MyTrait: Send + Sync {
  68. /// async fn foo(&self, self_: Arc<dyn MyTrait>) {}
  69. /// }
  70. /// ```
  71. async fn register_channel(
  72. &self,
  73. channel: ChannelPtr,
  74. executor: Arc<Executor<'_>>,
  75. ) -> Result<()> {
  76. debug!(target: "net::session::register_channel()", "[START]");
  77. // Protocols should all be initialized but not started.
  78. // We do this so that the protocols can begin receiving and buffering
  79. // messages while the handshake protocol is ongoing. They are currently
  80. // in sleep mode.
  81. let p2p = self.p2p();
  82. let protocols =
  83. p2p.protocol_registry().attach(self.type_id(), channel.clone(), p2p.clone()).await;
  84. // Perform the handshake protocol
  85. let protocol_version = ProtocolVersion::new(channel.clone(), p2p.settings().clone()).await;
  86. debug!(target: "net::session::register_channel()",
  87. "Performing handshake protocols {}", channel.clone().address());
  88. let handshake_task =
  89. self.perform_handshake_protocols(protocol_version, channel.clone(), executor.clone());
  90. // Switch on the channel
  91. channel.clone().start(executor.clone());
  92. // Wait for handshake to finish.
  93. // If the handshake returns an error, remove this host from all hostlists.
  94. match handshake_task.await {
  95. Ok(()) => {
  96. debug!(target: "net::session::register_channel()",
  97. "Handshake successful {}", channel.clone().address());
  98. }
  99. Err(e) => {
  100. debug!(target: "net::session::register_channel()",
  101. "Handshake error {} {}", e, channel.clone().address());
  102. }
  103. }
  104. // Now the channel is ready
  105. debug!(target: "net::session::register_channel()", "Session handshake complete");
  106. debug!(target: "net::session::register_channel()", "Activating remaining protocols");
  107. // Now start all the protocols. They are responsible for managing their own
  108. // lifetimes and correctly selfdestructing when the channel ends.
  109. for protocol in protocols {
  110. protocol.start(executor.clone()).await?;
  111. }
  112. debug!(target: "net::session::register_channel()", "[END]");
  113. Ok(())
  114. }
  115. /// Performs network handshake to initialize channel. Adds the channel to
  116. /// the list of connected channels, and prepares to remove the channel when
  117. /// a stop signal is received.
  118. async fn perform_handshake_protocols(
  119. &self,
  120. protocol_version: Arc<ProtocolVersion>,
  121. channel: ChannelPtr,
  122. executor: Arc<Executor<'_>>,
  123. ) -> Result<()> {
  124. // Perform handshake
  125. protocol_version.run(executor.clone()).await?;
  126. // Attempt to add channel to registry
  127. if let Err(e) = self.p2p().hosts().register_channel(channel.clone()).await {
  128. warn!(target: "net::session::perform_handshake_protocols()",
  129. "Couldn't add channel {} to registry! {}", channel.address(), e);
  130. return Err(e)
  131. }
  132. // Subscribe to stop, so we can remove from registry
  133. executor.spawn(remove_sub_on_stop(self.p2p(), channel)).detach();
  134. // Channel is ready for use
  135. Ok(())
  136. }
  137. /// Returns a pointer to the p2p network interface
  138. fn p2p(&self) -> P2pPtr;
  139. /// Return the session bit flag for the session type
  140. fn type_id(&self) -> SessionBitFlag;
  141. }