acceptor.rs 8.7 KB

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