inbound_session.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. dnet::{self, dnetev, DnetEvent},
  34. p2p::{P2p, P2pPtr},
  35. },
  36. Session, SessionBitFlag, SESSION_INBOUND,
  37. };
  38. use crate::{
  39. system::{LazyWeak, StoppableTask, StoppableTaskPtr},
  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. self.clone().start_accept_session(index, accept_addr.clone(), ex.clone()).await?;
  71. let task = StoppableTask::new();
  72. task.clone().start(
  73. self.clone().channel_sub_loop(index, ex.clone()),
  74. // Ignore stop handler
  75. |_| async {},
  76. Error::NetworkServiceStopped,
  77. ex.clone(),
  78. );
  79. accept_tasks.push(task);
  80. }
  81. Ok(())
  82. }
  83. /// Stops the inbound session.
  84. pub async fn stop(&self) {
  85. let acceptors = &*self.acceptors.lock().await;
  86. for acceptor in acceptors {
  87. acceptor.stop().await;
  88. }
  89. let accept_tasks = &*self.accept_tasks.lock().await;
  90. for accept_task in accept_tasks {
  91. accept_task.stop().await;
  92. }
  93. }
  94. /// Start accepting connections for inbound session.
  95. async fn start_accept_session(
  96. self: Arc<Self>,
  97. index: usize,
  98. accept_addr: Url,
  99. ex: Arc<Executor<'_>>,
  100. ) -> Result<()> {
  101. info!(target: "net::inbound_session", "[P2P] Starting Inbound session #{} on {}", index, accept_addr);
  102. // Generate a new acceptor for this inbound session
  103. let parent = Arc::downgrade(&self);
  104. let acceptor = Acceptor::new(parent);
  105. // Start listener
  106. let result = acceptor.clone().start(accept_addr, ex).await;
  107. if let Err(e) = &result {
  108. error!(target: "net::inbound_session", "[P2P] Error starting listener #{}: {}", index, e);
  109. acceptor.stop().await;
  110. } else {
  111. self.acceptors.lock().await.push(acceptor);
  112. }
  113. result
  114. }
  115. /// Wait for all new channels created by the acceptor and call setup_channel() on them.
  116. async fn channel_sub_loop(self: Arc<Self>, index: usize, ex: Arc<Executor<'_>>) -> Result<()> {
  117. let channel_sub = self.acceptors.lock().await[index].clone().subscribe().await;
  118. loop {
  119. let channel = channel_sub.receive().await?;
  120. // Spawn a detached task to process the channel.
  121. // This will just perform the channel setup then exit.
  122. ex.spawn(self.clone().setup_channel(index, channel, ex.clone())).detach();
  123. }
  124. }
  125. /// Registers the channel. First performs a network handshake and starts the channel.
  126. /// Then starts sending keep-alive and address messages across the channel.
  127. async fn setup_channel(
  128. self: Arc<Self>,
  129. index: usize,
  130. channel: ChannelPtr,
  131. ex: Arc<Executor<'_>>,
  132. ) -> Result<()> {
  133. info!(
  134. target: "net::inbound_session::setup_channel",
  135. "[P2P] Connected Inbound #{} [{}]", index, channel.address(),
  136. );
  137. dnetev!(self, InboundConnected, {
  138. addr: channel.info.addr.clone(),
  139. channel_id: channel.info.id,
  140. });
  141. let stop_sub = channel.subscribe_stop().await?;
  142. self.register_channel(channel.clone(), ex.clone()).await?;
  143. stop_sub.receive().await;
  144. self.p2p().remove(channel.clone()).await;
  145. // Downgrade this host to greylist if it's on the whitelist or anchorlist.
  146. self.downgrade_host(&channel.info.addr).await;
  147. debug!(
  148. target: "net::inbound_session::setup_channel()",
  149. "Received stop_sub, channel removed from P2P",
  150. );
  151. dnetev!(self, InboundDisconnected, {
  152. addr: channel.info.addr.clone(),
  153. channel_id: channel.info.id,
  154. });
  155. Ok(())
  156. }
  157. }
  158. #[async_trait]
  159. impl Session for InboundSession {
  160. fn p2p(&self) -> P2pPtr {
  161. self.p2p.upgrade()
  162. }
  163. fn type_id(&self) -> SessionBitFlag {
  164. SESSION_INBOUND
  165. }
  166. }