inbound_session.rs 7.0 KB

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