acceptor.rs 11 KB

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