acceptor.rs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 async_std::sync::{Arc, Mutex};
  19. use log::error;
  20. use smol::Executor;
  21. use url::Url;
  22. use super::{
  23. channel::{Channel, ChannelPtr},
  24. session::SessionWeakPtr,
  25. transport::{Listener, PtListener},
  26. };
  27. use crate::{
  28. system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription},
  29. Error, Result,
  30. };
  31. /// Atomic pointer to Acceptor
  32. pub type AcceptorPtr = Arc<Acceptor>;
  33. /// Create inbound socket connections
  34. pub struct Acceptor {
  35. channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  36. task: StoppableTaskPtr,
  37. pub session: Mutex<Option<SessionWeakPtr>>,
  38. }
  39. impl Acceptor {
  40. /// Create new Acceptor object.
  41. pub fn new(session: Mutex<Option<SessionWeakPtr>>) -> AcceptorPtr {
  42. Arc::new(Self {
  43. channel_subscriber: Subscriber::new(),
  44. task: StoppableTask::new(),
  45. session,
  46. })
  47. }
  48. /// Start accepting inbound socket connections
  49. pub async fn start(self: Arc<Self>, endpoint: Url, ex: Arc<Executor<'_>>) -> Result<()> {
  50. let listener = Listener::new(endpoint).await?.listen().await?;
  51. self.accept(listener, ex);
  52. Ok(())
  53. }
  54. /// Stop accepting inbound socket connections
  55. pub async fn stop(&self) {
  56. // Send stop signal
  57. self.task.stop().await;
  58. }
  59. /// Start receiving network messages.
  60. pub async fn subscribe(self: Arc<Self>) -> Subscription<Result<ChannelPtr>> {
  61. self.channel_subscriber.clone().subscribe().await
  62. }
  63. /// Run the accept loop in a new thread and error if a connection problem occurs
  64. fn accept(self: Arc<Self>, listener: Box<dyn PtListener>, ex: Arc<Executor<'_>>) {
  65. let self_ = self.clone();
  66. self.task.clone().start(
  67. self.run_accept_loop(listener),
  68. |result| self_.handle_stop(result),
  69. Error::NetworkServiceStopped,
  70. ex,
  71. );
  72. }
  73. /// Run the accept loop.
  74. async fn run_accept_loop(self: Arc<Self>, listener: Box<dyn PtListener>) -> Result<()> {
  75. loop {
  76. match listener.next().await {
  77. Ok((stream, url)) => {
  78. let channel =
  79. Channel::new(stream, url, self.session.lock().await.clone().unwrap()).await;
  80. self.channel_subscriber.notify(Ok(channel)).await;
  81. }
  82. Err(e) => {
  83. error!(
  84. target: "net::acceptor::run_accept_loop()",
  85. "[P2P] Acceptor failed listening: {}", e,
  86. );
  87. }
  88. }
  89. }
  90. }
  91. /// Handles network errors. Panics if errors pass silently, otherwise broadcasts it
  92. /// to all channel subscribers.
  93. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  94. match result {
  95. Ok(()) => panic!("Acceptor task should never complete without error status"),
  96. Err(err) => self.channel_subscriber.notify(Err(err)).await,
  97. }
  98. }
  99. }