From 09d691c5680540eb0465ca303861ec5429a2ebf1 Mon Sep 17 00:00:00 2001 From: dvkt Date: Fri, 27 Dec 2019 12:25:24 -0800 Subject: [PATCH] capture and print errors --- src/server.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/server.rs b/src/server.rs index 2b20744..bb5ce87 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,17 +1,17 @@ use async_std::{ fs, io::BufReader, - net::{TcpListener, TcpStream}, + net::{TcpListener, TcpStream, ToSocketAddrs}, + path::PathBuf, prelude::*, task, }; -use std::path::PathBuf; type Result = std::result::Result>; const MAX_PEEK_SIZE: usize = 1024; -pub fn start(addr: &str, root: &str) -> Result<()> { +pub fn start(addr: impl ToSocketAddrs, root: &str) -> Result<()> { task::block_on(async { let listener = TcpListener::bind(addr).await?; let mut incoming = listener.incoming(); @@ -19,7 +19,11 @@ pub fn start(addr: &str, root: &str) -> Result<()> { let stream = stream?; println!("-> Connection from: {}", stream.peer_addr()?); let root = root.to_string(); - task::spawn(client_loop(stream, root)); + task::spawn(async { + if let Err(e) = client_loop(stream, root).await { + eprintln!("-> {}", e); + } + }); } Ok(()) }) @@ -30,15 +34,16 @@ async fn client_loop(mut stream: TcpStream, root: String) -> Result<()> { let mut lines = reader.lines(); if let Some(Ok(line)) = lines.next().await { - println!("-> client sent: {:?}", line); + println!("-> {} sent: {:?}", stream.peer_addr()?, line); respond(&mut stream, &line, &root).await?; } Ok(()) } async fn respond(stream: &mut TcpStream, selector: &str, root: &str) -> Result<()> { - let mut path = PathBuf::from(root); - path.push(selector.replace("..", ".")); + let mut path = fs::canonicalize(root).await?; + path.push(selector.replace("..", ".").trim_start_matches('/')); + println!("path {:?}", path); let md = fs::metadata(path.clone()).await?; if md.is_file() { @@ -53,17 +58,17 @@ async fn respond(stream: &mut TcpStream, selector: &str, root: &str) -> Result<( async fn send_dir(stream: &mut TcpStream, path: PathBuf) -> Result<()> { let mut response = String::new(); let mut dir = fs::read_dir(path.clone()).await?; - while let Some(Ok(entry)) = dir.next().await { let file_type = file_type(&entry).await; + let f = entry.file_name(); + let file_name = f.to_string_lossy(); response.push_str(&format!( "{}{}\t{}\tlocalhost\t7070\r\n", - file_type, - entry.file_name().into_string().unwrap(), - entry.path().to_string_lossy(), + file_type, file_name, file_name, )); } stream.write_all(response.as_bytes()).await?; + stream.write_all(b".\r\n").await?; // end gopher response Ok(()) } @@ -77,6 +82,7 @@ async fn send_text(stream: &mut TcpStream, path: PathBuf) -> Result<()> { bytes -= n as u64; stream.write_all(&buf).await?; } + stream.write_all(b".\r\n").await?; // end gopher response Ok(()) }