acceptor.rs 9.4 KB

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