Skip to content

Sending plaintext response for non-TLS connection attempts #54

@BrandonLeeDotDev

Description

@BrandonLeeDotDev

This is my current attempt among others. Both print statements print. I have had intermittent success... its just not stable. Whats the correct way to approach this within the lib itself?


pub struct TlsListener(
    Vec<CertificateDer<'static>>,
    PrivateKeyDer<'static>,
    TlsAcceptor,
    TcpListener,
);

impl TlsListener {
    pub async fn bind(address: SocketAddr) -> Self {
        let listener = TcpListener::bind(address).await.unwrap();

        let certs = Path::new(CERTS_PATH);
        let cert = load_certs(&certs).unwrap();

        let key = Path::new(KEY_PATH);
        let key = load_keys(&key).unwrap();

        let config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(cert.clone(), key.clone_key())
            .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
            .unwrap();
        let acceptor = TlsAcceptor::from(Arc::new(config));

        TlsListener(cert, key, acceptor, listener)
    }

    pub async fn redirect(&self) -> io::Result<()> {
        println!("Redirecting");
        let (mut stream, _peer_addr) = self.3.accept().await?;
        let redirect =
            b"HTTP/1.1 301 Moved Permanently\r\nLocation: https://localhost:4010/\r\n\r\n";
        stream.write(redirect).await?;
        stream.flush().await?;
        println!("Redirected");
        Ok(())
    }

    pub async fn accept(&self) -> io::Result<(TlsStream<TcpStream>, SocketAddr)> {
        let listener = &self.3;
        let (stream, peer_addr) = listener.accept().await?;

        match self.2.accept(stream).await {
            Ok(stream) => Ok((stream, peer_addr)),
            Err(error) => {
                self.redirect().await?;
                Err(error)
            }
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions