Got it working with docker

This commit is contained in:
2025-03-18 13:13:00 +01:00
parent fa0d511bd6
commit 704a03be3d
3 changed files with 217 additions and 88 deletions

View File

@ -24,6 +24,7 @@ FROM scratch
# copy the build artifact from the build stage # copy the build artifact from the build stage
COPY --from=build /http_server/target/x86_64-unknown-linux-gnu/release/http_server / COPY --from=build /http_server/target/x86_64-unknown-linux-gnu/release/http_server /
COPY ./www /www
EXPOSE 8080 EXPOSE 8080

View File

@ -2,8 +2,10 @@ use signal_hook::{consts::*, iterator::Signals};
use std::{ use std::{
collections::HashMap, collections::HashMap,
error::Error, error::Error,
fs::{self},
io::{BufRead, BufReader, Write}, io::{BufRead, BufReader, Write},
net::{TcpListener, TcpStream}, net::{TcpListener, TcpStream},
path::PathBuf,
process::exit, process::exit,
thread, thread,
}; };
@ -120,9 +122,10 @@ fn parse_start_line(input: &str) -> Result<RequestLine, Vec<u8>> {
let mut response_body: Vec<u8> = vec![]; let mut response_body: Vec<u8> = vec![];
if input.ends_with(" ") { if input.ends_with(" ") {
for byte in b"There is whitespace between the start-line and the first field-line\r\n" { b"There is whitespace between the start-line and the first field-line"
response_body.push(*byte); .iter()
} .for_each(|byte| response_body.push(*byte));
response_field_lines.insert( response_field_lines.insert(
String::from("Content-Length"), String::from("Content-Length"),
response_body.len().to_string(), response_body.len().to_string(),
@ -133,7 +136,7 @@ fn parse_start_line(input: &str) -> Result<RequestLine, Vec<u8>> {
RequestMethods::GET, RequestMethods::GET,
"HTTP/1.1 400 Bad Request", "HTTP/1.1 400 Bad Request",
response_field_lines, response_field_lines,
response_body, Some(response_body),
)); ));
} }
@ -141,14 +144,15 @@ fn parse_start_line(input: &str) -> Result<RequestLine, Vec<u8>> {
let vec = input.trim().split_ascii_whitespace().collect::<Vec<&str>>(); let vec = input.trim().split_ascii_whitespace().collect::<Vec<&str>>();
let body = format!( let body = format!(
"The start-line has an incorrect amount of items. Got the value: {}\r\n", "The start-line has an incorrect amount of items. Got the value: {}",
vec.len() vec.len()
); );
if vec.len() != 3 { if vec.len() != 3 {
for byte in body.as_bytes() { body.as_bytes()
response_body.push(*byte); .iter()
} .for_each(|byte| response_body.push(*byte));
response_field_lines.insert( response_field_lines.insert(
String::from("Content-Length"), String::from("Content-Length"),
response_body.len().to_string(), response_body.len().to_string(),
@ -159,7 +163,7 @@ fn parse_start_line(input: &str) -> Result<RequestLine, Vec<u8>> {
RequestMethods::GET, RequestMethods::GET,
"HTTP/1.1 400 Bad Request", "HTTP/1.1 400 Bad Request",
response_field_lines, response_field_lines,
response_body, Some(response_body),
)); ));
} }
@ -174,6 +178,23 @@ fn parse_start_line(input: &str) -> Result<RequestLine, Vec<u8>> {
if method == String::from("HEAD") { if method == String::from("HEAD") {
start_line.method = RequestMethods::HEAD; start_line.method = RequestMethods::HEAD;
} }
} else {
b"Server only supports GET and HEAD"
.iter()
.for_each(|byte| response_body.push(*byte));
response_field_lines.insert(
String::from("Content-Length"),
response_body.len().to_string(),
);
response_field_lines.insert(String::from("Content-Type"), String::from("text/plain"));
return Err(response_builder(
RequestMethods::GET,
"HTTP/1.1 501 Not Implemented",
response_field_lines,
Some(response_body),
));
} }
let target = vec[1]; let target = vec[1];
@ -191,78 +212,120 @@ fn parse_start_line(input: &str) -> Result<RequestLine, Vec<u8>> {
return Ok(start_line); return Ok(start_line);
} }
fn parse_field_lines(reader: &mut BufReader<&mut TcpStream>) -> Option<HashMap<String, String>> { fn parse_field_lines(
let mut line: String; reader: &mut BufReader<&mut TcpStream>,
) -> Result<HashMap<String, String>, Vec<u8>> {
let mut response_field_lines: HashMap<String, String> = HashMap::new();
let mut response_body: Vec<u8> = vec![];
let mut field_lines: HashMap<String, String> = HashMap::new(); let mut field_lines: HashMap<String, String> = HashMap::new();
let mut is_first_line = true;
// Read field-lines till I hit an empty line // Read field-lines till I hit an empty line
loop { loop {
line = String::new(); let mut line = String::new();
reader.read_line(&mut line).unwrap(); reader.read_line(&mut line).unwrap();
if line.starts_with(" ") && is_first_line {
return None;
}
if !line.ends_with("\r\n") { if !line.ends_with("\r\n") {
return None; b"Lines need to end with a CRLF"
.iter()
.for_each(|byte| response_body.push(*byte));
response_field_lines.insert(
String::from("Content-Length"),
response_body.len().to_string(),
);
response_field_lines.insert(String::from("Content-Type"), String::from("text/plain"));
return Err(response_builder(
RequestMethods::GET,
"HTTP/1.1 400 Bad Request",
response_field_lines,
Some(response_body),
));
} }
if line.trim().is_empty() { if line.trim().is_empty() {
break; break;
} }
let field_line = line.split_once(":").expect("Shits fucked: {}"); let field_line = match line.split_once(":") {
Some(val) => val,
None => {
b"Invalid field-line"
.iter()
.for_each(|byte| response_body.push(*byte));
// Check if client has send more than one Host line response_field_lines.insert(
if field_lines.contains_key(&String::from("Host")) && field_line.0 == "Host" { String::from("Content-Length"),
return None; response_body.len().to_string(),
} );
response_field_lines
.insert(String::from("Content-Type"), String::from("text/plain"));
return Err(response_builder(
RequestMethods::GET,
"HTTP/1.1 400 Bad Request",
response_field_lines,
Some(response_body),
));
}
};
field_lines.insert(field_line.0.to_owned(), field_line.1.trim().to_owned()); field_lines.insert(field_line.0.to_owned(), field_line.1.trim().to_owned());
is_first_line = false;
} }
if !field_lines.contains_key(&String::from("Host")) { if !field_lines.contains_key(&String::from("Host")) {
return None; b"field-line with key HOST is missing"
.iter()
.for_each(|byte| response_body.push(*byte));
response_field_lines.insert(
String::from("Content-Length"),
response_body.len().to_string(),
);
response_field_lines.insert(String::from("Content-Type"), String::from("text/plain"));
return Err(response_builder(
RequestMethods::GET,
"HTTP/1.1 400 Bad Request",
response_field_lines,
Some(response_body),
));
} }
return Some(field_lines); return Ok(field_lines);
} }
fn response_builder( fn response_builder(
method: RequestMethods, method: RequestMethods,
status_line: &str, status_line: &str,
field_lines: HashMap<String, String>, field_lines: HashMap<String, String>,
body: Vec<u8>, body: Option<Vec<u8>>,
) -> Vec<u8> { ) -> Vec<u8> {
let mut response: Vec<u8> = vec![]; let mut response: Vec<u8> = vec![];
// TODO: replaces with eiter Option<T> or Result<T, T> status_line
if status_line.is_empty() { .as_bytes()
return response; .iter()
} .for_each(|byte| response.push(*byte));
for byte in status_line.as_bytes().iter() {
response.push(*byte);
}
response.push(b'\r'); response.push(b'\r');
response.push(b'\n'); response.push(b'\n');
if !field_lines.is_empty() { if !field_lines.is_empty() {
for field_line in field_lines.iter() { for field_line in field_lines.iter() {
for byte in field_line.0.as_bytes().iter() { field_line
response.push(*byte); .0
} .as_bytes()
.iter()
.for_each(|byte| response.push(*byte));
response.push(b':'); response.push(b':');
response.push(b' '); response.push(b' ');
for byte in field_line.1.as_bytes().iter() { field_line
response.push(*byte); .1
} .as_bytes()
.iter()
.for_each(|byte| response.push(*byte));
response.push(b'\r'); response.push(b'\r');
response.push(b'\n'); response.push(b'\n');
@ -273,81 +336,135 @@ fn response_builder(
response.push(b'\r'); response.push(b'\r');
response.push(b'\n'); response.push(b'\n');
if body.is_empty() { if method != RequestMethods::HEAD {
return response; match body {
} Some(val) => {
val.iter().for_each(|byte| response.push(*byte));
if method != RequestMethods::HEAD && method != RequestMethods::NULL { response.push(b'\r');
for byte in body.iter() { response.push(b'\n');
response.push(*byte); }
None => (),
} }
response.push(b'\r');
response.push(b'\n');
} }
return response; return response;
} }
fn handle_request(mut stream: TcpStream) { fn handle_request(mut stream: TcpStream) -> Result<(), Box<dyn Error>> {
let mut line = String::new(); let mut line = String::new();
let mut reader = BufReader::new(&mut stream); let mut reader = BufReader::new(&mut stream);
// Request can have one or many empty lines preceding the start-line and I will ignore these // Request can have one or many empty lines preceding the start-line and I will ignore these
loop { loop {
match reader.read_line(&mut line) { if reader.read_line(&mut line)? > 2 && line != "\r\n" {
Ok(val) => { break;
if val > 2 {
break;
}
}
// TODO: Replace with stream.write_all
Err(err) => {
eprintln!("{err}");
return;
}
};
if line != "\r\n" {
continue;
} }
} }
let start_line = match parse_start_line(&line) { let start_line = match parse_start_line(&line) {
Ok(val) => val, Ok(val) => val,
Err(response) => { Err(response) => {
stream.write_all(&response).unwrap(); stream.write_all(&response)?;
return; return Ok(());
} }
}; };
dbg!(&start_line); dbg!(&start_line);
if start_line.method == RequestMethods::NULL {
stream
.write_all(b"HTTP/1.1 501 Not Implemented\r\n\r\n")
.unwrap();
return;
}
let field_lines = match parse_field_lines(&mut reader) { let field_lines = match parse_field_lines(&mut reader) {
Some(val) => val, Ok(val) => val,
None => { Err(response) => {
stream stream.write_all(&response)?;
.write_all(b"HTTP/1.1 400 Bad Request\r\n\r\nInvalid Header") return Ok(());
.unwrap();
return;
} }
}; };
dbg!(&field_lines); dbg!(&field_lines);
// TODO: Read the body // TODO: Read the body
// let mut body: Vec<u8> = vec![]; // let mut body: Vec<u8> = vec![];
// reader.read_to_end(&mut body).unwrap(); // reader.read_to_end(&mut body)?;
// dbg!(&body); // dbg!(&body);
// TODO: Act upon the request
stream let mut response_field_lines: HashMap<String, String> = HashMap::new();
.write_all(b"HTTP/1.1 200 OK\r\n\r\nHello, World!\r\n") let mut response_body: Vec<u8> = vec![];
.unwrap();
// TODO: Act upon the request
if start_line.target == "/" {
let file = match fs::read("./www/index.html") {
Ok(val) => val,
Err(_) => {
b"The is no index.html, only you and me."
.iter()
.for_each(|byte| response_body.push(*byte));
response_field_lines.insert(
String::from("Content-Length"),
response_body.len().to_string(),
);
response_field_lines
.insert(String::from("Content-Type"), String::from("text/plain"));
let response = response_builder(
start_line.method,
"HTTP/1.1 200 OK",
response_field_lines,
Some(response_body),
);
stream.write_all(&response)?;
return Ok(());
}
};
file.iter().for_each(|byte| response_body.push(*byte));
response_field_lines.insert(String::from("Content-Length"), file.len().to_string());
response_field_lines.insert(String::from("Content-Type"), String::from("text/html"));
let response = response_builder(
start_line.method,
"HTTP/1.1 200 OK",
response_field_lines,
Some(response_body),
);
stream.write_all(&response)?;
} else {
let path: PathBuf = PathBuf::from(format!("./www{}", start_line.target));
match fs::read(path) {
Ok(val) => {
val.iter().for_each(|byte| response_body.push(*byte));
response_field_lines.insert(
String::from("Content-Length"),
response_body.len().to_string(),
);
// TODO: get mime-type of file and use that here
response_field_lines.insert(String::from("Content-Type"), String::from("*/*"));
let response = response_builder(
start_line.method,
"HTTP/1.1 200 OK",
response_field_lines,
Some(response_body),
);
stream.write_all(&response)?;
}
Err(_) => {
let response = response_builder(
start_line.method,
"HTTP/1.1 404 Not Found",
response_field_lines,
None,
);
stream.write_all(&response)?;
}
};
}
Ok(())
} }
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
@ -368,7 +485,8 @@ fn main() -> Result<(), Box<dyn Error>> {
for stream in listener.incoming() { for stream in listener.incoming() {
let stream = stream?; let stream = stream?;
handle_request(stream); handle_request(stream)?;
} }
Ok(()) Ok(())
} }

10
www/index.html Normal file
View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>http-server</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>