summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 8b4d4d5819fe3a4c79eeb13201659812973d03ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
pub mod config;

use crate::config::Config;
use anyhow::{bail, Context, Result};
use bytes::Bytes;
use http_body_util::{combinators::BoxBody, BodyExt, Empty};
use hyper::{
    body::Incoming, header::UPGRADE, http::uri::PathAndQuery, server::conn::http1,
    service::service_fn, upgrade::OnUpgrade, Method, Request, Response, StatusCode, Uri,
};
use log::{debug, error, info, warn};
use std::{fs::File, io::BufReader, path::Path, sync::Arc};
use tokio::{
    io::{AsyncRead, AsyncWrite},
    net::{TcpListener, TcpStream},
};
use tokio_rustls::TlsAcceptor;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    env_logger::init_from_env("LOG");

    let config = Arc::new(Config::load()?);

    tokio::select! {
        x = serve_http(config.clone()) => x.context("serving http")?,
        x = serve_https(config.clone()) => x.context("serving https")?,
    };
    Ok(())
}

async fn serve_http(config: Arc<Config>) -> Result<()> {
    let http_config = match &config.http {
        Some(n) => n,
        None => return Ok(()),
    };
    let listener = TcpListener::bind(http_config.bind).await?;
    info!("serving http");
    loop {
        let (stream, addr) = listener.accept().await.context("accepting connection")?;
        debug!("connection from {addr}");
        serve_stream(config.clone(), stream)
    }
}
async fn serve_https(config: Arc<Config>) -> Result<()> {
    let https_config = match &config.https {
        Some(n) => n,
        None => return Ok(()),
    };
    let tls_config = {
        let certs = load_certs(&https_config.tls_cert)?;
        let key = load_private_key(&https_config.tls_key)?;
        let mut cfg = rustls::ServerConfig::builder()
            .with_safe_defaults()
            .with_no_client_auth()
            .with_single_cert(certs, key)?;
        cfg.alpn_protocols = vec![
            // b"h2".to_vec(),
            b"http/1.1".to_vec(),
        ];
        Arc::new(cfg)
    };
    let listener = TcpListener::bind(https_config.bind).await?;
    let tls_acceptor = TlsAcceptor::from(tls_config);

    info!("serving https");
    loop {
        let (stream, addr) = listener.accept().await.context("accepting connection")?;
        debug!("connection from {addr}");
        let stream = tls_acceptor.accept(stream).await.context("accepting tls")?;
        serve_stream(config.clone(), stream)
    }
}

pub fn serve_stream<T: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
    config: Arc<Config>,
    stream: T,
) {
    tokio::task::spawn(async move {
        let conn = http1::Builder::new()
            .serve_connection(
                stream,
                service_fn(move |req| {
                    let config = config.clone();
                    async move {
                        match service(config, req).await {
                            Ok(r) => Ok(r),
                            Err(ServiceError::Hyper(e)) => Err(e),
                            Err(other) => Ok(Response::new(format!(
                                "the reverse proxy encountered an error: {other:?}"
                            ))
                            .map(|b| b.map_err(|e| match e {}).boxed())),
                        }
                    }
                }),
            )
            .with_upgrades();
        if let Err(err) = conn.await {
            error!("error: {:?}", err);
        }
    });
}

fn load_certs(path: &Path) -> anyhow::Result<Vec<rustls::Certificate>> {
    let mut reader = BufReader::new(File::open(path).context("reading tls certs")?);
    let certs = rustls_pemfile::certs(&mut reader).context("parsing tls certs")?;
    Ok(certs.into_iter().map(rustls::Certificate).collect())
}
fn load_private_key(path: &Path) -> anyhow::Result<rustls::PrivateKey> {
    let mut reader = BufReader::new(File::open(path).context("reading tls private key")?);
    let keys =
        rustls_pemfile::pkcs8_private_keys(&mut reader).context("parsing tls private key")?;
    if keys.len() != 1 {
        bail!("expected a single private key, found {}", keys.len())
    }
    Ok(rustls::PrivateKey(keys[0].clone()))
}

#[derive(Debug)]
enum ServiceError {
    Hyper(hyper::Error),
    NoHost,
    CantConnect,
}

async fn service(
    config: Arc<Config>,
    mut req: Request<Incoming>,
) -> Result<hyper::Response<BoxBody<bytes::Bytes, hyper::Error>>, ServiceError> {
    *req.uri_mut() = Uri::builder()
        .scheme("http")
        .authority("backend")
        .path_and_query(
            req.uri()
                .clone()
                .path_and_query()
                .cloned()
                .unwrap_or(PathAndQuery::from_static("/")),
        )
        .build()
        .unwrap();

    let route = config
        .hosts
        .get(remove_port(
            &req.headers()
                .get("host")
                .and_then(|e| e.to_str().ok())
                .map(String::from)
                .unwrap_or(String::from("")),
        ))
        .ok_or(ServiceError::NoHost)?;

    let upgrade_header = req.headers().get(UPGRADE).cloned();
    let on_upgrade_downstream = req.extensions_mut().remove::<OnUpgrade>();

    let mut resp = {
        let client_stream = TcpStream::connect(&route.backend)
            .await
            .map_err(|_| ServiceError::CantConnect)?;

        let (mut sender, conn) = hyper::client::conn::http1::handshake(client_stream)
            .await
            .map_err(ServiceError::Hyper)?;
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                warn!("connection failed: {:?}", err);
            }
        });
        sender
            .send_request(req)
            .await
            .map_err(ServiceError::Hyper)?
    };

    if let Some(proto) = upgrade_header {
        let on_upgrade_upstream = resp.extensions_mut().remove::<OnUpgrade>();
        tokio::task::spawn(async move {
            debug!("about upgrading connection, sending empty response");
            match (
                on_upgrade_upstream.unwrap().await,
                on_upgrade_downstream.unwrap().await,
            ) {
                (Ok(mut upgraded_upstream), Ok(mut upgraded_downstream)) => {
                    debug!("upgrade successful");
                    match tokio::io::copy_bidirectional(
                        &mut upgraded_downstream,
                        &mut upgraded_upstream,
                    )
                    .await
                    {
                        Ok((from_client, from_server)) => {
                            debug!("proxy socket terminated: {from_server} sent, {from_client} received")
                        }
                        Err(e) => warn!("proxy socket error: {e}"),
                    }
                }
                (a, b) => eprintln!("upgrade error: upstream={a:?} downstream={b:?}"),
            }
        });

        let mut resp = Response::new(Empty::<Bytes>::new());
        *resp.status_mut() = StatusCode::SWITCHING_PROTOCOLS;
        resp.headers_mut().insert(UPGRADE, proto);
        Ok(resp.map(|b| b.map_err(|e| match e {}).boxed()))
    } else {
        Ok(resp.map(|b| b.boxed()))
    }
}

pub fn remove_port(s: &str) -> &str {
    s.split_once(":").map(|(s, _)| s).unwrap_or(s)
}