commit 8ff1aca4deaf3e41e50358a2b63e9ab2dde3b06d Author: Xory Date: Sat Sep 28 21:39:16 2024 +0300 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fffb2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1f79329 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "whitehole" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/README.md b/README.md new file mode 100644 index 0000000..59c3b96 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# whitehole +A no-bullshit broccoli-like file hosting server. + +## Usage +In development environment: `cargo r -- [targetdir]` where `[targetdir]` is the directory you want to host. +In production: `whitehole [targetdir]` where `[targetdir]` is the directory you want to host. diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..0b58d6f --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,25 @@ +use std::path::Path; +use std::net::{TcpStream, Shutdown}; +use std::io::{Read, Write}; +use std::fs; + +pub fn handle_client(mut connection: TcpStream, target_dir: &String) -> std::io::Result<()> { + let mut buffer = vec![0 as u8; 1024]; // Little bit of wiggle room. + connection.read(&mut buffer)?; + let header = String::from_utf8_lossy(&buffer).to_string(); + println!("{header}"); + if !header.starts_with("GET") { + connection.shutdown(Shutdown::Both)?; + println!("ion wanna hear it"); + return Ok(()) + } + let client_desired_file_path = format!("{}/{}", target_dir, &header.split(" ").collect::>()[1][1..]); // Your code is not optimised if it doesn't make an inexperienced rustdev have a heart attack. + dbg!(&client_desired_file_path); + // let file_size: usize = fs::metadata(client_desired_file_path)?.len().try_into().unwrap(); + // let mut buffer = vec![0 as u8; file_size]; // Nuke the buffer. + let mut response: Vec = String::from("HTTP/1.1 200 OK").into_bytes(); + let mut file_contents = fs::read(&client_desired_file_path)?; + response.append(&mut file_contents); + connection.write(&response)?; + Ok(()) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..90e7f09 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,19 @@ +use std::net; +use std::path::Path; +use whitehole::handle_client; + +fn main() -> std::io::Result<()> { + let args = &std::env::args().collect::>()[1..]; + let target_dir = Path::new(&args[0]); + if !target_dir.is_dir() { + panic!("Target is not a directory"); + } + + let listener = net::TcpListener::bind("0.0.0.0:23898")?; // Alphanumerical for "WHIH" or + // "Whitehole". No idea why I did + // this. + for connection in listener.incoming() { + handle_client(connection?, &args[0])?; // See lib.rs for handle_client() + } + Ok(()) +}