layer4-proxy/src/servers/protocol/tcp.rs

56 lines
1.7 KiB
Rust
Raw Normal View History

use crate::servers::protocol::tls::determine_upstream_name;
use crate::servers::Proxy;
use log::{debug, error, info, trace, warn};
use std::error::Error;
2021-10-26 13:36:12 +00:00
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
pub(crate) async fn proxy(config: Arc<Proxy>) -> Result<(), Box<dyn Error>> {
2021-10-26 13:36:12 +00:00
let listener = TcpListener::bind(config.listen).await?;
let config = config.clone();
loop {
let thread_proxy = config.clone();
match listener.accept().await {
Err(err) => {
error!("Failed to accept connection: {}", err);
return Err(Box::new(err));
}
Ok((stream, _)) => {
tokio::spawn(async move {
match accept(stream, thread_proxy).await {
Ok(_) => {}
Err(err) => {
error!("Relay thread returned an error: {}", err);
}
};
});
}
}
}
}
async fn accept(inbound: TcpStream, proxy: Arc<Proxy>) -> Result<(), Box<dyn Error>> {
info!("New connection from {:?}", inbound.peer_addr()?);
2021-10-26 13:36:12 +00:00
let upstream_name = match proxy.tls {
false => proxy.default_action.clone(),
true => determine_upstream_name(&inbound, &proxy).await?,
2021-10-26 13:36:12 +00:00
};
debug!("Upstream: {}", upstream_name);
let upstream = match proxy.upstream.get(&upstream_name) {
Some(upstream) => upstream,
None => {
warn!(
"No upstream named {:?} on server {:?}",
proxy.default_action, proxy.name
2021-10-26 13:36:12 +00:00
);
proxy.upstream.get(&proxy.default_action).unwrap()
2021-10-26 13:36:12 +00:00
}
};
upstream.process(inbound).await
2021-10-26 13:36:12 +00:00
}