pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
use std::{
    future::Future,
    io,
    net::{SocketAddr, TcpStream, UdpSocket},
    pin::Pin,
    result::Result as StdResult,
    sync::OnceLock,
    task::{Context, Poll},
    time::Duration,
};

use async_trait::async_trait;
use futures_lite::future;
use hickory_resolver::net::runtime::{DnsTcpStream, DnsUdpSocket, RuntimeProvider, Spawn, Time};

use crate::runtime::Timer;
#[cfg(feature = "smtp")]
use crate::runtime::{BoxIo, Connect, Connector};
#[cfg(all(feature = "smtp", feature = "runtime-portable-tls"))]
use crate::runtime::{TlsConnector, Upgrade};
use crate::{Error, Result};
#[cfg(all(feature = "smtp", feature = "runtime-portable-tls"))]
use rustls_platform_verifier::BuilderVerifierExt as _;
#[cfg(all(feature = "smtp", feature = "runtime-portable-tls"))]
use std::sync::Arc;

#[derive(Clone, Copy, Debug)]
pub(super) struct PortableProvider;

impl RuntimeProvider for PortableProvider {
    type Handle = PortableHandle;
    type Timer = PortableTime;
    type Udp = PortableUdp;
    type Tcp = PortableTcp;

    fn create_handle(&self) -> Self::Handle {
        PortableHandle
    }

    fn connect_tcp(
        &self,
        server_addr: SocketAddr,
        bind_addr: Option<SocketAddr>,
        timeout: Option<Duration>,
    ) -> Pin<Box<dyn Send + Future<Output = io::Result<Self::Tcp>>>> {
        Box::pin(async move {
            if bind_addr.is_some() {
                return Err(io::Error::new(
                    io::ErrorKind::Unsupported,
                    "custom DNS source addresses are unsupported",
                ));
            }
            let connect = async_io::Async::<TcpStream>::connect(server_addr);
            let stream = match timeout {
                Some(duration) => PortableTime::timeout(duration, connect).await??,
                None => connect.await?,
            };
            stream.get_ref().set_nodelay(true)?;
            Ok(PortableTcp(stream))
        })
    }

    fn bind_udp(
        &self,
        local_addr: SocketAddr,
        _server_addr: SocketAddr,
    ) -> Pin<Box<dyn Send + Future<Output = io::Result<Self::Udp>>>> {
        Box::pin(async move {
            let socket = UdpSocket::bind(local_addr)?;
            socket.set_nonblocking(true)?;
            async_io::Async::new(socket).map(PortableUdp)
        })
    }
}

#[derive(Clone, Copy, Debug)]
pub(super) struct PortableHandle;

impl Spawn for PortableHandle {
    fn spawn_bg(&mut self, task: impl Future<Output = ()> + Send + 'static) {
        if let Ok(executor) = shared_executor() {
            executor.spawn(task).detach();
        }
    }
}

fn shared_executor() -> StdResult<&'static async_executor::Executor<'static>, ()> {
    static SHARED: OnceLock<StdResult<&'static async_executor::Executor<'static>, ()>> =
        OnceLock::new();
    *SHARED.get_or_init(|| {
        let executor: &'static async_executor::Executor<'static> =
            Box::leak(Box::new(async_executor::Executor::new()));
        let driver = executor;
        std::thread::Builder::new()
            .name("pata-dns".to_owned())
            .spawn(move || async_io::block_on(driver.run(future::pending::<()>())))
            .map(|_| &*executor)
            .map_err(|_| ())
    })
}

pub(super) fn initialize() -> Result<()> {
    shared_executor().map(|_| ()).map_err(|()| {
        Error::NetworkInitialization("cannot start the portable DNS executor".to_owned())
    })
}

#[derive(Clone, Copy, Debug)]
pub(super) struct PortableTime;

#[async_trait]
impl Time for PortableTime {
    async fn delay_for(duration: Duration) {
        async_io::Timer::after(duration).await;
    }

    async fn timeout<F: Future + Send + 'static>(
        duration: Duration,
        work: F,
    ) -> io::Result<F::Output> {
        if duration.is_zero() {
            return Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "DNS operation timed out",
            ));
        }
        future::or(async move { Ok(work.await) }, async move {
            async_io::Timer::after(duration).await;
            Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "DNS operation timed out",
            ))
        })
        .await
    }
}

pub(super) struct PortableUdp(async_io::Async<UdpSocket>);

#[async_trait]
impl DnsUdpSocket for PortableUdp {
    type Time = PortableTime;

    fn poll_recv_from(
        &self,
        context: &mut Context<'_>,
        buffer: &mut [u8],
    ) -> Poll<io::Result<(usize, SocketAddr)>> {
        loop {
            match self.0.get_ref().recv_from(buffer) {
                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
                result => return Poll::Ready(result),
            }
            std::task::ready!(self.0.poll_readable(context))?;
        }
    }

    fn poll_send_to(
        &self,
        context: &mut Context<'_>,
        buffer: &[u8],
        target: SocketAddr,
    ) -> Poll<io::Result<usize>> {
        loop {
            match self.0.get_ref().send_to(buffer, target) {
                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
                result => return Poll::Ready(result),
            }
            std::task::ready!(self.0.poll_writable(context))?;
        }
    }
}

pub(super) struct PortableTcp(async_io::Async<TcpStream>);

impl futures_io::AsyncRead for PortableTcp {
    fn poll_read(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffer: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.0).poll_read(context, buffer)
    }
}

impl futures_io::AsyncWrite for PortableTcp {
    fn poll_write(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffer: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.0).poll_write(context, buffer)
    }

    fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_flush(context)
    }

    fn poll_close(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_close(context)
    }
}

impl DnsTcpStream for PortableTcp {
    type Time = PortableTime;
}

#[cfg(feature = "smtp")]
#[derive(Clone, Copy, Debug)]
pub(super) struct PortableConnector;

#[cfg(feature = "smtp")]
impl Connector for PortableConnector {
    fn connect(&self, address: SocketAddr, deadline: std::time::Instant) -> Connect<'_> {
        Box::pin(async move {
            let remaining = deadline
                .checked_duration_since(std::time::Instant::now())
                .filter(|duration| !duration.is_zero())
                .ok_or_else(|| {
                    io::Error::new(io::ErrorKind::TimedOut, "connection deadline expired")
                })?;
            let stream =
                PortableTime::timeout(remaining, async_io::Async::<TcpStream>::connect(address))
                    .await??;
            stream.get_ref().set_nodelay(true)?;
            Ok(Box::new(stream) as BoxIo)
        })
    }
}

#[derive(Clone, Copy, Debug)]
pub(super) struct PortableTimer;

impl Timer for PortableTimer {
    fn sleep(&self, duration: Duration) -> crate::runtime::Sleep {
        Box::pin(async move {
            async_io::Timer::after(duration).await;
        })
    }
}

#[cfg(all(feature = "smtp", feature = "runtime-portable-tls"))]
#[derive(Clone, Copy, Debug)]
pub(super) struct PortableTls;

#[cfg(all(feature = "smtp", feature = "runtime-portable-tls"))]
fn tls_config() -> io::Result<Arc<rustls::ClientConfig>> {
    static CONFIG: OnceLock<StdResult<Arc<rustls::ClientConfig>, String>> = OnceLock::new();
    CONFIG
        .get_or_init(|| {
            let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
            let builder = rustls::ClientConfig::builder_with_provider(provider)
                .with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12])
                .map_err(|error| format!("invalid TLS policy: {error}"))?
                .with_platform_verifier()
                .map_err(|error| format!("platform TLS verification failed: {error}"))?;
            Ok(Arc::new(builder.with_no_client_auth()))
        })
        .clone()
        .map_err(io::Error::other)
}

#[cfg(all(feature = "smtp", feature = "runtime-portable-tls"))]
impl TlsConnector for PortableTls {
    fn upgrade<'a>(&'a self, server_name: &'a str, stream: BoxIo) -> Upgrade<'a> {
        Box::pin(async move {
            let server_name = rustls_pki_types::ServerName::try_from(server_name.to_owned())
                .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid TLS name"))?;
            futures_rustls::TlsConnector::from(tls_config()?)
                .connect(server_name, stream)
                .await
                .map(|stream| Box::new(stream) as BoxIo)
        })
    }
}

#[cfg(test)]
mod tests {
    use futures_executor::block_on;

    use super::*;

    #[test]
    fn zero_dns_timeout_expires_before_polling_work() {
        let result = block_on(PortableTime::timeout(
            Duration::ZERO,
            std::future::ready(()),
        ));

        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::TimedOut);
    }

    #[cfg(feature = "smtp")]
    #[test]
    fn expired_connection_deadline_skips_the_socket() {
        let result = block_on(
            PortableConnector.connect("127.0.0.1:25".parse().unwrap(), std::time::Instant::now()),
        );

        assert_eq!(result.err().unwrap().kind(), io::ErrorKind::TimedOut);
    }
}