inbound_session.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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::collections::HashMap;
  25. use async_std::sync::{Arc, Mutex, Weak};
  26. use async_trait::async_trait;
  27. use log::{error, info};
  28. use smol::Executor;
  29. use url::Url;
  30. use super::{
  31. super::{
  32. acceptor::{Acceptor, AcceptorPtr},
  33. channel::{ChannelInfo, ChannelPtr},
  34. p2p::{DnetInfo, P2p, P2pPtr},
  35. },
  36. Session, SessionBitFlag, SESSION_INBOUND,
  37. };
  38. use crate::{
  39. system::{StoppableTask, StoppableTaskPtr},
  40. Error, Result,
  41. };
  42. pub type InboundSessionPtr = Arc<InboundSession>;
  43. /// dnet info for an inbound connection
  44. #[derive(Clone)]
  45. pub struct InboundInfo {
  46. /// Remote address
  47. pub addr: Option<Url>,
  48. /// Channel info
  49. pub channel: Option<ChannelInfo>,
  50. }
  51. impl InboundInfo {
  52. async fn dnet_info(&self, p2p: P2pPtr) -> Option<Self> {
  53. let Some(ref addr) = self.addr else { return None };
  54. let Some(chan) = p2p.channels().lock().await.get(&addr).cloned() else { return None };
  55. Some(Self { addr: self.addr.clone(), channel: Some(chan.dnet_info().await) })
  56. }
  57. }
  58. /// Defines inbound connections session
  59. pub struct InboundSession {
  60. p2p: Weak<P2p>,
  61. acceptors: Mutex<Vec<AcceptorPtr>>,
  62. accept_tasks: Mutex<Vec<StoppableTaskPtr>>,
  63. connect_infos: Mutex<Vec<HashMap<Url, InboundInfo>>>,
  64. }
  65. impl InboundSession {
  66. /// Create a new inbound session
  67. pub fn new(p2p: Weak<P2p>) -> InboundSessionPtr {
  68. Arc::new(Self {
  69. p2p,
  70. acceptors: Mutex::new(vec![]),
  71. accept_tasks: Mutex::new(vec![]),
  72. connect_infos: Mutex::new(vec![]),
  73. })
  74. }
  75. /// Starts the inbound session. Begins by accepting connections and fails
  76. /// if the addresses are not configured. Then runs the channel subscription
  77. /// loop.
  78. pub async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  79. if self.p2p().settings().inbound_addrs.is_empty() {
  80. info!(target: "net::inbound_session", "[P2P] Not configured for inbound connections.");
  81. return Ok(())
  82. }
  83. // Activate mutex lock on accept tasks.
  84. let mut accept_tasks = self.accept_tasks.lock().await;
  85. for (index, accept_addr) in self.p2p().settings().inbound_addrs.iter().enumerate() {
  86. self.clone().start_accept_session(index, accept_addr.clone(), ex.clone()).await?;
  87. let task = StoppableTask::new();
  88. task.clone().start(
  89. self.clone().channel_sub_loop(index, ex.clone()),
  90. // Ignore stop handler
  91. |_| async {},
  92. Error::NetworkServiceStopped,
  93. ex.clone(),
  94. );
  95. self.connect_infos.lock().await.push(HashMap::new());
  96. accept_tasks.push(task);
  97. }
  98. Ok(())
  99. }
  100. /// Stops the inbound session.
  101. pub async fn stop(&self) {
  102. let acceptors = &*self.acceptors.lock().await;
  103. for acceptor in acceptors {
  104. acceptor.stop().await;
  105. }
  106. let accept_tasks = &*self.accept_tasks.lock().await;
  107. for accept_task in accept_tasks {
  108. accept_task.stop().await;
  109. }
  110. }
  111. /// Start accepting connections for inbound session.
  112. async fn start_accept_session(
  113. self: Arc<Self>,
  114. index: usize,
  115. accept_addr: Url,
  116. ex: Arc<Executor<'_>>,
  117. ) -> Result<()> {
  118. info!(target: "net::inbound_session", "[P2P] Starting Inbound session #{} on {}", index, accept_addr);
  119. // Generate a new acceptor for this inbound session
  120. let acceptor = Acceptor::new(Mutex::new(None));
  121. let parent = Arc::downgrade(&self);
  122. *acceptor.session.lock().await = Some(Arc::new(parent));
  123. // Start listener
  124. let result = acceptor.clone().start(accept_addr, ex).await;
  125. if let Err(e) = result.clone() {
  126. error!(target: "net::inbound_session", "[P2P] Error starting listener #{}: {}", index, e);
  127. acceptor.stop().await;
  128. } else {
  129. self.acceptors.lock().await.push(acceptor);
  130. }
  131. result
  132. }
  133. /// Wait for all new channels created by the acceptor and call setup_channel() on them.
  134. async fn channel_sub_loop(self: Arc<Self>, index: usize, ex: Arc<Executor<'_>>) -> Result<()> {
  135. let channel_sub = self.acceptors.lock().await[index].clone().subscribe().await;
  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!(target: "net::inbound_session", "[P2P] Connected Inbound #{} [{}]", index, channel.address());
  152. self.register_channel(channel.clone(), ex.clone()).await?;
  153. let addr = channel.address().clone();
  154. self.connect_infos.lock().await[index]
  155. .insert(addr.clone(), InboundInfo { addr: Some(addr.clone()), channel: None });
  156. let stop_sub = channel.subscribe_stop().await?;
  157. stop_sub.receive().await;
  158. self.connect_infos.lock().await[index].remove(&addr);
  159. Ok(())
  160. }
  161. }
  162. /// Dnet information for the inbound session
  163. pub struct InboundDnet {
  164. /// Slot information
  165. pub slots: Vec<Option<InboundInfo>>,
  166. }
  167. #[async_trait]
  168. impl Session for InboundSession {
  169. fn p2p(&self) -> P2pPtr {
  170. self.p2p.upgrade().unwrap()
  171. }
  172. fn type_id(&self) -> SessionBitFlag {
  173. SESSION_INBOUND
  174. }
  175. async fn dnet_info(&self) -> DnetInfo {
  176. let mut slots = vec![];
  177. for listen_addr in (*self.connect_infos.lock().await).iter() {
  178. for slot in listen_addr.values() {
  179. slots.push(slot.dnet_info(self.p2p()).await);
  180. }
  181. }
  182. DnetInfo::Inbound(InboundDnet { slots })
  183. }
  184. }