From 6e71a4194a534a59b3830bdd505b6c9643482d43 Mon Sep 17 00:00:00 2001 From: int 80h Date: Tue, 21 Apr 2020 20:56:54 -0400 Subject: [PATCH] Dir list works but needs cleaned up --- src/main.rs | 53 +++++++++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8d422c5..fc7861a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,12 +5,12 @@ extern crate serde_derive; use futures_util::future::TryFutureExt; use std::collections::HashMap; use std::error::Error; -use std::fs::File; use std::fs; +use std::fs::File; use std::io::{self, BufReader}; use std::net::ToSocketAddrs; -use std::sync::Arc; use std::path::{Path, PathBuf}; +use std::sync::Arc; use tokio::io::AsyncWriteExt; use tokio::net::TcpListener; use tokio::net::TcpStream; @@ -35,29 +35,13 @@ fn get_tls_config(cfg: config::Config) -> rustls::ServerConfig { } fn get_content(mut path: PathBuf, u: url::Url) -> Result { - println!("URL: {}", u); - if u.path() == "" || u.path() == "/" { - path.push("index.gemini"); - } else { - path.push(u.path().trim_start_matches("/")); - } - - if !u.path().ends_with("/") { - u.path().to_string().push('/'); - } - println!("{}", path.to_str().unwrap()); - - if !path.exists() { - return Ok("51 Not found!\r\n".to_string()) - } let meta = fs::metadata(&path).expect("Unable to read metadata"); if meta.is_file() { return Ok(std::fs::read_to_string(path).expect("Unable to read file")); } + let mut list = String::from("# Directory Listing\n\n"); - if !u.path().ends_with("/") { - path.push(format!("{}/", u.path().trim_start_matches("/"))); - } + // needs work for file in fs::read_dir(path)? { if let Ok(file) = file { let f = file.file_name().to_str().unwrap().to_owned(); @@ -73,13 +57,11 @@ async fn handle_connection( mut stream: TlsStream, cfg: config::Config, ) -> Result<(), io::Error> { - let mut buffer = [0; 512]; stream.read(&mut buffer).await?; let request = String::from_utf8_lossy(&buffer[..]).to_owned(); println!("Request: {}", request); - let url = Url::parse(&request).unwrap(); if url.scheme() != "gemini" { @@ -101,12 +83,35 @@ async fn handle_connection( } } - let p = PathBuf::from(dir); + let mut path = PathBuf::from(dir); + if url.path() != "" || url.path() != "/" { + path.push(url.path().trim_start_matches("/")); + } + + if !path.exists() { + stream.write_all(&b"51\tNot found!\r\n"[..]).await?; + stream.flush().await?; + return Ok(()); + } + + // add error + let meta = fs::metadata(&path).expect("Unable to read metadata"); + if meta.is_dir() { + if !url.path().ends_with("/") { + stream + .write_all(format!("31\t{}/\r\n", url).as_bytes()) + .await?; + stream.flush().await?; + } + if path.join("index.gemini").exists() { + path.push("index.gemini"); + } + } stream.write_all(&b"20\ttext/gemini\r\n"[..]).await?; stream.flush().await?; - let content = get_content(p, url)?; + let content = get_content(path, url)?; stream.write_all(content.as_bytes()).await?; stream.flush().await?;