parse X-Real-IP for use behind reverse proxy

This commit is contained in:
Crispy 2024-04-27 16:36:33 +02:00
parent f3484c9473
commit 9170e7f7f8
2 changed files with 9 additions and 3 deletions

View file

@ -3,6 +3,7 @@ pub struct Request {
pub method: Method, pub method: Method,
pub path: String, pub path: String,
pub host: String, pub host: String,
pub real_ip: Option<String>,
pub range: Option<RequestRange>, pub range: Option<RequestRange>,
} }
@ -52,6 +53,7 @@ impl Request {
// parse http headers // parse http headers
let mut host = None; let mut host = None;
let mut range = None; let mut range = None;
let mut real_ip = None;
for line in lines { for line in lines {
if line.is_empty() { if line.is_empty() {
break; break;
@ -61,6 +63,7 @@ impl Request {
match key { match key {
"host" => host = Some(value.to_owned()), "host" => host = Some(value.to_owned()),
"range" => range = RequestRange::parse(value), "range" => range = RequestRange::parse(value),
"x-real-ip" => real_ip = Some(value.to_owned()),
_ => (), _ => (),
} }
} }
@ -83,6 +86,7 @@ impl Request {
method, method,
path, path,
host, host,
real_ip,
range, range,
}) })
} }

View file

@ -87,7 +87,7 @@ fn handle_connection(mut stream: TcpStream) {
} }
fn handle_request(request: &str, stream: &mut TcpStream) -> bool { fn handle_request(request: &str, stream: &mut TcpStream) -> bool {
let Ok(client_ip) = stream.peer_addr() else { let Ok(socket_addr) = stream.peer_addr() else {
return true; return true;
}; };
let request = Request::parse(request); let request = Request::parse(request);
@ -95,6 +95,8 @@ fn handle_request(request: &str, stream: &mut TcpStream) -> bool {
let mut end_connection = true; let mut end_connection = true;
if let Some(request) = request { if let Some(request) = request {
let client_ip = format!("{socket_addr}");
let client_ip = request.real_ip.as_ref().unwrap_or(&client_ip);
println!("[{client_ip}] {} {}", request.method, request.path); println!("[{client_ip}] {} {}", request.method, request.path);
let head_only = request.method == Method::Head; let head_only = request.method == Method::Head;
let path = request.path.clone(); let path = request.path.clone();
@ -111,12 +113,12 @@ fn handle_request(request: &str, stream: &mut TcpStream) -> bool {
}) })
.format(head_only); .format(head_only);
} else { } else {
println!("[{client_ip}] bad request"); println!("[{socket_addr}] bad request");
response = Response::new(Status::BadRequest).format(false); response = Response::new(Status::BadRequest).format(false);
} }
if stream.write_all(&response).is_err() || stream.flush().is_err() { if stream.write_all(&response).is_err() || stream.flush().is_err() {
println!("[{client_ip}] failed to send response"); println!("[{socket_addr}] failed to send response");
} }
end_connection end_connection
} }