inbound_session.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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. p2p::{P2p, P2pPtr},
  34. },
  35. Session, SessionBitFlag, SESSION_INBOUND,
  36. };
  37. use crate::{
  38. system::{LazyWeak, StoppableTask, StoppableTaskPtr},
  39. Error, Result,
  40. };
  41. pub type InboundSessionPtr = Arc<InboundSession>;
  42. /// Defines inbound connections session
  43. pub struct InboundSession {
  44. pub(in crate::net) p2p: LazyWeak<P2p>,
  45. acceptors: Mutex<Vec<AcceptorPtr>>,
  46. accept_tasks: Mutex<Vec<StoppableTaskPtr>>,
  47. }
  48. impl InboundSession {
  49. /// Create a new inbound session
  50. pub fn new() -> InboundSessionPtr {
  51. Arc::new(Self {
  52. p2p: LazyWeak::new(),
  53. acceptors: Mutex::new(Vec::new()),
  54. accept_tasks: Mutex::new(Vec::new()),
  55. })
  56. }
  57. /// Starts the inbound session. Begins by accepting connections and fails
  58. /// if the addresses are not configured. Then runs the channel subscription
  59. /// loop.
  60. pub async fn start(self: Arc<Self>) -> Result<()> {
  61. if self.p2p().settings().inbound_addrs.is_empty() {
  62. info!(target: "net::inbound_session", "[P2P] Not configured for inbound connections.");
  63. return Ok(())
  64. }
  65. let ex = self.p2p().executor();
  66. // Activate mutex lock on accept tasks.
  67. let mut accept_tasks = self.accept_tasks.lock().await;
  68. for (index, accept_addr) in self.p2p().settings().inbound_addrs.iter().enumerate() {
  69. self.clone().start_accept_session(index, accept_addr.clone(), ex.clone()).await?;
  70. let task = StoppableTask::new();
  71. task.clone().start(
  72. self.clone().channel_sub_loop(index, ex.clone()),
  73. // Ignore stop handler
  74. |_| async {},
  75. Error::NetworkServiceStopped,
  76. ex.clone(),
  77. );
  78. accept_tasks.push(task);
  79. }
  80. Ok(())
  81. }
  82. /// Stops the inbound session.
  83. pub async fn stop(&self) {
  84. let acceptors = &*self.acceptors.lock().await;
  85. for acceptor in acceptors {
  86. acceptor.stop().await;
  87. }
  88. let accept_tasks = &*self.accept_tasks.lock().await;
  89. for accept_task in accept_tasks {
  90. accept_task.stop().await;
  91. }
  92. }
  93. /// Start accepting connections for inbound session.
  94. async fn start_accept_session(
  95. self: Arc<Self>,
  96. index: usize,
  97. accept_addr: Url,
  98. ex: Arc<Executor<'_>>,
  99. ) -> Result<()> {
  100. info!(target: "net::inbound_session", "[P2P] Starting Inbound session #{} on {}", index, accept_addr);
  101. // Generate a new acceptor for this inbound session
  102. let parent = Arc::downgrade(&self);
  103. let acceptor = Acceptor::new(parent);
  104. // Start listener
  105. let result = acceptor.clone().start(accept_addr, ex).await;
  106. if let Err(e) = &result {
  107. error!(target: "net::inbound_session", "[P2P] Error starting listener #{}: {}", index, e);
  108. acceptor.stop().await;
  109. } else {
  110. self.acceptors.lock().await.push(acceptor);
  111. }
  112. result
  113. }
  114. /// Wait for all new channels created by the acceptor and call setup_channel() on them.
  115. async fn channel_sub_loop(self: Arc<Self>, index: usize, ex: Arc<Executor<'_>>) -> Result<()> {
  116. let channel_sub = self.acceptors.lock().await[index].clone().subscribe().await;
  117. loop {
  118. let channel = channel_sub.receive().await?;
  119. // Spawn a detached task to process the channel.
  120. // This will just perform the channel setup then exit.
  121. ex.spawn(self.clone().setup_channel(index, channel, ex.clone())).detach();
  122. }
  123. }
  124. /// Registers the channel. First performs a network handshake and starts the channel.
  125. /// Then starts sending keep-alive and address messages across the channel.
  126. async fn setup_channel(
  127. self: Arc<Self>,
  128. index: usize,
  129. channel: ChannelPtr,
  130. ex: Arc<Executor<'_>>,
  131. ) -> Result<()> {
  132. info!(
  133. target: "net::inbound_session::setup_channel",
  134. "[P2P] Connected Inbound #{} [{}]", index, channel.address(),
  135. );
  136. let stop_sub = channel.subscribe_stop().await?;
  137. self.register_channel(channel.clone(), ex.clone()).await?;
  138. stop_sub.receive().await;
  139. debug!(
  140. target: "net::inbound_session::setup_channel()",
  141. "Received stop_sub, removing channel from P2P",
  142. );
  143. self.p2p().remove(channel).await;
  144. Ok(())
  145. }
  146. }
  147. #[async_trait]
  148. impl Session for InboundSession {
  149. fn p2p(&self) -> P2pPtr {
  150. self.p2p.upgrade()
  151. }
  152. fn type_id(&self) -> SessionBitFlag {
  153. SESSION_INBOUND
  154. }
  155. }