acceptor.rs 9.6 KB

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