inbound_session.rs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. use std::collections::HashMap;
  19. use async_std::sync::{Arc, Mutex, Weak};
  20. use async_trait::async_trait;
  21. use log::{error, info};
  22. use serde_json::json;
  23. use smol::Executor;
  24. use url::Url;
  25. use crate::{
  26. system::{StoppableTask, StoppableTaskPtr},
  27. Error, Result,
  28. };
  29. use super::{
  30. super::{Acceptor, AcceptorPtr, ChannelPtr, P2p},
  31. Session, SessionBitflag, SESSION_INBOUND,
  32. };
  33. struct InboundInfo {
  34. channel: ChannelPtr,
  35. }
  36. impl InboundInfo {
  37. async fn get_info(&self) -> serde_json::Value {
  38. self.channel.get_info().await
  39. }
  40. }
  41. /// Defines inbound connections session.
  42. pub struct InboundSession {
  43. p2p: Weak<P2p>,
  44. acceptors: Mutex<Vec<AcceptorPtr>>,
  45. accept_tasks: Mutex<Vec<StoppableTaskPtr>>,
  46. connect_infos: Mutex<Vec<HashMap<Url, InboundInfo>>>,
  47. }
  48. impl InboundSession {
  49. /// Create a new inbound session.
  50. pub async fn new(p2p: Weak<P2p>) -> Arc<Self> {
  51. Arc::new(Self {
  52. p2p,
  53. acceptors: Mutex::new(Vec::new()),
  54. accept_tasks: Mutex::new(Vec::new()),
  55. connect_infos: Mutex::new(Vec::new()),
  56. })
  57. }
  58. /// Starts the inbound session. Begins by accepting connections and fails if
  59. /// the addresses are not configured. Then runs the channel subscription
  60. /// loop.
  61. pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  62. if self.p2p().settings().inbound.is_empty() {
  63. info!(target: "net::inbound_session", "Not configured for accepting incoming connections.");
  64. return Ok(())
  65. }
  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.iter().enumerate() {
  69. self.clone().start_accept_session(index, accept_addr.clone(), executor.clone()).await?;
  70. let task = StoppableTask::new();
  71. task.clone().start(
  72. self.clone().channel_sub_loop(index, executor.clone()),
  73. // Ignore stop handler
  74. |_| async {},
  75. Error::NetworkServiceStopped,
  76. executor.clone(),
  77. );
  78. self.connect_infos.lock().await.push(HashMap::new());
  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. executor: Arc<Executor<'_>>,
  100. ) -> Result<()> {
  101. info!(target: "net::inbound_session", "#{} starting inbound session on {}", index, accept_addr);
  102. // Generate a new acceptor for this inbound session
  103. let acceptor = Acceptor::new(Mutex::new(None));
  104. let parent = Arc::downgrade(&self);
  105. *acceptor.session.lock().await = Some(Arc::new(parent));
  106. // Start listener
  107. let result = acceptor.clone().start(accept_addr, executor).await;
  108. if let Err(err) = result.clone() {
  109. error!(target: "net::inbound_session", "#{} error starting listener: {}", index, err);
  110. }
  111. self.acceptors.lock().await.push(acceptor);
  112. result
  113. }
  114. /// Wait for all new channels created by the acceptor and call
  115. /// setup_channel() on them.
  116. async fn channel_sub_loop(
  117. self: Arc<Self>,
  118. index: usize,
  119. executor: Arc<Executor<'_>>,
  120. ) -> Result<()> {
  121. let channel_sub = self.acceptors.lock().await[index].clone().subscribe().await;
  122. loop {
  123. let channel = channel_sub.receive().await?;
  124. // Spawn a detached task to process the channel
  125. // This will just perform the channel setup then exit.
  126. executor.spawn(self.clone().setup_channel(index, channel, executor.clone())).detach();
  127. }
  128. }
  129. /// Registers the channel. First performs a network handshake and starts the
  130. /// channel. Then starts sending keep-alive and address messages across the
  131. /// channel.
  132. async fn setup_channel(
  133. self: Arc<Self>,
  134. index: usize,
  135. channel: ChannelPtr,
  136. executor: Arc<Executor<'_>>,
  137. ) -> Result<()> {
  138. info!(target: "net::inbound_session", "#{} connected inbound [{}]", index, channel.address());
  139. self.clone().register_channel(channel.clone(), executor.clone()).await?;
  140. self.manage_channel_for_get_info(index, channel).await;
  141. Ok(())
  142. }
  143. async fn manage_channel_for_get_info(&self, index: usize, channel: ChannelPtr) {
  144. let key = channel.address();
  145. self.connect_infos.lock().await[index]
  146. .insert(key.clone(), InboundInfo { channel: channel.clone() });
  147. let stop_sub = channel.subscribe_stop().await;
  148. if stop_sub.is_ok() {
  149. stop_sub.unwrap().receive().await;
  150. }
  151. self.connect_infos.lock().await[index].remove(&key);
  152. }
  153. }
  154. #[async_trait]
  155. impl Session for InboundSession {
  156. async fn get_info(&self) -> serde_json::Value {
  157. let mut infos = HashMap::new();
  158. for (index, accept_addr) in self.p2p().settings().inbound.iter().enumerate() {
  159. let connect_infos = &self.connect_infos.lock().await[index];
  160. for (addr, info) in connect_infos {
  161. let json_addr = json!({ "accept_addr": accept_addr });
  162. let info = vec![json_addr, info.get_info().await];
  163. infos.insert(addr.to_string(), info);
  164. }
  165. }
  166. json!({
  167. "connected": infos,
  168. })
  169. }
  170. fn p2p(&self) -> Arc<P2p> {
  171. self.p2p.upgrade().unwrap()
  172. }
  173. fn type_id(&self) -> SessionBitflag {
  174. SESSION_INBOUND
  175. }
  176. }