You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
phd/src/server.rs

388 lines
10 KiB
Rust

4 years ago
use crate::{color, Request, Result};
use gophermap::{GopherMenu, ItemType};
use std::{
cmp::Ordering,
fs::{self, DirEntry},
io::{self, prelude::*, BufReader, Read, Write},
net::{TcpListener, TcpStream},
os::unix::fs::PermissionsExt,
4 years ago
path::Path,
process::Command,
4 years ago
str,
};
use threadpool::ThreadPool;
4 years ago
/// phd tries to be light on resources, so we only allow a low number
/// of simultaneous connections.
const MAX_WORKERS: usize = 10;
4 years ago
/// how many bytes of a file to read when trying to guess binary vs text?
4 years ago
const MAX_PEEK_SIZE: usize = 1024;
4 years ago
4 years ago
/// Files not displayed in directory listings.
const IGNORED_FILES: [&str; 3] = ["header.gph", "footer.gph", ".reverse"];
4 years ago
/// 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!("{}:{}", "0.0.0.0", port);
let listener = TcpListener::bind(&addr)?;
4 years ago
let full_root_path = fs::canonicalize(&root)?.to_string_lossy().to_string();
let pool = ThreadPool::new(MAX_WORKERS);
4 years ago
4 years ago
println!(
"{}┬ Listening {}on {}{}{} at {}{}{}",
color::Yellow,
color::Reset,
4 years ago
color::Yellow,
addr,
color::Reset,
color::Blue,
4 years ago
full_root_path,
color::Reset
);
for stream in listener.incoming() {
let stream = stream?;
4 years ago
println!(
"{}┌ Connection{} from {}{}",
color::Green,
color::Reset,
color::Magenta,
stream.peer_addr()?
);
4 years ago
let req = Request::from(host, port, root)?;
pool.execute(move || {
4 years ago
if let Err(e) = accept(stream, req) {
4 years ago
eprintln!("{}└ {}{}", color::Red, e, color::Reset);
}
});
}
Ok(())
}
4 years ago
/// Reads from the client and responds.
fn accept(stream: TcpStream, mut req: Request) -> Result<()> {
let reader = BufReader::new(&stream);
let mut lines = reader.lines();
if let Some(Ok(line)) = lines.next() {
4 years ago
println!(
"{}│{} Client sent:\t{}{:?}{}",
4 years ago
color::Green,
color::Reset,
color::Cyan,
4 years ago
line,
color::Reset
);
req.parse_request(&line);
4 years ago
write_response(&stream, req)?;
}
4 years ago
Ok(())
}
4 years ago
/// Writes a response to a client based on a Request.
4 years ago
fn write_response<'a, W>(w: &'a W, mut req: Request) -> Result<()>
4 years ago
where
&'a W: Write,
{
4 years ago
let path = req.file_path();
// check for dir.gph if we're looking for dir
let mut gph_file = path.clone();
gph_file.push_str(".gph");
4 years ago
if fs_exists(&gph_file) {
4 years ago
req.selector = req.selector.trim_end_matches('/').into();
req.selector.push_str(".gph");
return write_gophermap(w, req);
} else {
// check for index.gph if we're looking for dir
let mut index = path.clone();
4 years ago
index.push_str("/index.gph");
4 years ago
if fs_exists(&index) {
4 years ago
req.selector.push_str("/index.gph");
4 years ago
return write_gophermap(w, req);
}
}
4 years ago
let meta = match fs::metadata(&path) {
Ok(meta) => meta,
Err(_) => return write_not_found(w, req),
};
4 years ago
if path.ends_with(".gph") {
write_gophermap(w, req)
4 years ago
} else if meta.is_file() {
write_file(w, req)
4 years ago
} else if meta.is_dir() {
4 years ago
write_dir(w, req)
} else {
Ok(())
}
4 years ago
}
4 years ago
/// Send a directory listing (menu) to the client based on a Request.
fn write_dir<'a, W>(w: &'a W, req: Request) -> Result<()>
where
&'a W: Write,
{
let path = req.file_path();
4 years ago
if !fs_exists(&path) {
return write_not_found(w, req);
}
let mut header = path.clone();
4 years ago
header.push_str("/header.gph");
4 years ago
if fs_exists(&header) {
let mut sel = req.selector.clone();
4 years ago
sel.push_str("/header.gph");
write_gophermap(
w,
Request {
selector: sel,
..req.clone()
},
)?;
}
4 years ago
let mut menu = GopherMenu::with_write(w);
4 years ago
let rel_path = req.relative_file_path();
4 years ago
// show directory entries
let mut reverse = path.to_string();
reverse.push_str("/.reverse");
let paths = sort_paths(&path, fs_exists(&reverse))?;
4 years ago
for entry in paths {
4 years ago
let file_name = entry.file_name();
4 years ago
let f = file_name.to_string_lossy().to_string();
if f.chars().nth(0) == Some('.') || IGNORED_FILES.contains(&f.as_ref()) {
continue;
}
let mut path = rel_path.clone();
4 years ago
path.push('/');
4 years ago
path.push_str(&file_name.to_string_lossy());
menu.write_entry(
file_type(&entry),
&file_name.to_string_lossy(),
&path,
&req.host,
req.port,
)?;
4 years ago
}
4 years ago
let mut footer = path.clone();
footer.push_str("/footer.gph");
if fs_exists(&footer) {
let mut sel = req.selector.clone();
sel.push_str("/footer.gph");
write_gophermap(
w,
Request {
selector: sel,
..req.clone()
},
)?;
}
4 years ago
menu.end()?;
println!(
"{}│{} Server reply:\t{}DIR {}{}{}",
color::Green,
color::Reset,
color::Yellow,
color::Bold,
req.relative_file_path(),
color::Reset,
);
4 years ago
Ok(())
4 years ago
}
4 years ago
/// Send a file to the client based on a Request.
fn write_file<'a, W>(mut w: &'a W, req: Request) -> Result<()>
4 years ago
where
&'a W: Write,
{
let path = req.file_path();
let mut f = fs::File::open(&path)?;
io::copy(&mut f, &mut w)?;
println!(
"{}│{} Server reply:\t{}FILE {}{}{}",
color::Green,
color::Reset,
color::Yellow,
color::Bold,
req.relative_file_path(),
color::Reset,
);
4 years ago
Ok(())
}
4 years ago
4 years ago
/// Send a gophermap (menu) to the client based on a Request.
fn write_gophermap<'a, W>(mut w: &'a W, req: Request) -> Result<()>
where
&'a W: Write,
{
let path = req.file_path();
// Run the file and use its output as content if it's executable.
let reader = if is_executable(&path) {
4 years ago
shell(&path, &[&req.query, &req.host, &req.port.to_string()])?
} else {
fs::read_to_string(&path)?
};
4 years ago
for line in reader.lines() {
let mut line = line.trim_end_matches("\r").to_string();
4 years ago
match line.chars().filter(|&c| c == '\t').count() {
4 years ago
0 => {
// Insert `i` prefix to any prefix-less lines without tabs.
4 years ago
if line.chars().nth(0) != Some('i') {
line.insert(0, 'i');
}
line.push_str(&format!("\t(null)\t{}\t{}", req.host, req.port))
}
// Auto-add host and port to lines with just a selector.
4 years ago
1 => line.push_str(&format!("\t{}\t{}", req.host, req.port)),
2 => line.push_str(&format!("\t{}", req.port)),
_ => {}
}
line.push_str("\r\n");
w.write_all(line.as_bytes())?;
}
println!(
"{}│{} Server reply:\t{}MAP {}{}{}",
color::Green,
color::Reset,
color::Yellow,
color::Bold,
req.relative_file_path(),
color::Reset,
);
4 years ago
Ok(())
}
4 years ago
fn write_not_found<'a, W>(mut w: &'a W, req: Request) -> Result<()>
where
&'a W: Write,
{
let line = format!("3Not Found: {}\t/\tnone\t70\r\n", req.selector);
println!(
"{}│ Not found: {}{}{}",
color::Red,
color::Cyan,
req.relative_file_path(),
color::Reset,
);
4 years ago
w.write_all(line.as_bytes())?;
Ok(())
}
/// Determine the gopher type for a DirEntry on disk.
fn file_type(dir: &fs::DirEntry) -> ItemType {
4 years ago
let metadata = match dir.metadata() {
Err(_) => return ItemType::Error,
Ok(md) => md,
};
4 years ago
if metadata.is_file() {
if let Ok(file) = fs::File::open(&dir.path()) {
let mut buffer: Vec<u8> = vec![];
let _ = file.take(MAX_PEEK_SIZE as u64).read_to_end(&mut buffer);
if content_inspector::inspect(&buffer).is_binary() {
ItemType::Binary
4 years ago
} else {
ItemType::File
4 years ago
}
} else {
ItemType::Error
4 years ago
}
} else if metadata.is_dir() {
ItemType::Directory
4 years ago
} else {
ItemType::Error
4 years ago
}
}
4 years ago
/// Does the file exist? Y'know.
fn fs_exists(path: &str) -> bool {
Path::new(path).exists()
}
/// Is the file at the given path executable?
fn is_executable(path: &str) -> bool {
if let Ok(meta) = fs::metadata(path) {
meta.permissions().mode() & 0o111 != 0
} else {
false
}
}
/// Run a script and return its output.
4 years ago
fn shell(path: &str, args: &[&str]) -> Result<String> {
let output = Command::new(path).args(args).output()?;
if output.status.success() {
4 years ago
Ok(str::from_utf8(&output.stdout)?.to_string())
} else {
4 years ago
Ok(str::from_utf8(&output.stderr)?.to_string())
}
}
/// Sort directory paths: dirs first, files 2nd, version #s respected.
fn sort_paths(dir_path: &str, reverse_sort: bool) -> Result<Vec<DirEntry>> {
let mut paths: Vec<_> = fs::read_dir(dir_path)?.filter_map(|r| r.ok()).collect();
let is_dir = |entry: &fs::DirEntry| match entry.file_type() {
Ok(t) => t.is_dir(),
_ => false,
};
paths.sort_by(|a, b| {
let a_is_dir = is_dir(a);
let b_is_dir = is_dir(b);
let ord = if a_is_dir && b_is_dir || !a_is_dir && !b_is_dir {
alphanumeric_sort::compare_os_str(a.path().as_ref(), b.path().as_ref())
} else if is_dir(a) {
Ordering::Less
} else if is_dir(b) {
Ordering::Greater
} else {
Ordering::Equal // what
};
if reverse_sort {
ord.reverse()
} else {
ord
}
});
Ok(paths)
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! str_path {
($e:expr) => {
$e.path()
.to_str()
.unwrap()
.trim_start_matches("tests/sort/")
};
}
#[test]
fn test_sort_directory() {
let paths = sort_paths("tests/sort", false).unwrap();
assert_eq!(str_path!(paths[0]), "phetch-v0.1.7-linux-armv7.tar.gz");
assert_eq!(
str_path!(paths[paths.len() - 1]),
"phetch-v0.1.11-macos.zip"
);
}
#[test]
fn test_rsort_directory() {
let paths = sort_paths("tests/sort", true).unwrap();
assert_eq!(str_path!(paths[0]), "phetch-v0.1.11-macos.zip");
assert_eq!(
str_path!(paths[paths.len() - 1]),
"phetch-v0.1.7-linux-armv7.tar.gz"
);
}
}