Dir list works but needs cleaned up

This commit is contained in:
int 80h
2020-04-21 20:56:54 -04:00
parent 4056cbbc2f
commit 6e71a4194a

View File

@@ -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<String, io::Error> {
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<TcpStream>,
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?;