Compare commits
14 Commits
26712c8433
...
c_rewrite
Author | SHA1 | Date | |
---|---|---|---|
9adeaa8ff9
|
|||
2e22186952
|
|||
feee7b53cc
|
|||
8ba1b04f08
|
|||
54d0b65300
|
|||
3a6ce349d9
|
|||
684306c25c
|
|||
1f467994f7
|
|||
7853b4d2df
|
|||
cf48dc3e1c
|
|||
d5b4dcedd6
|
|||
0fd7795ace
|
|||
6472b0a278
|
|||
bb2e683f20
|
@ -1,3 +0,0 @@
|
|||||||
target/
|
|
||||||
debug/
|
|
||||||
**/*.rs.bk
|
|
14
.gitignore
vendored
14
.gitignore
vendored
@ -1,12 +1,2 @@
|
|||||||
# ---> Rust
|
libhttp.a
|
||||||
# Generated by Cargo
|
http_server
|
||||||
# will have compiled files and executables
|
|
||||||
debug/
|
|
||||||
target/
|
|
||||||
|
|
||||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
|
||||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
|
||||||
# Cargo.lock
|
|
||||||
|
|
||||||
# These are backup files generated by rustfmt
|
|
||||||
**/*.rs.bk
|
|
||||||
|
58
Cargo.lock
generated
58
Cargo.lock
generated
@ -1,58 +0,0 @@
|
|||||||
# This file is automatically @generated by Cargo.
|
|
||||||
# It is not intended for manual editing.
|
|
||||||
version = 4
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "http_server"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"mime_guess",
|
|
||||||
"signal-hook",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "libc"
|
|
||||||
version = "0.2.171"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "mime"
|
|
||||||
version = "0.3.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "mime_guess"
|
|
||||||
version = "2.0.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
|
|
||||||
dependencies = [
|
|
||||||
"mime",
|
|
||||||
"unicase",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "signal-hook"
|
|
||||||
version = "0.3.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"signal-hook-registry",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "signal-hook-registry"
|
|
||||||
version = "1.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicase"
|
|
||||||
version = "2.8.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539"
|
|
@ -1,8 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "http_server"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
signal-hook = "0.3.17"
|
|
||||||
mime_guess = "2.0.5"
|
|
35
Dockerfile
35
Dockerfile
@ -1,35 +0,0 @@
|
|||||||
FROM rust:1.85-slim-bookworm AS build
|
|
||||||
|
|
||||||
# get x86_64-unknown-linux-musl as a build target
|
|
||||||
RUN rustup target add x86_64-unknown-linux-musl
|
|
||||||
|
|
||||||
# create a new empty shell project
|
|
||||||
RUN USER=root cargo new --bin http_server
|
|
||||||
WORKDIR /http_server
|
|
||||||
|
|
||||||
# copy over your manifests
|
|
||||||
COPY ./Cargo.lock ./Cargo.lock
|
|
||||||
COPY ./Cargo.toml ./Cargo.toml
|
|
||||||
|
|
||||||
# this build step will cache your dependencies
|
|
||||||
RUN cargo build --release
|
|
||||||
RUN rm src/*.rs
|
|
||||||
|
|
||||||
# copy your source tree
|
|
||||||
COPY ./src ./src
|
|
||||||
|
|
||||||
# build for release as a static-pie linked binary
|
|
||||||
RUN rm ./target/release/deps/http_server*
|
|
||||||
ENV RUSTFLAGS='-C target-feature=+crt-static'
|
|
||||||
RUN cargo build --release --target x86_64-unknown-linux-musl
|
|
||||||
RUN strip /http_server/target/x86_64-unknown-linux-musl/release/http_server
|
|
||||||
|
|
||||||
FROM scratch
|
|
||||||
|
|
||||||
# copy the build artifact from the build stage
|
|
||||||
COPY --from=build /http_server/target/x86_64-unknown-linux-musl/release/http_server /
|
|
||||||
COPY ./www /www
|
|
||||||
|
|
||||||
EXPOSE 8080
|
|
||||||
|
|
||||||
CMD ["/http_server"]
|
|
8
Makefile
Normal file
8
Makefile
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
.POSIX:
|
||||||
|
server: server.c libhttp.a
|
||||||
|
gcc -I . -L. -ansi -ggdb -o http_server server.c -lstrops -Wl,-Bstatic -lhttp -Wl,-Bdynamic
|
||||||
|
|
||||||
|
libhttp.a: http.c
|
||||||
|
gcc -c -ansi -ggdb -o http.o http.c -lstrops
|
||||||
|
ar cr libhttp.a http.o
|
||||||
|
rm http.o
|
15
compose.yml
15
compose.yml
@ -1,15 +0,0 @@
|
|||||||
networks:
|
|
||||||
http-network:
|
|
||||||
name: http-network
|
|
||||||
driver: bridge
|
|
||||||
|
|
||||||
services:
|
|
||||||
http-server:
|
|
||||||
container_name: http-server
|
|
||||||
build: .
|
|
||||||
image: http-server:latest
|
|
||||||
restart: always
|
|
||||||
ports:
|
|
||||||
- 80:8080
|
|
||||||
networks:
|
|
||||||
- http-network
|
|
104
http.c
Normal file
104
http.c
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
#include "http.h"
|
||||||
|
#include <strops.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
/* TODO: https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable */
|
||||||
|
int http_init(int port, int connection_amount) {
|
||||||
|
int ret;
|
||||||
|
int server_sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
if (server_sock == -1) {
|
||||||
|
perror("Couldn't create socket");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct sockaddr_in server_addr;
|
||||||
|
server_addr.sin_family = AF_INET;
|
||||||
|
server_addr.sin_addr.s_addr = INADDR_ANY;
|
||||||
|
server_addr.sin_port = htons(port);
|
||||||
|
|
||||||
|
if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof server_addr) == -1) {
|
||||||
|
perror("Couldn't bind socket");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (listen(server_sock, connection_amount) == -1) {
|
||||||
|
perror("Cannot listen on socket");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return server_sock;
|
||||||
|
}
|
||||||
|
|
||||||
|
HTTP_Request* http_accept(int server) {
|
||||||
|
int client_sock = accept(server, NULL, NULL);
|
||||||
|
if (client_sock == -1) {
|
||||||
|
perror("Couldn't connect to client");
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
HTTP_Request *request = malloc(sizeof(HTTP_Request));
|
||||||
|
request->client_sock = client_sock;
|
||||||
|
|
||||||
|
/* TODO: Read entire message and parse into request struct */
|
||||||
|
ssize_t bytes_read;
|
||||||
|
size_t bufsize = 4096;
|
||||||
|
char buf[bufsize];
|
||||||
|
|
||||||
|
bytes_read = read(request->client_sock, buf, bufsize - 1);
|
||||||
|
if (bytes_read == -1) {
|
||||||
|
perror("Failed to read data");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* TODO: read tmp line by line */
|
||||||
|
char *tmp = strops_trim_left_string(buf, "\r\n");
|
||||||
|
size_t lines_count = 0;
|
||||||
|
size_t lines_capacity = 10;
|
||||||
|
char **lines = malloc(lines_capacity * sizeof (char*));
|
||||||
|
size_t i;
|
||||||
|
while (strops_length(tmp) > 0) {
|
||||||
|
char *line = malloc(strops_length(tmp));
|
||||||
|
memset(line, 0, strops_length(tmp));
|
||||||
|
for (i = 0; i < strops_length(tmp); i++) {
|
||||||
|
if (tmp[i] == '\r' && tmp[i + 1] == '\n') {
|
||||||
|
i += 2;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
line[i] = tmp[i];
|
||||||
|
}
|
||||||
|
for (; i > 0; i--) {
|
||||||
|
strops_remove_at_pos_char_inplace(tmp, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lines_count >= lines_capacity) {
|
||||||
|
lines_capacity *= 2;
|
||||||
|
lines = realloc(lines, lines_capacity * sizeof (char*));
|
||||||
|
}
|
||||||
|
lines[lines_count] = line;
|
||||||
|
lines_count++;
|
||||||
|
}
|
||||||
|
free(tmp);
|
||||||
|
/* TODO: Parse lines */
|
||||||
|
/* TODO: find suitable data structure for field-lines */
|
||||||
|
/*
|
||||||
|
request-line => method target version
|
||||||
|
seperated by whitespace (SP)
|
||||||
|
|
||||||
|
field-line => field-name:field-value
|
||||||
|
seperated by a single colon => ':'
|
||||||
|
field-value may have leading and trailing optionial whitespace (OWS)
|
||||||
|
*/
|
||||||
|
for (i = 0; i < lines_count; i++) {
|
||||||
|
printf("%s\n", lines[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* TODO: remeber to delete this code after finishing parsing code */
|
||||||
|
for (i = lines_count; i > 0; i--) {
|
||||||
|
free(lines[i]);
|
||||||
|
}
|
||||||
|
free(lines);
|
||||||
|
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
26
http.h
Normal file
26
http.h
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
#ifndef HTTP_H
|
||||||
|
#define HTTP_H
|
||||||
|
|
||||||
|
#include <netinet/in.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int client_sock;
|
||||||
|
char *method;
|
||||||
|
char *target;
|
||||||
|
char *version;
|
||||||
|
/* Field_Lines (Header) */
|
||||||
|
char *body;
|
||||||
|
} HTTP_Request;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
char *version;
|
||||||
|
unsigned int status;
|
||||||
|
/* Field_Lines (Header) */
|
||||||
|
char *body;
|
||||||
|
} HTTP_Response;
|
||||||
|
|
||||||
|
int http_init(int port, int connection_amount);
|
||||||
|
HTTP_Request* http_accept(int server);
|
||||||
|
|
||||||
|
#endif /* HTTP_H */
|
13
internal/server-info.html
Normal file
13
internal/server-info.html
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>server-info</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Server written by AustrianToast</h1>
|
||||||
|
<a href="https://gitea.hopeless-cloud.xyz/AustrianToast/http_server">Source code</a>
|
||||||
|
<br>
|
||||||
|
<a href="mailto:austriantoast@hopeless-cloud.xyz">AustrianToasts e-mail</a>
|
||||||
|
</body>
|
||||||
|
</html>
|
48
server.c
Normal file
48
server.c
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
#include <strops.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <errno.h>
|
||||||
|
|
||||||
|
#include "http.h"
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#define PORT 8080
|
||||||
|
|
||||||
|
HTTP_Response* handle_client(HTTP_Request *request) {
|
||||||
|
ssize_t bytes_written;
|
||||||
|
|
||||||
|
char *response = "HTTP/1.1 200 \r\n\r\n";
|
||||||
|
bytes_written = write(request->client_sock, response, strops_length(response));
|
||||||
|
if (bytes_written != strops_length(response)) {
|
||||||
|
fprintf(stderr, "Incomplete write\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
TODO: implement signals
|
||||||
|
TODO: graceful server shutdown
|
||||||
|
*/
|
||||||
|
int main() {
|
||||||
|
int ret;
|
||||||
|
int server;
|
||||||
|
server = http_init(PORT, 3);
|
||||||
|
if (server == -1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
HTTP_Request *request;
|
||||||
|
while(1) {
|
||||||
|
request = http_accept(server);
|
||||||
|
if (request == NULL) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
handle_client(request);
|
||||||
|
close(request->client_sock);
|
||||||
|
free(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
close(server);
|
||||||
|
return 0;
|
||||||
|
}
|
450
src/main.rs
450
src/main.rs
@ -1,450 +0,0 @@
|
|||||||
use signal_hook::{consts::*, iterator::Signals};
|
|
||||||
use std::{
|
|
||||||
collections::HashMap,
|
|
||||||
error::Error,
|
|
||||||
fs::{self},
|
|
||||||
io::{BufRead, BufReader, Write},
|
|
||||||
net::{TcpListener, TcpStream},
|
|
||||||
path::PathBuf,
|
|
||||||
process::exit,
|
|
||||||
thread,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
|
|
||||||
enum RequestMethods {
|
|
||||||
NULL = -1, // This is only to initialise the struct
|
|
||||||
GET,
|
|
||||||
HEAD,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct StartLine {
|
|
||||||
method: RequestMethods,
|
|
||||||
target: String,
|
|
||||||
version: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StartLine {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
method: RequestMethods::NULL,
|
|
||||||
target: String::new(),
|
|
||||||
version: String::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// https://datatracker.ietf.org/doc/html/rfc9110#name-methods
|
|
||||||
pub fn is_valid_method(method: &str) -> bool {
|
|
||||||
if method.trim().is_empty() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only GET and HEAD are required, the rest is optional
|
|
||||||
["GET", "HEAD"].contains(&method.trim())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: make the checks less shit and actually correct
|
|
||||||
// https://datatracker.ietf.org/doc/html/rfc9112#name-request-target
|
|
||||||
pub fn is_valid_target(target: &str) -> bool {
|
|
||||||
if target.trim().is_empty() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// origin-form
|
|
||||||
if target.starts_with("/") {
|
|
||||||
if target.contains("?") && target.split("?").count() != 2 {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// absolute-form
|
|
||||||
if target.starts_with("http://") {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// authority-form
|
|
||||||
if target.contains(":") && target.split(":").count() == 2 {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// asterisk-form
|
|
||||||
if target.trim() == "*" {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_valid_version(version: &str) -> bool {
|
|
||||||
if version.trim().is_empty() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let http_name = version.trim();
|
|
||||||
|
|
||||||
if http_name.starts_with("HTTP/") {
|
|
||||||
let version_numbers = http_name.trim_start_matches("HTTP/");
|
|
||||||
let version_numbers = version_numbers.split(".").collect::<Vec<&str>>();
|
|
||||||
if version_numbers.len() != 2 {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let major = match version_numbers[0].parse::<u8>() {
|
|
||||||
Ok(val) => val,
|
|
||||||
Err(_) => {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let minor = match version_numbers[1].parse::<u8>() {
|
|
||||||
Ok(val) => val,
|
|
||||||
Err(_) => {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if major <= 9 && minor <= 9 {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_start_line(input: &str) -> Result<StartLine, Vec<u8>> {
|
|
||||||
let mut response_field_lines: HashMap<String, String> = HashMap::new();
|
|
||||||
let mut response_body: Vec<u8> = vec![];
|
|
||||||
let mut start_line = StartLine::new();
|
|
||||||
let vec = input.trim().split_ascii_whitespace().collect::<Vec<&str>>();
|
|
||||||
|
|
||||||
if vec.len() != 3 {
|
|
||||||
format!(
|
|
||||||
"The start-line has an incorrect amount of items. Got the value: {}",
|
|
||||||
vec.len()
|
|
||||||
)
|
|
||||||
.as_bytes()
|
|
||||||
.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 ",
|
|
||||||
Some(response_field_lines),
|
|
||||||
Some(response_body),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let method = vec[0];
|
|
||||||
let target = vec[1];
|
|
||||||
let version = vec[2];
|
|
||||||
|
|
||||||
if StartLine::is_valid_method(&method)
|
|
||||||
&& StartLine::is_valid_target(&target)
|
|
||||||
&& StartLine::is_valid_version(&version)
|
|
||||||
{
|
|
||||||
// start_line.method will remain RequestMethods::NULL if it is not supported.
|
|
||||||
match method {
|
|
||||||
"GET" => start_line.method = RequestMethods::GET,
|
|
||||||
"HEAD" => start_line.method = RequestMethods::HEAD,
|
|
||||||
_ => start_line.method = RequestMethods::NULL,
|
|
||||||
}
|
|
||||||
|
|
||||||
start_line.target = target.to_string();
|
|
||||||
|
|
||||||
if version == "HTTP/1.1" || version == "HTTP/1.0" {
|
|
||||||
start_line.version = version.to_string();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err(response_builder(
|
|
||||||
RequestMethods::HEAD,
|
|
||||||
"HTTP/1.1 400 ",
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(start_line)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_field_lines(
|
|
||||||
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();
|
|
||||||
|
|
||||||
// Read field-lines till I hit an empty line
|
|
||||||
loop {
|
|
||||||
let mut line = String::new();
|
|
||||||
reader.read_line(&mut line).unwrap();
|
|
||||||
|
|
||||||
if !line.ends_with("\r\n") {
|
|
||||||
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 ",
|
|
||||||
Some(response_field_lines),
|
|
||||||
Some(response_body),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
if line.trim().is_empty() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
let field_line = match line.split_once(":") {
|
|
||||||
Some(val) => val,
|
|
||||||
None => {
|
|
||||||
b"Invalid field-line"
|
|
||||||
.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 ",
|
|
||||||
Some(response_field_lines),
|
|
||||||
Some(response_body),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
field_lines.insert(field_line.0.to_owned(), field_line.1.trim().to_owned());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !field_lines.contains_key(&String::from("Host")) {
|
|
||||||
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 ",
|
|
||||||
Some(response_field_lines),
|
|
||||||
Some(response_body),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(field_lines);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn response_builder(
|
|
||||||
method: RequestMethods,
|
|
||||||
status_line: &str,
|
|
||||||
field_lines: Option<HashMap<String, String>>,
|
|
||||||
body: Option<Vec<u8>>,
|
|
||||||
) -> Vec<u8> {
|
|
||||||
let mut response: Vec<u8> = vec![];
|
|
||||||
|
|
||||||
status_line
|
|
||||||
.as_bytes()
|
|
||||||
.iter()
|
|
||||||
.for_each(|byte| response.push(*byte));
|
|
||||||
response.push(b'\r');
|
|
||||||
response.push(b'\n');
|
|
||||||
|
|
||||||
match field_lines {
|
|
||||||
Some(val) => {
|
|
||||||
for field_line in val.iter() {
|
|
||||||
field_line
|
|
||||||
.0
|
|
||||||
.as_bytes()
|
|
||||||
.iter()
|
|
||||||
.for_each(|byte| response.push(*byte));
|
|
||||||
|
|
||||||
response.push(b':');
|
|
||||||
response.push(b' ');
|
|
||||||
|
|
||||||
field_line
|
|
||||||
.1
|
|
||||||
.as_bytes()
|
|
||||||
.iter()
|
|
||||||
.for_each(|byte| response.push(*byte));
|
|
||||||
|
|
||||||
response.push(b'\r');
|
|
||||||
response.push(b'\n');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => (),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mandatory empty line between header and body
|
|
||||||
response.push(b'\r');
|
|
||||||
response.push(b'\n');
|
|
||||||
|
|
||||||
if method != RequestMethods::HEAD {
|
|
||||||
match body {
|
|
||||||
Some(val) => {
|
|
||||||
val.iter().for_each(|byte| response.push(*byte));
|
|
||||||
response.push(b'\r');
|
|
||||||
response.push(b'\n');
|
|
||||||
}
|
|
||||||
None => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_get_file(start_line: &StartLine, _field_lines: &HashMap<String, String>) -> Vec<u8> {
|
|
||||||
let mut response_field_lines: HashMap<String, String> = HashMap::new();
|
|
||||||
let mut response_body: Vec<u8> = vec![];
|
|
||||||
|
|
||||||
let path: PathBuf = match start_line.target.as_str() {
|
|
||||||
"/" => PathBuf::from("/www/index.html"),
|
|
||||||
_ => PathBuf::from(format!("/www{}", start_line.target)),
|
|
||||||
};
|
|
||||||
|
|
||||||
// TODO: Check if wanted file is contained in the optional Accept field-line
|
|
||||||
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept for reference
|
|
||||||
// let mime_type = match MimeGuess::from_path(&path).first_raw() {
|
|
||||||
// Some(val) => val,
|
|
||||||
// _ => {
|
|
||||||
// return response_builder(RequestMethods::HEAD, "HTTP/1.1 500 ", None, None);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
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(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let mime_type = mime_guess::from_path(&path)
|
|
||||||
.first_raw()
|
|
||||||
.expect("Could not guess mime-type from path");
|
|
||||||
response_field_lines.insert(String::from("Content-Type"), mime_type.to_string());
|
|
||||||
|
|
||||||
response_builder(
|
|
||||||
start_line.method,
|
|
||||||
"HTTP/1.1 200 ",
|
|
||||||
Some(response_field_lines),
|
|
||||||
Some(response_body),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Err(_) => response_builder(start_line.method, "HTTP/1.1 404 ", None, None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_request(mut stream: TcpStream) -> Result<(), Box<dyn Error>> {
|
|
||||||
let mut line = String::new();
|
|
||||||
let mut reader = BufReader::new(&mut stream);
|
|
||||||
let mut response_field_lines: HashMap<String, String> = HashMap::new();
|
|
||||||
let mut response_body: Vec<u8> = vec![];
|
|
||||||
|
|
||||||
// Request can have one or many empty lines preceding the start-line and I will ignore these
|
|
||||||
loop {
|
|
||||||
if reader.read_line(&mut line)? > 2 && line != "\r\n" {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if line.ends_with(" ") {
|
|
||||||
b"There is whitespace between the start-line and the first field-line"
|
|
||||||
.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(
|
|
||||||
RequestMethods::GET,
|
|
||||||
"HTTP/1.1 400 ",
|
|
||||||
Some(response_field_lines),
|
|
||||||
Some(response_body),
|
|
||||||
);
|
|
||||||
stream.write_all(&response)?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let start_line = match parse_start_line(&line) {
|
|
||||||
Ok(val) => val,
|
|
||||||
Err(response) => {
|
|
||||||
stream.write_all(&response)?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
dbg!(&start_line);
|
|
||||||
|
|
||||||
let field_lines = match parse_field_lines(&mut reader) {
|
|
||||||
Ok(val) => val,
|
|
||||||
Err(response) => {
|
|
||||||
stream.write_all(&response)?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
dbg!(&field_lines);
|
|
||||||
|
|
||||||
// let mut request_body: Vec<u8> = vec![];
|
|
||||||
// reader.read_to_end(&mut request_body)?;
|
|
||||||
|
|
||||||
let response = match start_line.target.as_str() {
|
|
||||||
// For docker healtcheck. If the server can properly respond, then it must be healthy.
|
|
||||||
"/server-health" => response_builder(RequestMethods::HEAD, "HTTP/1.1 200 ", None, None),
|
|
||||||
"/server-stats" => response_builder(start_line.method, "HTTP/1.1 404 ", None, None),
|
|
||||||
"/server-info" => response_builder(start_line.method, "HTTP/1.1 404 ", None, None),
|
|
||||||
_ => try_get_file(&start_line, &field_lines),
|
|
||||||
};
|
|
||||||
stream.write_all(&response)?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn Error>> {
|
|
||||||
let mut signals = Signals::new([SIGINT, SIGTERM])?;
|
|
||||||
|
|
||||||
// TODO: Gracefully shutdown server
|
|
||||||
thread::spawn(move || {
|
|
||||||
for sig in signals.forever() {
|
|
||||||
println!("Received signal {:?}", sig);
|
|
||||||
println!("Shutting down");
|
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let listener = TcpListener::bind("0.0.0.0:8080")?;
|
|
||||||
|
|
||||||
println!("Server started");
|
|
||||||
|
|
||||||
for stream in listener.incoming() {
|
|
||||||
let stream = stream?;
|
|
||||||
handle_request(stream)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
Reference in New Issue
Block a user