acceptor.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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};
  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. // Create the new Channel.
  107. let session = self.session.clone();
  108. let channel = Channel::new(stream, url, session).await;
  109. // Increment the connection counter
  110. self.conn_count.fetch_add(1, SeqCst);
  111. // This task will subscribe on the new channel and decrement
  112. // the connection counter. Along with that, it will notify
  113. // the CondVar that might be waiting to allow new connections.
  114. let self_ = self.clone();
  115. let channel_ = channel.clone();
  116. let cv_ = cv.clone();
  117. ex.spawn(async move {
  118. let stop_sub = channel_.subscribe_stop().await.unwrap();
  119. stop_sub.receive().await;
  120. self_.conn_count.fetch_sub(1, SeqCst);
  121. cv_.notify();
  122. })
  123. .detach();
  124. // Finally, notify any subscribers about the new channel.
  125. self.channel_subscriber.notify(Ok(channel)).await;
  126. }
  127. // As per accept(2) recommendation:
  128. Err(e) if e.raw_os_error().is_some() => match e.raw_os_error().unwrap() {
  129. libc::EAGAIN | libc::ECONNABORTED | libc::EPROTO | libc::EINTR => continue,
  130. _ => {
  131. error!(
  132. target: "net::acceptor::run_accept_loop()",
  133. "[P2P] Acceptor failed listening: {}", e,
  134. );
  135. error!(
  136. target: "net::acceptor::run_accept_loop()",
  137. "[P2P] Closing listener loop"
  138. );
  139. return Err(e.into())
  140. }
  141. },
  142. // In case a TLS handshake fails, we'll get this:
  143. Err(e) if e.kind() == ErrorKind::UnexpectedEof => continue,
  144. // Errors we didn't handle above:
  145. Err(e) => {
  146. error!(
  147. target: "net::acceptor::run_accept_loop()",
  148. "[P2P] Unhandled listener.next() error: {}", e,
  149. );
  150. error!(
  151. target: "net::acceptor::run_accept_loop()",
  152. "[P2P] Closing listener loop"
  153. );
  154. return Err(e.into())
  155. }
  156. }
  157. }
  158. }
  159. /// Handles network errors. Panics if errors pass silently, otherwise broadcasts it
  160. /// to all channel subscribers.
  161. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  162. match result {
  163. Ok(()) => panic!("Acceptor task should never complete without error status"),
  164. Err(err) => self.channel_subscriber.notify(Err(err)).await,
  165. }
  166. }
  167. }