acceptor.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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::{env, fs};
  19. use async_std::sync::{Arc, Mutex};
  20. use log::{error, info};
  21. use smol::Executor;
  22. use url::Url;
  23. use super::{
  24. transport::{TcpTransport, TorTransport, Transport, TransportListener, TransportName},
  25. Channel, ChannelPtr, SessionWeakPtr,
  26. };
  27. use crate::{
  28. system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription},
  29. Error, Result,
  30. };
  31. /// Atomic pointer to Acceptor class.
  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>>) -> Arc<Self> {
  42. Arc::new(Self {
  43. channel_subscriber: Subscriber::new(),
  44. task: StoppableTask::new(),
  45. session,
  46. })
  47. }
  48. /// Start accepting inbound socket connections. Creates a listener to start
  49. /// listening on a local socket address. Then runs an accept loop in a new
  50. /// thread, erroring if a connection problem occurs.
  51. pub async fn start(
  52. self: Arc<Self>,
  53. accept_url: Url,
  54. executor: Arc<Executor<'_>>,
  55. ) -> Result<()> {
  56. let transport_name = TransportName::try_from(accept_url.clone())?;
  57. macro_rules! accept {
  58. ($listener:expr, $transport:expr, $upgrade:expr) => {{
  59. if let Err(err) = $listener {
  60. error!(target: "net::acceptor", "Setup for {} failed: {}", accept_url, err);
  61. return Err(Error::BindFailed(accept_url.as_str().into()))
  62. }
  63. let listener = $listener?.await;
  64. if let Err(err) = listener {
  65. error!(target: "net::acceptor", "Bind listener to {} failed: {}", accept_url, err);
  66. return Err(Error::BindFailed(accept_url.as_str().into()))
  67. }
  68. let listener = listener?;
  69. match $upgrade {
  70. None => {
  71. self.accept(Box::new(listener), executor);
  72. }
  73. Some(u) if u == "tls" => {
  74. let tls_listener = $transport.upgrade_listener(listener)?.await?;
  75. self.accept(Box::new(tls_listener), executor);
  76. }
  77. Some(u) => return Err(Error::UnsupportedTransportUpgrade(u)),
  78. }
  79. }};
  80. }
  81. match transport_name {
  82. TransportName::Tcp(upgrade) => {
  83. let transport = TcpTransport::new(None, 1024);
  84. let listener = transport.listen_on(accept_url.clone());
  85. accept!(listener, transport, upgrade);
  86. }
  87. TransportName::Tor(upgrade) => {
  88. let socks5_url = Url::parse(
  89. &env::var("DARKFI_TOR_SOCKS5_URL")
  90. .unwrap_or_else(|_| "socks5://127.0.0.1:9050".to_string()),
  91. )?;
  92. let torc_url = Url::parse(
  93. &env::var("DARKFI_TOR_CONTROL_URL")
  94. .unwrap_or_else(|_| "tcp://127.0.0.1:9051".to_string()),
  95. )?;
  96. let auth_cookie = env::var("DARKFI_TOR_COOKIE");
  97. if auth_cookie.is_err() {
  98. return Err(Error::TorError(
  99. "Please set the env var DARKFI_TOR_COOKIE to the configured tor cookie file. \
  100. For example: \
  101. \'export DARKFI_TOR_COOKIE=\"/var/lib/tor/control_auth_cookie\"\'".to_string(),
  102. ));
  103. }
  104. let auth_cookie = auth_cookie.unwrap();
  105. let auth_cookie = hex::encode(fs::read(auth_cookie).unwrap());
  106. let transport = TorTransport::new(socks5_url, Some((torc_url, auth_cookie)))?;
  107. // generate EHS pointing to local address
  108. let hurl = transport.create_ehs(accept_url.clone())?;
  109. info!(target: "net::acceptor", "EHS TOR: {}", hurl.to_string());
  110. let listener = transport.clone().listen_on(accept_url.clone());
  111. accept!(listener, transport, upgrade);
  112. }
  113. _ => unimplemented!(),
  114. }
  115. Ok(())
  116. }
  117. /// Stop accepting inbound socket connections.
  118. pub async fn stop(&self) {
  119. // Send stop signal
  120. self.task.stop().await;
  121. }
  122. /// Start receiving network messages.
  123. pub async fn subscribe(self: Arc<Self>) -> Subscription<Result<ChannelPtr>> {
  124. self.channel_subscriber.clone().subscribe().await
  125. }
  126. /// Run the accept loop in a new thread and error if a connection problem
  127. /// occurs.
  128. fn accept(self: Arc<Self>, listener: Box<dyn TransportListener>, executor: Arc<Executor<'_>>) {
  129. let self2 = self.clone();
  130. self.task.clone().start(
  131. self.clone().run_accept_loop(listener),
  132. |result| self2.handle_stop(result),
  133. Error::NetworkServiceStopped,
  134. executor,
  135. );
  136. }
  137. /// Run the accept loop.
  138. async fn run_accept_loop(self: Arc<Self>, listener: Box<dyn TransportListener>) -> Result<()> {
  139. loop {
  140. match listener.next().await {
  141. Ok((stream, url)) => {
  142. let channel =
  143. Channel::new(stream, url, self.session.lock().await.clone().unwrap()).await;
  144. self.channel_subscriber.notify(Ok(channel)).await;
  145. }
  146. Err(e) => {
  147. error!(target: "net::acceptor", "Error listening for new connection: {}", e);
  148. }
  149. }
  150. }
  151. }
  152. /// Handles network errors. Panics if error passes silently, otherwise
  153. /// broadcasts the error.
  154. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  155. match result {
  156. Ok(()) => panic!("Acceptor task should never complete without error status"),
  157. Err(err) => {
  158. // Send this error to all channel subscribers
  159. let result = Err(err);
  160. self.channel_subscriber.notify(result).await;
  161. }
  162. }
  163. }
  164. }