inbound_session.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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. //! Inbound connections session. Manages the creation of inbound sessions.
  19. //! Used to create an inbound session and start and stop the session.
  20. //!
  21. //! Class consists of 3 pointers: a weak pointer to the p2p parent class,
  22. //! an acceptor pointer, and a stoppable task pointer. Using a weak pointer
  23. //! to P2P allows us to avoid circular dependencies.
  24. use std::sync::{Arc, Weak};
  25. use async_trait::async_trait;
  26. use smol::{lock::Mutex, Executor};
  27. use tracing::{debug, error, warn};
  28. use url::Url;
  29. use super::{
  30. super::{
  31. acceptor::{Acceptor, AcceptorPtr},
  32. channel::ChannelPtr,
  33. dnet::{self, dnetev, DnetEvent},
  34. p2p::{P2p, P2pPtr},
  35. },
  36. Session, SessionBitFlag, SESSION_INBOUND,
  37. };
  38. use crate::{
  39. system::{StoppableTask, StoppableTaskPtr, Subscription},
  40. util::logger::verbose,
  41. Error, Result,
  42. };
  43. pub type InboundSessionPtr = Arc<InboundSession>;
  44. /// Defines inbound connections session
  45. pub struct InboundSession {
  46. pub(in crate::net) p2p: Weak<P2p>,
  47. acceptors: Mutex<Vec<AcceptorPtr>>,
  48. accept_tasks: Mutex<Vec<StoppableTaskPtr>>,
  49. }
  50. impl InboundSession {
  51. /// Create a new inbound session
  52. pub fn new(p2p: Weak<P2p>) -> InboundSessionPtr {
  53. Arc::new(Self {
  54. p2p,
  55. acceptors: Mutex::new(Vec::new()),
  56. accept_tasks: Mutex::new(Vec::new()),
  57. })
  58. }
  59. /// Starts the inbound session. Begins by accepting connections and fails
  60. /// if the addresses are not configured. Then runs the channel subscription
  61. /// loop.
  62. pub async fn start(self: Arc<Self>) -> Result<()> {
  63. let inbound_addrs = self.p2p().settings().read().await.inbound_addrs.clone();
  64. if inbound_addrs.is_empty() {
  65. verbose!(target: "net::inbound_session", "[P2P] Not configured for inbound connections.");
  66. return Ok(())
  67. }
  68. let ex = self.p2p().executor();
  69. // Activate mutex lock on accept tasks.
  70. let mut accept_tasks = self.accept_tasks.lock().await;
  71. for (index, accept_addr) in inbound_addrs.iter().enumerate() {
  72. // First initialize an Acceptor and its Subscriber.
  73. let parent = Arc::downgrade(&self);
  74. let acceptor = Acceptor::new(parent);
  75. // Now start the Subscriber. The Subscriber will return a Channel once it has been
  76. // prepared by the Acceptor.
  77. let channel_sub = acceptor.clone().subscribe().await;
  78. // Then start listening for a Channel returned by the Subscriber. Call setup_channel()
  79. // to register the Channel when it has been received.
  80. let task = StoppableTask::new();
  81. task.clone().start(
  82. self.clone().channel_sub_loop(channel_sub, index, ex.clone()),
  83. // Ignore stop handler
  84. |_| async {},
  85. Error::NetworkServiceStopped,
  86. ex.clone(),
  87. );
  88. accept_tasks.push(task);
  89. // Finally, run the Acceptor to start accepting inbound connections. Only when
  90. // the Subscriber has been set up can we safely do this.
  91. self.clone()
  92. .start_accept_session(index, accept_addr.clone(), acceptor, ex.clone())
  93. .await?;
  94. }
  95. Ok(())
  96. }
  97. /// Stops the inbound session.
  98. pub async fn stop(&self) {
  99. if self.p2p().settings().read().await.inbound_addrs.is_empty() {
  100. verbose!(target: "net::inbound_session", "[P2P] Stopping inbound session.");
  101. return
  102. }
  103. let acceptors = &*self.acceptors.lock().await;
  104. for acceptor in acceptors {
  105. acceptor.stop().await;
  106. }
  107. let accept_tasks = &*self.accept_tasks.lock().await;
  108. for accept_task in accept_tasks {
  109. accept_task.stop().await;
  110. }
  111. }
  112. /// Start accepting connections for inbound session.
  113. async fn start_accept_session(
  114. self: Arc<Self>,
  115. index: usize,
  116. accept_addr: Url,
  117. acceptor: AcceptorPtr,
  118. ex: Arc<Executor<'_>>,
  119. ) -> Result<()> {
  120. verbose!(target: "net::inbound_session", "[P2P] Starting Inbound session #{index} on {accept_addr}");
  121. // Start listener
  122. let result = acceptor.clone().start(accept_addr, ex).await;
  123. if let Err(e) = &result {
  124. error!(target: "net::inbound_session", "[P2P] Error starting listener #{index}: {e}");
  125. acceptor.stop().await;
  126. } else {
  127. self.acceptors.lock().await.push(acceptor);
  128. }
  129. result
  130. }
  131. /// Wait for all new channels created by the acceptor and call setup_channel() on them.
  132. async fn channel_sub_loop(
  133. self: Arc<Self>,
  134. channel_sub: Subscription<Result<ChannelPtr>>,
  135. index: usize,
  136. ex: Arc<Executor<'_>>,
  137. ) -> Result<()> {
  138. loop {
  139. let channel = channel_sub.receive().await?;
  140. // Spawn a detached task to process the channel.
  141. // This will just perform the channel setup then exit.
  142. ex.spawn(self.clone().setup_channel(index, channel, ex.clone())).detach();
  143. }
  144. }
  145. /// Registers the channel. First performs a network handshake and starts the channel.
  146. /// Then starts sending keep-alive and address messages across the channel.
  147. async fn setup_channel(
  148. self: Arc<Self>,
  149. index: usize,
  150. channel: ChannelPtr,
  151. ex: Arc<Executor<'_>>,
  152. ) {
  153. verbose!(
  154. target: "net::inbound_session::setup_channel",
  155. "[P2P] Connected Inbound #{index} [{}]", channel.display_address()
  156. );
  157. dnetev!(self, InboundConnected, {
  158. addr: channel.info.connect_addr.clone(),
  159. channel_id: channel.info.id,
  160. });
  161. let stop_sub = channel.subscribe_stop().await;
  162. match self.register_channel(channel.clone(), ex.clone()).await {
  163. Ok(()) => {
  164. if let Ok(stop_sub) = stop_sub {
  165. // Wait for a stop signal, then cleanup.
  166. stop_sub.receive().await;
  167. debug!(
  168. target: "net::inbound_session::setup_channel",
  169. "Received stop_sub, channel removed from P2P",
  170. );
  171. }
  172. }
  173. Err(e) => {
  174. warn!(
  175. target: "net::inbound_session::setup_channel",
  176. "Channel setup failed! Err={e}"
  177. );
  178. }
  179. }
  180. dnetev!(self, InboundDisconnected, {
  181. addr: channel.info.connect_addr.clone(),
  182. channel_id: channel.info.id,
  183. });
  184. }
  185. }
  186. #[async_trait]
  187. impl Session for InboundSession {
  188. fn p2p(&self) -> P2pPtr {
  189. self.p2p.upgrade().unwrap()
  190. }
  191. fn type_id(&self) -> SessionBitFlag {
  192. SESSION_INBOUND
  193. }
  194. async fn reload(self: Arc<Self>) {}
  195. }