transport.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. use std::net::SocketAddr;
  2. use async_trait::async_trait;
  3. // TODO remove *
  4. use futures::prelude::*;
  5. use futures_rustls::{TlsAcceptor, TlsStream};
  6. use url::Url;
  7. use crate::Result;
  8. mod upgrade_tls;
  9. pub use upgrade_tls::TlsUpgrade;
  10. mod tcp;
  11. pub use tcp::TcpTransport;
  12. mod tor;
  13. pub use tor::TorTransport;
  14. mod unix;
  15. pub use unix::UnixTransport;
  16. /// A helper function to convert SocketAddr to Url and add scheme
  17. pub(crate) fn socket_addr_to_url(addr: SocketAddr, scheme: &str) -> Result<Url> {
  18. let url = Url::parse(&format!("{}://{}", scheme, addr))?;
  19. Ok(url)
  20. }
  21. /// Used as wrapper for stream used by Transport trait
  22. pub trait TransportStream: AsyncWrite + AsyncRead + Unpin + Send + Sync {}
  23. /// Used as wrapper for listener used by Transport trait
  24. #[async_trait]
  25. pub trait TransportListener: Send + Sync + Unpin {
  26. async fn next(&self) -> Result<(Box<dyn TransportStream>, Url)>;
  27. }
  28. #[derive(Clone)]
  29. pub enum TransportName {
  30. Tcp(Option<String>),
  31. Tor(Option<String>),
  32. Nym(Option<String>),
  33. Unix,
  34. }
  35. impl TryFrom<Url> for TransportName {
  36. type Error = crate::Error;
  37. fn try_from(url: Url) -> Result<Self> {
  38. let transport_name = match url.scheme() {
  39. "tcp" => Self::Tcp(None),
  40. "tcp+tls" | "tls" => Self::Tcp(Some("tls".into())),
  41. "tor" => Self::Tor(None),
  42. "tor+tls" => Self::Tor(Some("tls".into())),
  43. "nym" => Self::Nym(None),
  44. "nym+tls" => Self::Nym(Some("tls".into())),
  45. "unix" => Self::Unix,
  46. n => return Err(crate::Error::UnsupportedTransport(n.into())),
  47. };
  48. Ok(transport_name)
  49. }
  50. }
  51. /// The `Transport` trait serves as a base for implementing transport protocols.
  52. /// Base transports can optionally be upgraded with TLS in order to support encryption.
  53. /// The implementation of our TLS authentication can be found in the [`upgrade_tls`] module.
  54. pub trait Transport {
  55. type Acceptor;
  56. type Connector;
  57. type Listener: Future<Output = Result<Self::Acceptor>>;
  58. type Dial: Future<Output = Result<Self::Connector>>;
  59. type TlsListener: Future<Output = Result<(TlsAcceptor, Self::Acceptor)>>;
  60. type TlsDialer: Future<Output = Result<TlsStream<Self::Connector>>>;
  61. fn listen_on(self, url: Url) -> Result<Self::Listener>
  62. where
  63. Self: Sized;
  64. fn upgrade_listener(self, acceptor: Self::Acceptor) -> Result<Self::TlsListener>
  65. where
  66. Self: Sized;
  67. fn dial(self, url: Url) -> Result<Self::Dial>
  68. where
  69. Self: Sized;
  70. fn upgrade_dialer(self, stream: Self::Connector) -> Result<Self::TlsDialer>
  71. where
  72. Self: Sized;
  73. }