acceptor.rs 9.0 KB

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