diff --git a/src/main.rs b/src/main.rs index 93ea0c3..d6f0fbf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -43,6 +43,8 @@ fn main() { fn start_server(ip: Ipv4Addr, port: u16) { let running_ip = SocketAddrV4::new(ip, port); + notify(&format!("Starting server on {running_ip}..."), None); - server::start(running_ip); + + let _ = server::start(running_ip); } diff --git a/src/server.rs b/src/server.rs index 7f8c7b2..63a528e 100644 --- a/src/server.rs +++ b/src/server.rs @@ -7,16 +7,18 @@ use std::thread; use urlencoding::decode; /// Simple HTTP server that opens files based on GET requests -pub fn start(address: SocketAddrV4) { - let listener = TcpListener::bind(address).unwrap(); +pub fn start(address: SocketAddrV4) -> Result<(), std::io::Error> { + let listener = TcpListener::bind(address)?; - for stream in listener.incoming() { - let stream = stream.unwrap(); - - thread::spawn(|| { - handle_connection(stream); - }); + for maybe_stream in listener.incoming() { + if let Ok(stream) = maybe_stream { + thread::spawn(|| { + handle_connection(stream); + }); + } } + + Ok(()) } /// Opens the given file and returns 200, otherwise 404 @@ -25,7 +27,9 @@ fn handle_connection(mut stream: TcpStream) { let request_line: Vec<&str> = request_line.split(' ').collect(); if let Some(request) = request_line.get(1) { - out(stream, "HTTP/1.1 200 OK", &open(request)); + if let Ok(response) = open(request) { + out(stream, "HTTP/1.1 200 OK", &response); + } } else { out(stream, "HTTP/1.1 404 NOT FOUND", ""); } @@ -40,21 +44,29 @@ fn out(mut stream: TcpStream, status: &str, contents: &str) { } /// Open an executable in wine -fn open(request: &str) -> String { - let request = decode(request).unwrap(); +fn open(request: &str) -> Result { + let Ok(request) = decode(request) else { + return Err("The request was invalid.") + }; println!("{}", request); let split = request.split("//").collect::>(); - let Output { stdout, stderr, .. } = Command::new("wine") + let Ok(Output { stdout, stderr, .. }) = Command::new("wine") .env("WINEPREFIX", split[1]) .arg(split[0]) - .output() - .unwrap(); + .output() else { + return Err("Error while trying to run the wine command.") + }; + + let Ok(stdout) = String::from_utf8(stdout) else { + return Err("The program returned invalid stdout.") + }; - let stdout = String::from_utf8(stdout).unwrap(); - let stderr = String::from_utf8(stderr).unwrap(); + let Ok(stderr) = String::from_utf8(stderr) else { + return Err("The program returned invalid stderr.") + }; - format!("stdout:\n{stdout}\nstderr:\n{stderr}") + Ok(format!("stdout:\n{stdout}\nstderr:\n{stderr}")) }