split proxy into stream handler and http message handler
This commit is contained in:
parent
0c6ffa5e77
commit
954a1993a9
14 changed files with 92 additions and 71 deletions
|
|
@ -1,203 +0,0 @@
|
|||
use super::UpstreamOption;
|
||||
use crate::log::*;
|
||||
use rand::Rng;
|
||||
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, BufReader, Cursor, Read},
|
||||
path::PathBuf,
|
||||
sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
},
|
||||
};
|
||||
use tokio_rustls::rustls::{Certificate, PrivateKey, ServerConfig};
|
||||
|
||||
// server name (hostname or ip address) in ascii lower case
|
||||
pub type ServerNameLC = Vec<u8>;
|
||||
|
||||
pub struct Backends {
|
||||
pub apps: HashMap<ServerNameLC, Backend>, // TODO: hyper::uriで抜いたhostで引っ掛ける。Stringでいいのか?
|
||||
pub default_server_name: Option<ServerNameLC>, // for plaintext http
|
||||
}
|
||||
|
||||
pub struct Backend {
|
||||
pub app_name: String,
|
||||
pub server_name: String,
|
||||
pub reverse_proxy: ReverseProxy,
|
||||
|
||||
// tls settings
|
||||
pub tls_cert_path: Option<PathBuf>,
|
||||
pub tls_cert_key_path: Option<PathBuf>,
|
||||
pub https_redirection: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ReverseProxy {
|
||||
pub default_upstream: Option<Upstream>,
|
||||
pub upstream: HashMap<String, Upstream>,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LoadBalance {
|
||||
RoundRobin,
|
||||
Random,
|
||||
}
|
||||
impl Default for LoadBalance {
|
||||
fn default() -> Self {
|
||||
Self::RoundRobin
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Upstream {
|
||||
pub uri: Vec<hyper::Uri>,
|
||||
pub lb: LoadBalance,
|
||||
pub cnt: UpstreamCount, // counter for load balancing
|
||||
pub opts: HashSet<UpstreamOption>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct UpstreamCount(Arc<AtomicUsize>);
|
||||
|
||||
impl Upstream {
|
||||
pub fn get(&self) -> Option<&hyper::Uri> {
|
||||
match self.lb {
|
||||
LoadBalance::RoundRobin => {
|
||||
let idx = self.increment_cnt();
|
||||
self.uri.get(idx)
|
||||
}
|
||||
LoadBalance::Random => {
|
||||
let mut rng = rand::thread_rng();
|
||||
let max = self.uri.len() - 1;
|
||||
self.uri.get(rng.gen_range(0..max))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn current_cnt(&self) -> usize {
|
||||
self.cnt.0.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn increment_cnt(&self) -> usize {
|
||||
if self.current_cnt() < self.uri.len() - 1 {
|
||||
self.cnt.0.fetch_add(1, Ordering::Relaxed)
|
||||
} else {
|
||||
self.cnt.0.fetch_and(0, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub async fn update_server_config(&self) -> io::Result<ServerConfig> {
|
||||
debug!("Update TLS server config");
|
||||
let (certs_path, certs_keys_path) =
|
||||
if let (Some(c), Some(k)) = (self.tls_cert_path.as_ref(), self.tls_cert_key_path.as_ref()) {
|
||||
(c, k)
|
||||
} else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
"Invalid certs and keys paths",
|
||||
));
|
||||
};
|
||||
let certs: Vec<_> = {
|
||||
let certs_path_str = certs_path.display().to_string();
|
||||
let mut reader = BufReader::new(File::open(certs_path).map_err(|e| {
|
||||
io::Error::new(
|
||||
e.kind(),
|
||||
format!(
|
||||
"Unable to load the certificates [{}]: {}",
|
||||
certs_path_str, e
|
||||
),
|
||||
)
|
||||
})?);
|
||||
rustls_pemfile::certs(&mut reader).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Unable to parse the certificates",
|
||||
)
|
||||
})?
|
||||
}
|
||||
.drain(..)
|
||||
.map(Certificate)
|
||||
.collect();
|
||||
let certs_keys: Vec<_> = {
|
||||
let certs_keys_path_str = certs_keys_path.display().to_string();
|
||||
let encoded_keys = {
|
||||
let mut encoded_keys = vec![];
|
||||
File::open(certs_keys_path)
|
||||
.map_err(|e| {
|
||||
io::Error::new(
|
||||
e.kind(),
|
||||
format!(
|
||||
"Unable to load the certificate keys [{}]: {}",
|
||||
certs_keys_path_str, e
|
||||
),
|
||||
)
|
||||
})?
|
||||
.read_to_end(&mut encoded_keys)?;
|
||||
encoded_keys
|
||||
};
|
||||
let mut reader = Cursor::new(encoded_keys);
|
||||
let pkcs8_keys = rustls_pemfile::pkcs8_private_keys(&mut reader).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Unable to parse the certificates private keys (PKCS8)",
|
||||
)
|
||||
})?;
|
||||
reader.set_position(0);
|
||||
let mut rsa_keys = rustls_pemfile::rsa_private_keys(&mut reader).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Unable to parse the certificates private keys (RSA)",
|
||||
)
|
||||
})?;
|
||||
let mut keys = pkcs8_keys;
|
||||
keys.append(&mut rsa_keys);
|
||||
if keys.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"No private keys found - Make sure that they are in PKCS#8/PEM format",
|
||||
));
|
||||
}
|
||||
keys.drain(..).map(PrivateKey).collect()
|
||||
};
|
||||
|
||||
let mut server_config = certs_keys
|
||||
.into_iter()
|
||||
.find_map(|certs_key| {
|
||||
let server_config_builder = ServerConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_no_client_auth();
|
||||
if let Ok(found_config) = server_config_builder.with_single_cert(certs.clone(), certs_key) {
|
||||
Some(found_config)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Unable to find a valid certificate and key",
|
||||
)
|
||||
})?;
|
||||
|
||||
#[cfg(feature = "h3")]
|
||||
{
|
||||
server_config.alpn_protocols = vec![
|
||||
b"h3".to_vec(),
|
||||
b"hq-29".to_vec(), // quinn draft example TODO: remove later
|
||||
b"h2".to_vec(),
|
||||
b"http/1.1".to_vec(),
|
||||
];
|
||||
}
|
||||
#[cfg(not(feature = "h3"))]
|
||||
{
|
||||
server_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
}
|
||||
|
||||
// server_config;
|
||||
Ok(server_config)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
use crate::error::*;
|
||||
|
||||
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
|
||||
pub enum UpstreamOption {
|
||||
OverrideHost,
|
||||
// TODO: Adds more options for heder override
|
||||
}
|
||||
impl TryFrom<&str> for UpstreamOption {
|
||||
type Error = anyhow::Error;
|
||||
fn try_from(val: &str) -> Result<Self> {
|
||||
match val {
|
||||
"override_host" => Ok(Self::OverrideHost),
|
||||
_ => Err(anyhow!("Unsupported header option")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,6 @@
|
|||
mod backend;
|
||||
mod backend_opt;
|
||||
#[cfg(feature = "h3")]
|
||||
mod proxy_h3;
|
||||
mod proxy_handler;
|
||||
mod proxy_main;
|
||||
mod proxy_tls;
|
||||
mod utils_headers;
|
||||
mod utils_request;
|
||||
mod utils_synth_response;
|
||||
|
||||
pub use backend::*;
|
||||
pub use backend_opt::UpstreamOption;
|
||||
pub use proxy_main::Proxy;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ impl<T> Proxy<T>
|
|||
where
|
||||
T: Connect + Clone + Sync + Send + 'static,
|
||||
{
|
||||
pub async fn client_serve_h3(self, conn: quinn::Connecting) {
|
||||
pub async fn client_serve_h3(&self, conn: quinn::Connecting) {
|
||||
let clients_count = self.globals.clients_count.clone();
|
||||
if clients_count.increment() > self.globals.max_clients {
|
||||
clients_count.decrement();
|
||||
|
|
@ -79,7 +79,7 @@ where
|
|||
|
||||
let self_inner = self.clone();
|
||||
self.globals.runtime_handle.spawn(async move {
|
||||
if let Err(e) = self_inner.handle_request_h3(req, stream, client_addr).await {
|
||||
if let Err(e) = self_inner.handle_stream_h3(req, stream, client_addr).await {
|
||||
error!("HTTP/3 request failed: {}", e);
|
||||
}
|
||||
// // TODO: Work around for timeout
|
||||
|
|
@ -98,7 +98,7 @@ where
|
|||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_request_h3<S>(
|
||||
async fn handle_stream_h3<S>(
|
||||
self,
|
||||
req: Request<()>,
|
||||
mut stream: RequestStream<S, Bytes>,
|
||||
|
|
@ -129,7 +129,11 @@ where
|
|||
};
|
||||
|
||||
let new_req: Request<Body> = Request::from_parts(req_parts, body);
|
||||
let res = self.handle_request(new_req, client_addr).await?;
|
||||
let res = self
|
||||
.msg_handler
|
||||
.clone()
|
||||
.handle_request(new_req, client_addr, self.listening_on, self.tls_enabled)
|
||||
.await?;
|
||||
|
||||
let (new_res_parts, new_body) = res.into_parts();
|
||||
let new_res = Response::from_parts(new_res_parts, ());
|
||||
|
|
|
|||
|
|
@ -1,264 +0,0 @@
|
|||
// Highly motivated by https://github.com/felipenoris/hyper-reverse-proxy
|
||||
use super::{utils_headers::*, utils_request::*, utils_synth_response::*, Proxy, Upstream};
|
||||
use crate::{constants::*, error::*, log::*};
|
||||
use hyper::{
|
||||
client::connect::Connect,
|
||||
header::{self, HeaderValue},
|
||||
http::uri::Scheme,
|
||||
Body, Request, Response, StatusCode, Uri, Version,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io::copy_bidirectional;
|
||||
|
||||
impl<T> Proxy<T>
|
||||
where
|
||||
T: Connect + Clone + Sync + Send + 'static,
|
||||
{
|
||||
pub async fn handle_request(
|
||||
self,
|
||||
mut req: Request<Body>,
|
||||
client_addr: SocketAddr, // アクセス制御用
|
||||
) -> Result<Response<Body>> {
|
||||
req.log(&client_addr, Some("(Incoming)"));
|
||||
|
||||
// Here we start to handle with server_name
|
||||
// Find backend application for given server_name, and drop if incoming request is invalid as request.
|
||||
// let (server_name, _port) = parse_host_port(&req)?;
|
||||
let server_name_bytes = req.parse_host()?.to_ascii_lowercase();
|
||||
|
||||
let backend = if let Some(be) = self.backends.apps.get(&server_name_bytes) {
|
||||
be
|
||||
} else if let Some(default_server_name) = &self.backends.default_server_name {
|
||||
debug!("Serving by default app");
|
||||
self.backends.apps.get(default_server_name).unwrap()
|
||||
} else {
|
||||
// info!("{} => {}", request_log, StatusCode::SERVICE_UNAVAILABLE);
|
||||
return http_error(StatusCode::SERVICE_UNAVAILABLE);
|
||||
};
|
||||
|
||||
// Redirect to https if !tls_enabled and redirect_to_https is true
|
||||
if !self.tls_enabled && backend.https_redirection.unwrap_or(false) {
|
||||
debug!("Redirect to secure connection: {}", &backend.server_name);
|
||||
// info!("{} => {}", request_log, StatusCode::PERMANENT_REDIRECT);
|
||||
return secure_redirection(&backend.server_name, self.globals.https_port, &req);
|
||||
}
|
||||
|
||||
///////////////////////
|
||||
// Find reverse proxy for given path and choose one of upstream host
|
||||
// TODO: More flexible path matcher
|
||||
let path = req.uri().path();
|
||||
let upstream = if let Some(upstream) = backend.reverse_proxy.upstream.get(path) {
|
||||
upstream
|
||||
} else if let Some(default_upstream) = &backend.reverse_proxy.default_upstream {
|
||||
default_upstream
|
||||
} else {
|
||||
return http_error(StatusCode::NOT_FOUND);
|
||||
};
|
||||
let upstream_scheme_host = if let Some(u) = upstream.get() {
|
||||
u
|
||||
} else {
|
||||
return http_error(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
};
|
||||
///////////////////////
|
||||
|
||||
// Upgrade in request header
|
||||
let upgrade_in_request = extract_upgrade(req.headers());
|
||||
let request_upgraded = req.extensions_mut().remove::<hyper::upgrade::OnUpgrade>();
|
||||
|
||||
// Build request from destination information
|
||||
let req_forwarded = if let Ok(req) = self.generate_request_forwarded(
|
||||
&client_addr,
|
||||
req,
|
||||
upstream_scheme_host,
|
||||
&upgrade_in_request,
|
||||
upstream,
|
||||
) {
|
||||
req
|
||||
} else {
|
||||
error!("Failed to generate destination uri for reverse proxy");
|
||||
return http_error(StatusCode::SERVICE_UNAVAILABLE);
|
||||
};
|
||||
// debug!("Request to be forwarded: {:?}", req_forwarded);
|
||||
req_forwarded.log(&client_addr, Some("Forwarding"));
|
||||
|
||||
// Forward request to
|
||||
let mut res_backend = match self.forwarder.request(req_forwarded).await {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("Failed to get response from backend: {}", e);
|
||||
return http_error(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
};
|
||||
debug!("Response from backend: {:?}", res_backend.status());
|
||||
// let response_log = res_backend.status().to_string();
|
||||
|
||||
if res_backend.status() == StatusCode::SWITCHING_PROTOCOLS {
|
||||
// Handle StatusCode::SWITCHING_PROTOCOLS in response
|
||||
let upgrade_in_response = extract_upgrade(res_backend.headers());
|
||||
if if let (Some(u_req), Some(u_res)) =
|
||||
(upgrade_in_request.as_ref(), upgrade_in_response.as_ref())
|
||||
{
|
||||
u_req.to_ascii_lowercase() == u_res.to_ascii_lowercase()
|
||||
} else {
|
||||
false
|
||||
} {
|
||||
if let Some(request_upgraded) = request_upgraded {
|
||||
let mut response_upgraded = res_backend
|
||||
.extensions_mut()
|
||||
.remove::<hyper::upgrade::OnUpgrade>()
|
||||
.ok_or_else(|| anyhow!("Response does not have an upgrade extension"))? // TODO: any response code?
|
||||
.await?;
|
||||
// TODO: H3で死ぬことがある
|
||||
// thread 'rpxy' panicked at 'Failed to upgrade request: hyper::Error(User(ManualUpgrade))', src/proxy/proxy_handler.rs:124:63
|
||||
tokio::spawn(async move {
|
||||
let mut request_upgraded = request_upgraded.await.map_err(|e| {
|
||||
error!("Failed to upgrade request: {}", e);
|
||||
anyhow!("Failed to upgrade request: {}", e)
|
||||
})?; // TODO: any response code?
|
||||
copy_bidirectional(&mut response_upgraded, &mut request_upgraded)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Coping between upgraded connections failed: {}", e))?; // TODO: any response code?
|
||||
Ok(()) as Result<()>
|
||||
});
|
||||
// info!("{} => {}", request_log, response_log);
|
||||
Ok(res_backend)
|
||||
} else {
|
||||
error!("Request does not have an upgrade extension");
|
||||
// info!("{} => {}", request_log, StatusCode::BAD_REQUEST);
|
||||
http_error(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
} else {
|
||||
error!(
|
||||
"Backend tried to switch to protocol {:?} when {:?} was requested",
|
||||
upgrade_in_response, upgrade_in_request
|
||||
);
|
||||
// info!("{} => {}", request_log, StatusCode::SERVICE_UNAVAILABLE);
|
||||
http_error(StatusCode::SERVICE_UNAVAILABLE)
|
||||
}
|
||||
} else {
|
||||
// Generate response to client
|
||||
if self.generate_response_forwarded(&mut res_backend).is_ok() {
|
||||
// info!("{} => {}", request_log, response_log);
|
||||
Ok(res_backend)
|
||||
} else {
|
||||
// info!("{} => {}", request_log, StatusCode::BAD_GATEWAY);
|
||||
http_error(StatusCode::BAD_GATEWAY)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////
|
||||
// Functions to generate messages
|
||||
|
||||
fn generate_response_forwarded<B: core::fmt::Debug>(
|
||||
&self,
|
||||
response: &mut Response<B>,
|
||||
) -> Result<()> {
|
||||
let headers = response.headers_mut();
|
||||
remove_hop_header(headers);
|
||||
remove_connection_header(headers);
|
||||
append_header_entry_with_comma(
|
||||
headers,
|
||||
"server",
|
||||
&format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),
|
||||
)?;
|
||||
#[cfg(feature = "h3")]
|
||||
{
|
||||
if self.globals.http3 {
|
||||
if let Some(port) = self.globals.https_port {
|
||||
append_header_entry_with_comma(
|
||||
headers,
|
||||
header::ALT_SVC.as_str(),
|
||||
&format!(
|
||||
"h3=\":{}\"; ma={}, h3-29=\":{}\"; ma={}",
|
||||
port, H3_ALT_SVC_MAX_AGE, port, H3_ALT_SVC_MAX_AGE
|
||||
),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_request_forwarded<B: core::fmt::Debug>(
|
||||
&self,
|
||||
client_addr: &SocketAddr,
|
||||
mut req: Request<B>,
|
||||
upstream_scheme_host: &Uri,
|
||||
upgrade: &Option<String>,
|
||||
upstream: &Upstream,
|
||||
) -> Result<Request<B>> {
|
||||
debug!("Generate request to be forwarded");
|
||||
|
||||
// Add te: trailer if contained in original request
|
||||
let te_trailers = {
|
||||
if let Some(te) = req.headers().get(header::TE) {
|
||||
te.as_bytes()
|
||||
.split(|v| v == &b',' || v == &b' ')
|
||||
.any(|x| x == "trailers".as_bytes())
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
let headers = req.headers_mut();
|
||||
// delete headers specified in header.connection
|
||||
remove_connection_header(headers);
|
||||
// delete hop headers including header.connection
|
||||
remove_hop_header(headers);
|
||||
// X-Forwarded-For
|
||||
add_forwarding_header(headers, client_addr, self.tls_enabled, &self.globals)?;
|
||||
|
||||
// Add te: trailer if te_trailer
|
||||
if te_trailers {
|
||||
headers.insert(header::TE, "trailer".parse()?);
|
||||
}
|
||||
|
||||
// add "host" header of original server_name if not exist (default)
|
||||
if req.headers().get(header::HOST).is_none() {
|
||||
let org_host = req
|
||||
.uri()
|
||||
.host()
|
||||
.ok_or_else(|| anyhow!("Invalid request"))?
|
||||
.to_owned();
|
||||
req
|
||||
.headers_mut()
|
||||
.insert(header::HOST, HeaderValue::from_str(&org_host)?);
|
||||
};
|
||||
|
||||
// apply upstream-specific headers given in upstream_option
|
||||
let headers = req.headers_mut();
|
||||
apply_upstream_options_to_header(headers, client_addr, upstream_scheme_host, upstream)?;
|
||||
|
||||
// update uri in request
|
||||
ensure!(upstream_scheme_host.authority().is_some() && upstream_scheme_host.scheme().is_some());
|
||||
let new_uri = Uri::builder()
|
||||
.scheme(upstream_scheme_host.scheme().unwrap().as_str())
|
||||
.authority(upstream_scheme_host.authority().unwrap().as_str());
|
||||
let pq = req.uri().path_and_query();
|
||||
*req.uri_mut() = match pq {
|
||||
None => new_uri,
|
||||
Some(x) => new_uri.path_and_query(x.to_owned()),
|
||||
}
|
||||
.build()?;
|
||||
|
||||
// upgrade
|
||||
if let Some(v) = upgrade {
|
||||
req.headers_mut().insert("upgrade", v.parse()?);
|
||||
req
|
||||
.headers_mut()
|
||||
.insert(header::CONNECTION, HeaderValue::from_str("upgrade")?);
|
||||
}
|
||||
|
||||
// Change version to http/1.1 when destination scheme is http
|
||||
if req.version() != Version::HTTP_11 && upstream_scheme_host.scheme() == Some(&Scheme::HTTP) {
|
||||
*req.version_mut() = Version::HTTP_11;
|
||||
} else if req.version() == Version::HTTP_3 {
|
||||
debug!("HTTP/3 is currently unsupported for request to upstream. Use HTTP/2.");
|
||||
*req.version_mut() = Version::HTTP_2;
|
||||
}
|
||||
|
||||
Ok(req)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,6 @@
|
|||
// use super::proxy_handler::handle_request;
|
||||
use super::Backends;
|
||||
use crate::{error::*, globals::Globals, log::*};
|
||||
use hyper::{
|
||||
client::connect::Connect, server::conn::Http, service::service_fn, Body, Client, Request,
|
||||
};
|
||||
use crate::{error::*, globals::Globals, log::*, msg_handler::HttpMessageHandler};
|
||||
use hyper::{client::connect::Connect, server::conn::Http, service::service_fn, Body, Request};
|
||||
use std::{net::SocketAddr, sync::Arc};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncWrite},
|
||||
|
|
@ -40,8 +37,7 @@ where
|
|||
{
|
||||
pub listening_on: SocketAddr,
|
||||
pub tls_enabled: bool, // TCP待受がTLSかどうか
|
||||
pub backends: Arc<Backends>,
|
||||
pub forwarder: Arc<Client<T>>,
|
||||
pub msg_handler: HttpMessageHandler<T>,
|
||||
pub globals: Arc<Globals>,
|
||||
}
|
||||
|
||||
|
|
@ -59,13 +55,21 @@ where
|
|||
return;
|
||||
}
|
||||
|
||||
// let handler_inner = self.msg_handler.clone();
|
||||
self.globals.runtime_handle.clone().spawn(async move {
|
||||
tokio::time::timeout(
|
||||
self.globals.timeout + Duration::from_secs(1),
|
||||
server
|
||||
.serve_connection(
|
||||
stream,
|
||||
service_fn(move |req: Request<Body>| self.clone().handle_request(req, peer_addr)),
|
||||
service_fn(move |req: Request<Body>| {
|
||||
self.msg_handler.clone().handle_request(
|
||||
req,
|
||||
peer_addr,
|
||||
self.listening_on,
|
||||
self.tls_enabled,
|
||||
)
|
||||
}),
|
||||
)
|
||||
.with_upgrades(),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
use super::{
|
||||
proxy_main::{LocalExecutor, Proxy},
|
||||
ServerNameLC,
|
||||
};
|
||||
use crate::{constants::*, error::*, log::*};
|
||||
use super::proxy_main::{LocalExecutor, Proxy};
|
||||
use crate::{backend::ServerNameLC, constants::*, error::*, log::*};
|
||||
#[cfg(feature = "h3")]
|
||||
use futures::StreamExt;
|
||||
use futures::{future::FutureExt, select};
|
||||
|
|
@ -24,7 +21,7 @@ where
|
|||
info!("Start cert watch service");
|
||||
loop {
|
||||
let mut hm_server_config = HashMap::<ServerNameLC, Arc<ServerConfig>>::default();
|
||||
for (server_name_bytes, backend) in self.backends.apps.iter() {
|
||||
for (server_name_bytes, backend) in self.globals.backends.apps.iter() {
|
||||
if backend.tls_cert_key_path.is_some() && backend.tls_cert_path.is_some() {
|
||||
match backend.update_server_config().await {
|
||||
Err(_e) => {
|
||||
|
|
@ -137,6 +134,7 @@ where
|
|||
// TODO: Work around to initially serve incoming connection
|
||||
// かなり適当。エラーが出たり出なかったり。原因がわからない…
|
||||
let next = self
|
||||
.globals
|
||||
.backends
|
||||
.apps
|
||||
.iter()
|
||||
|
|
@ -152,6 +150,7 @@ where
|
|||
std::str::from_utf8(initial_app_name)
|
||||
);
|
||||
let backend_serve = self
|
||||
.globals
|
||||
.backends
|
||||
.apps
|
||||
.get(initial_app_name)
|
||||
|
|
|
|||
|
|
@ -1,156 +0,0 @@
|
|||
use super::{Upstream, UpstreamOption};
|
||||
use crate::{error::*, globals::Globals, log::*, utils::*};
|
||||
use bytes::BufMut;
|
||||
use hyper::{
|
||||
header::{self, HeaderMap, HeaderName, HeaderValue},
|
||||
Uri,
|
||||
};
|
||||
use std::{net::SocketAddr, sync::Arc};
|
||||
|
||||
////////////////////////////////////////////////////
|
||||
// Functions to manipulate headers
|
||||
|
||||
pub(super) fn apply_upstream_options_to_header(
|
||||
headers: &mut HeaderMap,
|
||||
_client_addr: &SocketAddr,
|
||||
upstream_scheme_host: &Uri,
|
||||
upstream: &Upstream,
|
||||
) -> Result<()> {
|
||||
for opt in upstream.opts.iter() {
|
||||
match opt {
|
||||
UpstreamOption::OverrideHost => {
|
||||
let upstream_host = upstream_scheme_host.host().ok_or_else(|| anyhow!("none"))?;
|
||||
headers
|
||||
.insert(header::HOST, HeaderValue::from_str(upstream_host)?)
|
||||
.ok_or_else(|| anyhow!("none"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/rfc9110
|
||||
pub(super) fn append_header_entry_with_comma(
|
||||
headers: &mut HeaderMap,
|
||||
key: &str,
|
||||
value: &str,
|
||||
) -> Result<()> {
|
||||
match headers.entry(HeaderName::from_bytes(key.as_bytes())?) {
|
||||
header::Entry::Vacant(entry) => {
|
||||
entry.insert(value.parse::<HeaderValue>()?);
|
||||
}
|
||||
header::Entry::Occupied(mut entry) => {
|
||||
// entry.append(value.parse::<HeaderValue>()?);
|
||||
let mut new_value = Vec::<u8>::with_capacity(entry.get().as_bytes().len() + 2 + value.len());
|
||||
new_value.put_slice(entry.get().as_bytes());
|
||||
new_value.put_slice(&[b',', b' ']);
|
||||
new_value.put_slice(value.as_bytes());
|
||||
entry.insert(HeaderValue::from_bytes(&new_value)?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn add_header_entry_if_not_exist(
|
||||
headers: &mut HeaderMap,
|
||||
key: impl Into<std::borrow::Cow<'static, str>>,
|
||||
value: impl Into<std::borrow::Cow<'static, str>>,
|
||||
) -> Result<()> {
|
||||
match headers.entry(HeaderName::from_bytes(key.into().as_bytes())?) {
|
||||
header::Entry::Vacant(entry) => {
|
||||
entry.insert(value.into().parse::<HeaderValue>()?);
|
||||
}
|
||||
header::Entry::Occupied(_) => (),
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn add_forwarding_header(
|
||||
headers: &mut HeaderMap,
|
||||
client_addr: &SocketAddr,
|
||||
tls: bool,
|
||||
globals: &Arc<Globals>, // TODO: Fix
|
||||
) -> Result<()> {
|
||||
// default process
|
||||
// optional process defined by upstream_option is applied in fn apply_upstream_options
|
||||
append_header_entry_with_comma(
|
||||
headers,
|
||||
"x-forwarded-for",
|
||||
&client_addr.to_canonical().ip().to_string(),
|
||||
)?;
|
||||
|
||||
/////////// As Nginx
|
||||
// If we receive X-Forwarded-Proto, pass it through; otherwise, pass along the
|
||||
// scheme used to connect to this server
|
||||
add_header_entry_if_not_exist(
|
||||
headers,
|
||||
"x-forwarded-proto",
|
||||
if tls { "https" } else { "http" },
|
||||
)?;
|
||||
// If we receive X-Forwarded-Port, pass it through; otherwise, pass along the
|
||||
// server port the client connected to
|
||||
add_header_entry_if_not_exist(
|
||||
headers,
|
||||
"x-forwarded-port",
|
||||
if tls {
|
||||
globals.https_port.unwrap().to_string()
|
||||
} else {
|
||||
globals.http_port.unwrap().to_string()
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn remove_connection_header(headers: &mut HeaderMap) {
|
||||
if let Some(values) = headers.get(header::CONNECTION) {
|
||||
if let Ok(v) = values.clone().to_str() {
|
||||
for m in v.split(',') {
|
||||
if !m.is_empty() {
|
||||
headers.remove(m.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const HOP_HEADERS: &[&str] = &[
|
||||
"connection",
|
||||
"te",
|
||||
"trailer",
|
||||
"keep-alive",
|
||||
"proxy-connection",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
];
|
||||
|
||||
pub(super) fn remove_hop_header(headers: &mut HeaderMap) {
|
||||
HOP_HEADERS.iter().for_each(|key| {
|
||||
headers.remove(*key);
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn extract_upgrade(headers: &HeaderMap) -> Option<String> {
|
||||
if let Some(c) = headers.get(header::CONNECTION) {
|
||||
if c
|
||||
.to_str()
|
||||
.unwrap_or("")
|
||||
.split(',')
|
||||
.into_iter()
|
||||
.any(|w| w.trim().to_ascii_lowercase() == header::UPGRADE.as_str().to_ascii_lowercase())
|
||||
{
|
||||
if let Some(u) = headers.get(header::UPGRADE) {
|
||||
if let Ok(m) = u.to_str() {
|
||||
debug!("Upgrade in request header: {}", m);
|
||||
return Some(m.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
use crate::{error::*, log::*, utils::*};
|
||||
use hyper::{header, Request};
|
||||
use std::fmt::Display;
|
||||
|
||||
////////////////////////////////////////////////////
|
||||
// Functions of utils for request messages
|
||||
pub trait MsgLog {
|
||||
fn log<T: Display + ToCanonical>(self, src: &T, extra: Option<&str>);
|
||||
}
|
||||
impl<B> MsgLog for &Request<B> {
|
||||
fn log<T: Display + ToCanonical>(self, src: &T, extra: Option<&str>) {
|
||||
let canonical_src = src.to_canonical();
|
||||
|
||||
let server_name = self.headers().get(header::HOST).map_or_else(
|
||||
|| {
|
||||
self
|
||||
.uri()
|
||||
.authority()
|
||||
.map_or_else(|| "<none>", |au| au.as_str())
|
||||
},
|
||||
|h| h.to_str().unwrap_or("<none>"),
|
||||
);
|
||||
info!(
|
||||
"{} <- {} -- {} {:?} {:?} {:?} {}",
|
||||
server_name,
|
||||
canonical_src,
|
||||
self.method(),
|
||||
self.version(),
|
||||
self
|
||||
.uri()
|
||||
.path_and_query()
|
||||
.map_or_else(|| "", |v| v.as_str()),
|
||||
self.headers(),
|
||||
extra.map_or_else(|| "", |v| v)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ParseHost {
|
||||
fn parse_host(&self) -> Result<&[u8]>;
|
||||
}
|
||||
impl<B> ParseHost for Request<B> {
|
||||
fn parse_host(&self) -> Result<&[u8]> {
|
||||
let headers_host = self.headers().get(header::HOST);
|
||||
let uri_host = self.uri().host();
|
||||
// let uri_port = self.uri().port_u16();
|
||||
|
||||
ensure!(
|
||||
!(headers_host.is_none() && uri_host.is_none()),
|
||||
"No host in request header"
|
||||
);
|
||||
|
||||
// prioritize server_name in uri
|
||||
uri_host.map_or_else(
|
||||
|| {
|
||||
let m = headers_host.unwrap().as_bytes();
|
||||
if m.starts_with(&[b'[']) {
|
||||
println!("v6 bracket");
|
||||
// v6 address with bracket case. if port is specified, always it is in this case.
|
||||
let mut iter = m.split(|ptr| ptr == &b'[' || ptr == &b']');
|
||||
iter.next().ok_or_else(|| anyhow!("Invalid Host"))?; // first item is always blank
|
||||
iter.next().ok_or_else(|| anyhow!("Invalid Host"))
|
||||
} else if m.len() - m.split(|v| v == &b':').fold(0, |acc, s| acc + s.len()) >= 2 {
|
||||
println!("v6 non-bracket");
|
||||
// v6 address case, if 2 or more ':' is contained
|
||||
Ok(m)
|
||||
} else {
|
||||
// v4 address or hostname
|
||||
m.split(|colon| colon == &b':')
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("Invalid Host"))
|
||||
}
|
||||
},
|
||||
|v| Ok(v.as_bytes()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
// Highly motivated by https://github.com/felipenoris/hyper-reverse-proxy
|
||||
use crate::error::*;
|
||||
use hyper::{Body, Request, Response, StatusCode, Uri};
|
||||
|
||||
////////////////////////////////////////////////////
|
||||
// Functions to create response (error or redirect)
|
||||
|
||||
pub(super) fn http_error(status_code: StatusCode) -> Result<Response<Body>> {
|
||||
let response = Response::builder()
|
||||
.status(status_code)
|
||||
.body(Body::empty())?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub(super) fn secure_redirection<B>(
|
||||
server_name: &str,
|
||||
tls_port: Option<u16>,
|
||||
req: &Request<B>,
|
||||
) -> Result<Response<Body>> {
|
||||
let pq = match req.uri().path_and_query() {
|
||||
Some(x) => x.as_str(),
|
||||
_ => "",
|
||||
};
|
||||
let new_uri = Uri::builder().scheme("https").path_and_query(pq);
|
||||
let dest_uri = match tls_port {
|
||||
Some(443) | None => new_uri.authority(server_name),
|
||||
Some(p) => new_uri.authority(format!("{}:{}", server_name, p)),
|
||||
}
|
||||
.build()?;
|
||||
let response = Response::builder()
|
||||
.status(StatusCode::MOVED_PERMANENTLY)
|
||||
.header("Location", dest_uri.to_string())
|
||||
.body(Body::empty())?;
|
||||
Ok(response)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue