From 3353989e7e20ceb7ca5980aca4c72e4bad37a825 Mon Sep 17 00:00:00 2001 From: Johann150 Date: Sun, 24 Jan 2021 20:31:47 +0100 Subject: [PATCH] add log_line to RequestHandle There are still some problems with this, the error handling in handle_request will have to be changed to accomodated the new log_line. --- src/main.rs | 51 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/src/main.rs b/src/main.rs index bea9ab5..e05d512 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ use { borrow::Cow, error::Error, ffi::OsStr, + fmt::Write, fs::File, io::BufReader, net::SocketAddr, @@ -119,19 +120,37 @@ fn check_path(s: String) -> Result { struct RequestHandle { pub stream: TlsStream, + pub log_line: String, } /// Handle a single client session (request + response). async fn handle_request(stream: TcpStream) -> Result { + let log_line = format!( + "{} {}", + stream.local_addr().unwrap(), + if ARGS.log_ips { + stream + .peer_addr() + .expect("could not get peer address") + .to_string() + } else { + // Do not log IP address, but something else so columns still line up. + "-".into() + } + ); + let stream = TLS.accept(stream).await?; - let mut handle = RequestHandle { stream }; + let mut handle = RequestHandle { stream, log_line }; match parse_request(&mut handle).await { Ok(url) => send_response(url, &mut handle).await?, Err((status, msg)) => send_header(&mut handle, status, msg).await?, } handle.stream.shutdown().await?; + + log::info!("{}", handle.log_line); + Ok(()) } @@ -171,20 +190,9 @@ async fn parse_request(handle: &mut RequestHandle) -> std::result::Result Result { } async fn send_header(handle: &mut RequestHandle, status: u8, meta: &str) -> Result { - use std::fmt::Write; - let mut response = String::with_capacity(64); - write!(response, "{} {}", status, meta)?; - log::info!("Responding with status {:?}", response); - response.push_str("\r\n"); - handle.stream.write_all(response.as_bytes()).await?; + // add response status and response meta + write!(handle.log_line, " {} \"{}\"", status, meta)?; + + handle + .stream + .write_all(format!("{} {}\r\n", status, meta).as_bytes()) + .await?; Ok(()) }