acceptor.rs 8.9 KB

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