Fix bad requests and cgi (add working QUERY_STRING var that generates from post message)

This commit is contained in:
g1n 2021-07-30 16:53:24 +00:00
parent 38bedc8ae7
commit 72e57a4747
1 changed files with 20 additions and 13 deletions

View File

@ -1,4 +1,5 @@
use std::fs;
use std::env;
use std::path::Path;
use std::io::prelude::*;
use std::io::ErrorKind;
@ -54,21 +55,18 @@ fn handle_connection(mut stream: TcpStream, root_dir: String) {
let request = String::from_utf8_lossy(&buffer[..]);
let parsed_request: Vec<&str> = request.split(' ').collect();
let _post: Vec<&str> = request.split('\n').collect();
let _post = _post[1].to_string();
if parsed_request.len() != 3 {
let status_line = "5 Request error";
send_response(status_line, "".to_string(), stream);
return;
}
let host = parsed_request[0];
let _host = parsed_request[0];
let _path = parsed_request[1];
let _post_len = parsed_request[2];
let mut _post = ""; // TODO: fix behaviour for post
/*
if _post_len.len() > 0 {
let _post = parsed_request[3];
} else {
let _post = "";
}*/
let get = format!( "{} {} {}\r\n {}\r\n", host, _path, _post_len, _post);
let _get_bytes = get.as_bytes();
let status_line = if Path::new(&format!("{}{}", root_dir, _path).to_string()).exists() && !_path.contains(".."){
"2 text/gemini"
} else {
@ -82,6 +80,7 @@ fn handle_connection(mut stream: TcpStream, root_dir: String) {
if Path::new(&full_path).is_file() {
_contents = fs::read_to_string(format!("{}{}", root_dir, _path)).unwrap();
if _path.contains(".sh") {
env::set_var("QUERY_STRING", _post);
let command = Command::new(format!("{}", full_path)).output().unwrap();
_contents = String::from_utf8(command.stdout).unwrap();
}
@ -89,6 +88,8 @@ fn handle_connection(mut stream: TcpStream, root_dir: String) {
exists = Path::new(&format!("{}{}/index.gmi", root_dir, _path).to_string()).exists();
if exists {
if _path.contains("..") {
let status_line = "4 Not Found";
send_response(status_line, "".to_string(), stream);
return;
}
_contents = fs::read_to_string(format!("{}{}index.gmi", root_dir, _path)).unwrap_or_else(|error| {
@ -100,6 +101,8 @@ fn handle_connection(mut stream: TcpStream, root_dir: String) {
});
} else {
if _path.contains("..") {
let status_line = "4 Not Found";
send_response(status_line, "".to_string(), stream);
return;
}
_contents = format!("=> ..\n");
@ -120,13 +123,17 @@ fn handle_connection(mut stream: TcpStream, root_dir: String) {
}
}
send_response(status_line, _contents, stream);
}
fn send_response(status_line: &str, contents: String, mut stream: TcpStream) {
let response = format!(
"{}\r\n{}",
status_line,
_contents
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}