acceptor.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::{
  19. io::ErrorKind,
  20. sync::{
  21. atomic::{AtomicUsize, Ordering::SeqCst},
  22. Arc,
  23. },
  24. };
  25. use url::Url;
  26. #[cfg(feature = "upnp-igd")]
  27. use smol::lock::Mutex as AsyncMutex;
  28. use super::{
  29. channel::{Channel, ChannelPtr},
  30. hosts::HostColor,
  31. session::SessionWeakPtr,
  32. transport::{Listener, PtListener},
  33. };
  34. #[cfg(feature = "upnp-igd")]
  35. use super::upnp::{setup_port_mappings, PortMapping};
  36. use crate::{
  37. system::{
  38. CondVar, ExecutorPtr, Publisher, PublisherPtr, StoppableTask, StoppableTaskPtr,
  39. Subscription,
  40. },
  41. util::logger::verbose,
  42. Error, Result,
  43. };
  44. /// Atomic pointer to Acceptor
  45. pub type AcceptorPtr = Arc<Acceptor>;
  46. /// Create inbound socket connections
  47. pub struct Acceptor {
  48. channel_publisher: PublisherPtr<Result<ChannelPtr>>,
  49. task: StoppableTaskPtr,
  50. session: SessionWeakPtr,
  51. conn_count: AtomicUsize,
  52. #[cfg(feature = "upnp-igd")]
  53. port_mappings: AsyncMutex<Vec<Arc<dyn PortMapping>>>,
  54. }
  55. impl Acceptor {
  56. /// Create new Acceptor object.
  57. pub fn new(session: SessionWeakPtr) -> AcceptorPtr {
  58. Arc::new(Self {
  59. channel_publisher: Publisher::new(),
  60. task: StoppableTask::new(),
  61. session,
  62. conn_count: AtomicUsize::new(0),
  63. #[cfg(feature = "upnp-igd")]
  64. port_mappings: AsyncMutex::new(Vec::new()),
  65. })
  66. }
  67. /// Start accepting inbound socket connections
  68. pub async fn start(self: Arc<Self>, endpoint: Url, ex: ExecutorPtr) -> Result<()> {
  69. let datastore =
  70. self.session.upgrade().unwrap().p2p().settings().read().await.p2p_datastore.clone();
  71. // Initialize listener
  72. let listener = Listener::new(endpoint.clone(), datastore, true).await?;
  73. // Open socket
  74. let ptlistener = listener.listen().await?;
  75. #[cfg(feature = "p2p-tor")]
  76. if endpoint.scheme() == "tor" {
  77. let onion_addr = listener.endpoint().await;
  78. verbose!("[P2P] Adding {onion_addr} to external_addrs");
  79. self.session
  80. .upgrade()
  81. .unwrap()
  82. .p2p()
  83. .settings()
  84. .write()
  85. .await
  86. .external_addrs
  87. .push(onion_addr);
  88. }
  89. #[cfg(feature = "upnp-igd")]
  90. {
  91. let actual_endpoint = listener.endpoint().await;
  92. let settings = self.session.upgrade().unwrap().p2p().settings();
  93. let mappings = setup_port_mappings(&actual_endpoint, settings, ex.clone());
  94. self.port_mappings.lock().await.extend(mappings);
  95. }
  96. self.accept(ptlistener, ex);
  97. Ok(())
  98. }
  99. /// Stop accepting inbound socket connections
  100. pub async fn stop(&self) {
  101. // Stop all port mappings
  102. #[cfg(feature = "upnp-igd")]
  103. {
  104. let mappings = std::mem::take(&mut *self.port_mappings.lock().await);
  105. for mapping in mappings {
  106. mapping.stop();
  107. }
  108. }
  109. // Send stop signal
  110. self.task.stop().await;
  111. }
  112. /// Start receiving network messages.
  113. pub async fn subscribe(self: Arc<Self>) -> Subscription<Result<ChannelPtr>> {
  114. self.channel_publisher.clone().subscribe().await
  115. }
  116. /// Run the accept loop in a new thread and error if a connection problem occurs
  117. fn accept(self: Arc<Self>, listener: Box<dyn PtListener>, ex: ExecutorPtr) {
  118. let self_ = self.clone();
  119. self.task.clone().start(
  120. self.run_accept_loop(listener, ex.clone()),
  121. |result| self_.handle_stop(result),
  122. Error::NetworkServiceStopped,
  123. ex,
  124. );
  125. }
  126. /// Run the accept loop.
  127. async fn run_accept_loop(
  128. self: Arc<Self>,
  129. listener: Box<dyn PtListener>,
  130. ex: ExecutorPtr,
  131. ) -> Result<()> {
  132. // CondVar used to notify the loop to recheck if new connections can
  133. // be accepted by the listener.
  134. let cv = Arc::new(CondVar::new());
  135. let hosts = self.session.upgrade().unwrap().p2p().hosts();
  136. loop {
  137. // Refuse new connections if we're up to the connection limit
  138. let limit =
  139. self.session.upgrade().unwrap().p2p().settings().read().await.inbound_connections;
  140. if self.clone().conn_count.load(SeqCst) >= limit {
  141. // This will get notified every time an inbound channel is stopped.
  142. // These channels are the channels spawned below on listener.next().is_ok().
  143. // After the notification, we reset the condvar and retry this loop to see
  144. // if we can accept more connections, and if not - we'll be back here.
  145. verbose!(target: "net::acceptor::run_accept_loop", "Reached incoming conn limit, waiting...");
  146. cv.wait().await;
  147. cv.reset();
  148. continue
  149. }
  150. // Now we wait for a new connection.
  151. match listener.next().await {
  152. Ok((stream, url)) => {
  153. // Check if we reject this peer
  154. if hosts.container.contains(HostColor::Black, &url) ||
  155. hosts.block_all_ports(&url)
  156. {
  157. verbose!(target: "net::acceptor::run_accept_loop", "Peer {url} is blacklisted");
  158. continue
  159. }
  160. // Create the new Channel.
  161. let session = self.session.clone();
  162. let channel = Channel::new(stream, None, url, session, false).await;
  163. // Increment the connection counter
  164. self.conn_count.fetch_add(1, SeqCst);
  165. // This task will subscribe on the new channel and decrement
  166. // the connection counter. Along with that, it will notify
  167. // the CondVar that might be waiting to allow new connections.
  168. let self_ = self.clone();
  169. let channel_ = channel.clone();
  170. let cv_ = cv.clone();
  171. ex.spawn(async move {
  172. let stop_sub = channel_.subscribe_stop().await?;
  173. stop_sub.receive().await;
  174. self_.conn_count.fetch_sub(1, SeqCst);
  175. cv_.notify();
  176. Ok::<(), crate::Error>(())
  177. })
  178. .detach();
  179. // Finally, notify any publishers about the new channel.
  180. self.channel_publisher.notify(Ok(channel)).await;
  181. }
  182. // As per accept(2) recommendation:
  183. Err(e) if e.raw_os_error().is_some() => match e.raw_os_error().unwrap() {
  184. libc::EAGAIN | libc::ECONNABORTED | libc::EPROTO | libc::EINTR => continue,
  185. libc::ECONNRESET => {
  186. verbose!(
  187. target: "net::acceptor::run_accept_loop",
  188. "[P2P] Connection reset by peer in accept_loop"
  189. );
  190. continue
  191. }
  192. libc::ETIMEDOUT => {
  193. verbose!(
  194. target: "net::acceptor::run_accept_loop",
  195. "[P2P] Connection timed out in accept_loop"
  196. );
  197. continue
  198. }
  199. libc::EPIPE => {
  200. verbose!(
  201. target: "net::acceptor::run_accept_loop",
  202. "[P2P] Broken pipe in accept_loop"
  203. );
  204. continue
  205. }
  206. x => {
  207. verbose!(
  208. target: "net::acceptor::run_accept_loop",
  209. "[P2P] Unhandled OS Error: {e} {x}"
  210. );
  211. continue
  212. }
  213. },
  214. // In case a TLS handshake fails, we'll get this:
  215. Err(e) if e.kind() == ErrorKind::UnexpectedEof => continue,
  216. // Handle ErrorKind::Other
  217. Err(e) if e.kind() == ErrorKind::Other => {
  218. if let Some(inner) = std::error::Error::source(&e) {
  219. if let Some(inner) = inner.downcast_ref::<futures_rustls::rustls::Error>() {
  220. verbose!(
  221. target: "net::acceptor::run_accept_loop",
  222. "[P2P] rustls listener error: {inner:?}"
  223. );
  224. continue
  225. }
  226. }
  227. verbose!(
  228. target: "net::acceptor::run_accept_loop",
  229. "[P2P] Unhandled ErrorKind::Other error: {e:?}"
  230. );
  231. continue
  232. }
  233. // Errors we didn't handle above:
  234. Err(e) => {
  235. verbose!(
  236. target: "net::acceptor::run_accept_loop",
  237. "[P2P] Unhandled listener.next() error: {e}"
  238. );
  239. continue
  240. }
  241. }
  242. }
  243. }
  244. /// Handles network errors. Panics if errors pass silently, otherwise broadcasts it
  245. /// to all channel publishers.
  246. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  247. match result {
  248. Ok(()) => panic!("Acceptor task should never complete without error status"),
  249. Err(err) => self.channel_publisher.notify(Err(err)).await,
  250. }
  251. }
  252. }