|
| 1 | +//! Connection hooks for customizing connection setup. |
| 2 | +//! |
| 3 | +//! The [`ConnectionHook`] trait provides a way to intercept connections during setup, |
| 4 | +//! enabling custom authentication, handshakes, or protocol negotiations. |
| 5 | +//! |
| 6 | +//! # Built-in Hooks |
| 7 | +//! |
| 8 | +//! The [`token`] module provides ready-to-use token-based authentication hooks: |
| 9 | +//! - [`token::ServerHook`] - Server-side hook that validates client tokens |
| 10 | +//! - [`token::ClientHook`] - Client-side hook that sends a token to the server |
| 11 | +//! |
| 12 | +//! # Custom Hooks |
| 13 | +//! |
| 14 | +//! Implement [`ConnectionHook`] for custom authentication or protocol negotiation: |
| 15 | +//! |
| 16 | +//! ```rust,ignore |
| 17 | +//! use msg_socket::ConnectionHook; |
| 18 | +//! use std::io; |
| 19 | +//! use tokio::io::{AsyncRead, AsyncWrite, AsyncReadExt, AsyncWriteExt}; |
| 20 | +//! |
| 21 | +//! struct MyAuth; |
| 22 | +//! |
| 23 | +//! impl<Io> ConnectionHook<Io> for MyAuth |
| 24 | +//! where |
| 25 | +//! Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, |
| 26 | +//! { |
| 27 | +//! async fn on_connection(&self, mut io: Io) -> Result<Io, HookError> { |
| 28 | +//! let mut buf = [0u8; 32]; |
| 29 | +//! io.read_exact(&mut buf).await?; |
| 30 | +//! if &buf == b"expected_token_value_32_bytes!!!" { |
| 31 | +//! io.write_all(b"OK").await?; |
| 32 | +//! Ok(io) |
| 33 | +//! } else { |
| 34 | +//! Err(HookError::custom("invalid token")) |
| 35 | +//! } |
| 36 | +//! } |
| 37 | +//! } |
| 38 | +//! ``` |
| 39 | +
|
| 40 | +use std::{error::Error as StdError, fmt, future::Future, io, pin::Pin, sync::Arc}; |
| 41 | + |
| 42 | +use tokio::io::{AsyncRead, AsyncWrite}; |
| 43 | + |
| 44 | +pub mod token; |
| 45 | + |
| 46 | +/// Error type for connection hooks. |
| 47 | +/// |
| 48 | +/// This enum provides two variants: |
| 49 | +/// - `Io` for standard I/O errors |
| 50 | +/// - `Custom` for hook-specific errors (type-erased) |
| 51 | +#[derive(Debug)] |
| 52 | +pub enum HookError { |
| 53 | + /// An I/O error occurred. |
| 54 | + Io(io::Error), |
| 55 | + /// A custom hook-specific error. |
| 56 | + Custom(Box<dyn StdError + Send + Sync + 'static>), |
| 57 | +} |
| 58 | + |
| 59 | +impl HookError { |
| 60 | + /// Creates a custom error from any error type. |
| 61 | + pub fn custom<E>(error: E) -> Self |
| 62 | + where |
| 63 | + E: StdError + Send + Sync + 'static, |
| 64 | + { |
| 65 | + Self::Custom(Box::new(error)) |
| 66 | + } |
| 67 | + |
| 68 | + /// Creates a custom error from a string message. |
| 69 | + pub fn message(msg: impl Into<String>) -> Self { |
| 70 | + Self::Io(io::Error::other(msg.into())) |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl fmt::Display for HookError { |
| 75 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 76 | + match self { |
| 77 | + Self::Io(e) => write!(f, "IO error: {e}"), |
| 78 | + Self::Custom(e) => write!(f, "Hook error: {e}"), |
| 79 | + } |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +impl StdError for HookError { |
| 84 | + fn source(&self) -> Option<&(dyn StdError + 'static)> { |
| 85 | + match self { |
| 86 | + Self::Io(e) => Some(e), |
| 87 | + Self::Custom(e) => Some(e.as_ref()), |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +impl From<io::Error> for HookError { |
| 93 | + fn from(error: io::Error) -> Self { |
| 94 | + Self::Io(error) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +/// Hook executed during connection setup. |
| 99 | +/// |
| 100 | +/// For server sockets (Rep, Pub): called when a connection is accepted. |
| 101 | +/// For client sockets (Req, Sub): called after connecting. |
| 102 | +/// |
| 103 | +/// The hook receives the raw IO stream and has full control over the handshake protocol. |
| 104 | +pub trait ConnectionHook<Io>: Send + Sync + 'static |
| 105 | +where |
| 106 | + Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, |
| 107 | +{ |
| 108 | + /// Called when a connection is established. |
| 109 | + /// |
| 110 | + /// # Arguments |
| 111 | + /// * `io` - The raw IO stream for this connection |
| 112 | + /// |
| 113 | + /// # Returns |
| 114 | + /// The IO stream on success (potentially wrapped/transformed), or an error to reject |
| 115 | + /// the connection. |
| 116 | + fn on_connection(&self, io: Io) -> impl Future<Output = Result<Io, HookError>> + Send; |
| 117 | +} |
| 118 | + |
| 119 | +// ============================================================================ |
| 120 | +// Type-erased hook for internal use |
| 121 | +// ============================================================================ |
| 122 | + |
| 123 | +/// Type-erased connection hook for internal use. |
| 124 | +/// |
| 125 | +/// This trait allows storing hooks with different concrete types behind a single |
| 126 | +/// `Arc<dyn ConnectionHookErased<Io>>`. |
| 127 | +pub(crate) trait ConnectionHookErased<Io>: Send + Sync + 'static |
| 128 | +where |
| 129 | + Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, |
| 130 | +{ |
| 131 | + fn on_connection( |
| 132 | + self: Arc<Self>, |
| 133 | + io: Io, |
| 134 | + ) -> Pin<Box<dyn Future<Output = Result<Io, HookError>> + Send + 'static>>; |
| 135 | +} |
| 136 | + |
| 137 | +impl<T, Io> ConnectionHookErased<Io> for T |
| 138 | +where |
| 139 | + T: ConnectionHook<Io>, |
| 140 | + Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, |
| 141 | +{ |
| 142 | + fn on_connection( |
| 143 | + self: Arc<Self>, |
| 144 | + io: Io, |
| 145 | + ) -> Pin<Box<dyn Future<Output = Result<Io, HookError>> + Send + 'static>> { |
| 146 | + Box::pin(async move { ConnectionHook::on_connection(&*self, io).await }) |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +// ============================================================================ |
| 151 | +// Hook result type for driver tasks |
| 152 | +// ============================================================================ |
| 153 | + |
| 154 | +/// The result of running a connection hook. |
| 155 | +/// |
| 156 | +/// Contains the processed IO stream and associated address. |
| 157 | +pub(crate) struct HookResult<Io, A> { |
| 158 | + pub(crate) stream: Io, |
| 159 | + pub(crate) addr: A, |
| 160 | +} |
0 commit comments