port as number

pull/1/head
dvkt 5 years ago
parent 1708db9ffa
commit a902c0870c

@ -11,14 +11,20 @@ fn main() {
let mut root = "."; let mut root = ".";
let mut iter = args.iter(); let mut iter = args.iter();
let mut host = "localhost"; let mut host = "localhost";
let mut port = "70"; let mut port = 70;
while let Some(arg) = iter.next() { while let Some(arg) = iter.next() {
match arg.as_ref() { match arg.as_ref() {
"--version" | "-v" | "-version" => return print_version(), "--version" | "-v" | "-version" => return print_version(),
"--help" | "-help" => return print_help(), "--help" | "-help" => return print_help(),
"--port" | "-p" | "-port" => { "--port" | "-p" | "-port" => {
if let Some(p) = iter.next() { if let Some(p) = iter.next() {
port = p; port = p
.parse()
.map_err(|_| {
eprintln!("bad port: {}", p);
process::exit(1)
})
.unwrap();
} }
} }
"-h" => { "-h" => {

@ -10,129 +10,138 @@ use threadpool::ThreadPool;
const MAX_WORKERS: usize = 10; const MAX_WORKERS: usize = 10;
const MAX_PEEK_SIZE: usize = 1024; const MAX_PEEK_SIZE: usize = 1024;
const TCP_BUF_SIZE: usize = 1024;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#[derive(Debug)]
pub struct Request { pub struct Request {
stream: TcpStream,
selector: String, selector: String,
root: String, root: String,
host: String, host: String,
port: String, port: u16,
} }
/// Starts a Gopher server at the specified root directory. impl Request {
pub fn start(host: &str, port: &str, root_dir: &str) -> Result<()> { pub fn from(host: &str, port: u16, root: &str) -> Result<Request> {
Ok(Request {
host: host.into(),
port: port,
root: fs::canonicalize(root)?.to_string_lossy().into(),
selector: String::new(),
})
}
/// Path to the target file on disk requested by this request.
pub fn file_path(&self) -> String {
let mut path = self.root.to_string();
path.push_str(self.selector.replace("..", ".").trim_start_matches('/'));
path
}
/// Path to the target file relative to the server root.
pub fn relative_file_path(&self) -> String {
self.file_path().replace(&self.root, "")
}
}
/// Starts a Gopher server at the specified host, port, and root directory.
pub fn start(host: &str, port: u16, root: &str) -> Result<()> {
let addr = format!("{}:{}", host, port); let addr = format!("{}:{}", host, port);
let listener = TcpListener::bind(&addr)?; let listener = TcpListener::bind(&addr)?;
let full_root_path = fs::canonicalize(&root_dir)?.to_string_lossy().to_string(); let full_root_path = fs::canonicalize(&root)?.to_string_lossy().to_string();
println!("-> Listening on {} at {}", addr, full_root_path);
let pool = ThreadPool::new(MAX_WORKERS); let pool = ThreadPool::new(MAX_WORKERS);
println!("-> Listening on {} at {}", addr, full_root_path);
for stream in listener.incoming() { for stream in listener.incoming() {
let stream = stream?; let stream = stream?;
println!("-> Connection from: {}", stream.peer_addr()?); println!("-> Connection from: {}", stream.peer_addr()?);
let mut req = Request::from( let req = Request::from(host, port, root)?;
stream,
root_dir.to_string(),
host.to_string(),
port.to_string(),
);
pool.execute(move || { pool.execute(move || {
if let Err(e) = req.serve() { if let Err(e) = accept(stream, req) {
eprintln!("-> {}", e); eprintln!("-! {}", e);
} }
}); });
} }
Ok(()) Ok(())
} }
impl Request { /// Reads from the client and responds.
pub fn from(stream: TcpStream, root: String, host: String, port: String) -> Request { fn accept(stream: TcpStream, mut req: Request) -> Result<()> {
Request { let reader = BufReader::new(&stream);
stream, let mut lines = reader.lines();
root, if let Some(Ok(line)) = lines.next() {
host, println!("-> Received: {:?}", line);
port, req.selector = line;
selector: String::new(), write_response(&stream, req)?;
}
}
pub fn root_path_as_string(&self) -> Result<String> {
Ok(fs::canonicalize(&self.root)?.to_string_lossy().to_string())
} }
Ok(())
}
pub fn path(&self) -> Result<PathBuf> { /// Writes a response to a client based on a Request.
let mut path = fs::canonicalize(&self.root)?; fn write_response<'a, W>(w: &'a W, req: Request) -> Result<()>
path.push(self.selector.replace("..", ".").trim_start_matches('/')); where
Ok(path) &'a W: Write,
{
println!("file_path: {}", req.file_path());
let md = fs::metadata(&req.file_path())?;
if md.is_file() {
write_text(w, req)
} else if md.is_dir() {
write_dir(w, req)
} else {
Ok(())
} }
}
pub fn path_as_string(&self) -> Result<String> { /// Send a directory listing (menu) to the client based on a Request.
let mut path = self fn write_dir<'a, W>(w: &'a W, req: Request) -> Result<()>
.path()? where
.to_string_lossy() &'a W: Write,
.to_string() {
.replace(&self.root_path_as_string()?, ""); let mut dir = fs::read_dir(&req.file_path())?;
let mut menu = GopherMenu::with_write(w);
let rel_path = req.relative_file_path();
while let Some(Ok(entry)) = dir.next() {
let mut path = rel_path.clone();
if !path.ends_with('/') { if !path.ends_with('/') {
path.push('/'); path.push('/');
} }
Ok(path) let file_name = entry.file_name();
} path.push_str(&file_name.to_string_lossy());
println!(
/// Reads from the client and responds. "file_type: {:?}
fn serve(&mut self) -> Result<()> { file_name: {}
let reader = BufReader::new(&self.stream); path: {}
let mut lines = reader.lines(); req.host: {}
if let Some(Ok(line)) = lines.next() { req.port: {}",
println!("-> Received: {:?}", line); file_type(&entry),
self.selector = line; file_name.to_string_lossy(),
self.respond()?; path,
} req.host,
Ok(()) req.port
} );
menu.write_entry(
/// Respond to a client's request. file_type(&entry),
fn respond(&mut self) -> Result<()> { &file_name.to_string_lossy(),
let md = fs::metadata(self.path()?)?; &path,
if md.is_file() { &req.host,
write_text(&self.stream, self.path()?) req.port,
} else if md.is_dir() { )?;
self.send_dir()
} else {
Ok(())
}
}
/// Send a directory listing (menu) to the client.
fn send_dir(&mut self) -> Result<()> {
let mut dir = fs::read_dir(self.path()?)?;
let mut menu = GopherMenu::with_write(&self.stream);
let path = self.path_as_string()?;
while let Some(Ok(entry)) = dir.next() {
let mut path = path.clone();
let file_name = entry.file_name();
path.push_str(&file_name.to_string_lossy());
menu.write_entry(
file_type(&entry),
&file_name.to_string_lossy(),
&path,
&self.host,
self.port.parse()?,
)?;
}
menu.end()?;
Ok(())
} }
menu.end()?;
Ok(())
} }
/// Send a text file to the client. /// Send a text file to the client based on a Request.
fn write_text<'a, W>(mut w: &'a W, path: PathBuf) -> Result<()> fn write_text<'a, W>(mut w: &'a W, req: Request) -> Result<()>
where where
&'a W: Write, &'a W: Write,
{ {
let path = req.file_path();
let md = fs::metadata(&path)?; let md = fs::metadata(&path)?;
let mut f = fs::File::open(&path)?; let mut f = fs::File::open(&path)?;
let mut buf = [0; 1024]; let mut buf = [0; TCP_BUF_SIZE];
let mut bytes = md.len(); let mut bytes = md.len();
while bytes > 0 { while bytes > 0 {
let n = f.read(&mut buf[..])?; let n = f.read(&mut buf[..])?;

Loading…
Cancel
Save