tls-improvements #50

Merged
JakeHillion merged 3 commits from tls-improvements into main 2022-05-24 15:56:33 +01:00
2 changed files with 52 additions and 25 deletions

View File

@ -1,5 +1,5 @@
use std::fs; use std::fs::OpenOptions;
use std::io::{Read, Write}; use std::io::{self, ErrorKind, Read, Write};
use std::os::unix::net::UnixStream; use std::os::unix::net::UnixStream;
use std::path::PathBuf; use std::path::PathBuf;
@ -7,11 +7,15 @@ pub(super) fn handler(mut stream: UnixStream) -> i32 {
println!("entered http handler"); println!("entered http handler");
let mut buf = Vec::new(); let mut buf = Vec::new();
loop { let mut buf_len = 0;
let buf_len = buf.len();
buf.resize_with(buf_len + 1024, Default::default);
if stream.read(&mut buf[buf_len..]).unwrap() == 0 { loop {
buf.resize_with(buf_len + 4096, Default::default);
let read_bytes = stream.read(&mut buf[buf_len..]).unwrap();
buf_len += read_bytes;
if read_bytes == 0 {
break; break;
} }
@ -29,33 +33,53 @@ pub(super) fn handler(mut stream: UnixStream) -> i32 {
req.path req.path
}; };
let status_line = if filename.is_some() { if let Some(filename) = filename {
"HTTP/1.1 200 OK" if try_serve_file(&mut stream, filename).unwrap() {
} else { return exitcode::OK;
"HTTP/1.1 404 NOT FOUND" }
}; }
let contents = if let Some(filename) = filename { let status_line = "HTTP/1.1 404 NOT FOUND";
fs::read_to_string( let contents = "file not found\n";
PathBuf::from("/var/www/html/")
.join(filename.strip_prefix('/').unwrap_or(filename)),
)
.unwrap()
} else {
"content not found\n".to_string()
};
let response_header = format!( let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n", "{}\r\nContent-Length: {}\r\n\r\n{}",
status_line, status_line,
contents.len(), contents.len(),
contents
); );
stream.write_all(response_header.as_bytes()).unwrap(); stream.write_all(response.as_bytes()).unwrap();
stream.write_all(contents.as_bytes()).unwrap();
break; break;
} }
exitcode::OK exitcode::OK
} }
fn try_serve_file(stream: &mut impl io::Write, filename: &str) -> io::Result<bool> {
let mut fd = match OpenOptions::new()
.read(true)
.open(PathBuf::from("/var/www/html/").join(filename.strip_prefix('/').unwrap_or(filename)))
{
Ok(fd) => fd,
Err(e) => {
if e.kind() == ErrorKind::NotFound {
return Ok(false);
}
return Err(e);
}
};
let status_line = "HTTP/1.1 200 OK";
let response_header = format!(
"{}\r\nContent-Length: {}\r\n\r\n",
status_line,
fd.metadata()?.len(),
);
stream.write_all(response_header.as_bytes())?;
io::copy(&mut fd, stream)?;
Ok(true)
}

View File

@ -56,6 +56,9 @@ pub(crate) fn handler(
} }
} }
tls_conn.send_close_notify();
tls_conn.write_tls(&mut stream).unwrap();
exitcode::OK exitcode::OK
} }