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

View file

@ -87,7 +87,7 @@ fn handle_connection(mut stream: TcpStream) {
}
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;
};
let request = Request::parse(request);
@ -95,6 +95,8 @@ fn handle_request(request: &str, stream: &mut TcpStream) -> bool {
let mut end_connection = true;
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);
let head_only = request.method == Method::Head;
let path = request.path.clone();
@ -111,12 +113,12 @@ fn handle_request(request: &str, stream: &mut TcpStream) -> bool {
})
.format(head_only);
} else {
println!("[{client_ip}] bad request");
println!("[{socket_addr}] bad request");
response = Response::new(Status::BadRequest).format(false);
}
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
}