2
0
mirror of https://github.com/xvxx/phd synced 2024-11-14 18:12:54 +00:00
phd/src/server.rs

277 lines
7.9 KiB
Rust
Raw Normal View History

2019-12-28 04:19:09 +00:00
use crate::{Request, Result};
2019-12-27 23:42:57 +00:00
use gophermap::{GopherMenu, ItemType};
2019-12-27 22:37:46 +00:00
use std::{
2019-12-28 09:13:01 +00:00
fs,
2019-12-28 22:01:14 +00:00
io::{self, prelude::*, BufReader, Read, Write},
2019-12-27 23:42:57 +00:00
net::{TcpListener, TcpStream},
2019-12-28 08:21:41 +00:00
os::unix::fs::PermissionsExt,
2019-12-28 05:06:33 +00:00
path::Path,
2019-12-28 08:21:41 +00:00
process::Command,
2019-12-28 09:13:01 +00:00
str,
2019-12-27 04:59:34 +00:00
};
2019-12-27 22:37:46 +00:00
use threadpool::ThreadPool;
2019-12-27 04:59:34 +00:00
2019-12-28 05:53:07 +00:00
/// phd tries to be light on resources, so we only allow a low number
/// of simultaneous connections.
2019-12-27 23:42:57 +00:00
const MAX_WORKERS: usize = 10;
2019-12-28 05:53:07 +00:00
/// how many bytes of a file to read when trying to guess binary vs text?
2019-12-27 05:48:29 +00:00
const MAX_PEEK_SIZE: usize = 1024;
2019-12-28 05:53:07 +00:00
2019-12-28 06:17:42 +00:00
/// Files not displayed in directory listings.
const IGNORED_FILES: [&str; 3] = ["header.gph", "footer.gph", ".reverse"];
2019-12-28 04:09:41 +00:00
/// Starts a Gopher server at the specified host, port, and root directory.
pub fn start(host: &str, port: u16, root: &str) -> Result<()> {
2019-12-27 23:42:57 +00:00
let addr = format!("{}:{}", host, port);
let listener = TcpListener::bind(&addr)?;
2019-12-28 04:09:41 +00:00
let full_root_path = fs::canonicalize(&root)?.to_string_lossy().to_string();
2019-12-27 23:42:57 +00:00
let pool = ThreadPool::new(MAX_WORKERS);
2019-12-28 04:09:41 +00:00
println!("-> Listening on {} at {}", addr, full_root_path);
2019-12-27 23:42:57 +00:00
for stream in listener.incoming() {
let stream = stream?;
println!("-> Connection from: {}", stream.peer_addr()?);
2019-12-28 04:09:41 +00:00
let req = Request::from(host, port, root)?;
2019-12-27 23:42:57 +00:00
pool.execute(move || {
2019-12-28 04:09:41 +00:00
if let Err(e) = accept(stream, req) {
eprintln!("-! {}", e);
2019-12-27 23:42:57 +00:00
}
});
}
Ok(())
}
2019-12-28 04:09:41 +00:00
/// 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() {
2019-12-28 04:28:08 +00:00
println!("-> Client sent: {:?}", line);
2019-12-28 09:13:43 +00:00
req.parse_request(&line);
2019-12-28 04:09:41 +00:00
write_response(&stream, req)?;
2019-12-27 22:37:46 +00:00
}
2019-12-28 04:09:41 +00:00
Ok(())
}
2019-12-27 22:37:46 +00:00
2019-12-28 04:09:41 +00:00
/// Writes a response to a client based on a Request.
2019-12-28 05:06:33 +00:00
fn write_response<'a, W>(w: &'a W, mut req: Request) -> Result<()>
2019-12-28 04:09:41 +00:00
where
&'a W: Write,
{
2019-12-28 05:06:33 +00:00
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");
2019-12-28 21:02:55 +00:00
if fs_exists(&gph_file) {
2019-12-28 05:06:33 +00:00
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();
2019-12-28 06:00:43 +00:00
index.push_str("/index.gph");
2019-12-28 21:02:55 +00:00
if fs_exists(&index) {
2019-12-28 06:00:43 +00:00
req.selector.push_str("/index.gph");
2019-12-28 05:06:33 +00:00
return write_gophermap(w, req);
}
}
2019-12-28 21:02:55 +00:00
let meta = match fs::metadata(&path) {
Ok(meta) => meta,
Err(_) => return write_not_found(w, req),
};
2019-12-28 05:06:33 +00:00
if path.ends_with(".gph") {
write_gophermap(w, req)
2019-12-28 21:02:55 +00:00
} else if meta.is_file() {
2019-12-28 04:27:02 +00:00
write_file(w, req)
2019-12-28 21:02:55 +00:00
} else if meta.is_dir() {
2019-12-28 04:09:41 +00:00
write_dir(w, req)
} else {
Ok(())
2019-12-27 20:58:05 +00:00
}
2019-12-28 04:09:41 +00:00
}
2019-12-27 20:58:05 +00:00
2019-12-28 04:09:41 +00:00
/// 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,
{
2019-12-28 05:37:16 +00:00
let path = req.file_path();
2019-12-28 21:02:55 +00:00
if !fs_exists(&path) {
return write_not_found(w, req);
}
2019-12-28 05:37:16 +00:00
let mut header = path.clone();
2019-12-28 05:50:26 +00:00
header.push_str("/header.gph");
2019-12-28 21:02:55 +00:00
if fs_exists(&header) {
2019-12-28 05:37:16 +00:00
let mut sel = req.selector.clone();
2019-12-28 05:50:26 +00:00
sel.push_str("/header.gph");
2019-12-28 05:37:16 +00:00
write_gophermap(
w,
Request {
selector: sel,
..req.clone()
},
)?;
}
2019-12-28 05:50:26 +00:00
let mut menu = GopherMenu::with_write(w);
2019-12-28 04:09:41 +00:00
let rel_path = req.relative_file_path();
2019-12-28 05:50:26 +00:00
// sort directory entries
let mut paths: Vec<_> = fs::read_dir(&path)?.filter_map(|r| r.ok()).collect();
2019-12-28 06:17:42 +00:00
let mut reverse = path.clone();
reverse.push_str("/.reverse");
2019-12-29 03:01:52 +00:00
let is_dir = |entry: &fs::DirEntry| match entry.file_type() {
Ok(t) => t.is_dir(),
_ => false,
};
2019-12-28 21:02:55 +00:00
if fs_exists(&reverse) {
2019-12-29 03:01:52 +00:00
paths.sort_by_key(|entry| (!is_dir(&entry), std::cmp::Reverse(entry.path())));
2019-12-28 06:17:42 +00:00
} else {
2019-12-29 03:01:52 +00:00
paths.sort_by_key(|entry| (!is_dir(&entry), entry.path()));
2019-12-28 06:17:42 +00:00
}
2019-12-28 05:50:26 +00:00
for entry in paths {
2019-12-28 04:09:41 +00:00
let file_name = entry.file_name();
2019-12-28 06:17:42 +00:00
let f = file_name.to_string_lossy().to_string();
2019-12-29 03:01:52 +00:00
if f.chars().nth(0) == Some('.') || IGNORED_FILES.contains(&f.as_ref()) {
2019-12-28 05:37:16 +00:00
continue;
}
let mut path = rel_path.clone();
2019-12-28 06:00:43 +00:00
path.push('/');
2019-12-28 04:09:41 +00:00
path.push_str(&file_name.to_string_lossy());
menu.write_entry(
file_type(&entry),
&file_name.to_string_lossy(),
&path,
&req.host,
req.port,
)?;
2019-12-27 05:56:56 +00:00
}
2019-12-29 08:19:57 +00:00
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()
},
)?;
}
2019-12-28 04:09:41 +00:00
menu.end()?;
Ok(())
2019-12-28 03:19:09 +00:00
}
2019-12-27 05:56:56 +00:00
2019-12-28 04:27:02 +00:00
/// Send a file to the client based on a Request.
fn write_file<'a, W>(mut w: &'a W, req: Request) -> Result<()>
2019-12-28 03:19:09 +00:00
where
&'a W: Write,
{
2019-12-28 22:01:14 +00:00
let mut f = fs::File::open(&req.file_path())?;
io::copy(&mut f, &mut w)?;
2019-12-28 03:19:09 +00:00
Ok(())
2019-12-27 04:59:34 +00:00
}
2019-12-27 05:48:29 +00:00
2019-12-28 05:06:33 +00:00
/// 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();
2019-12-28 08:21:41 +00:00
2019-12-28 20:17:06 +00:00
// Run the file and use its output as content if it's executable.
2019-12-28 08:21:41 +00:00
let reader = if is_executable(&path) {
2019-12-28 09:13:01 +00:00
shell(&path, &[&req.query, &req.host, &req.port.to_string()])?
2019-12-28 08:21:41 +00:00
} else {
fs::read_to_string(path)?
};
2019-12-28 05:06:33 +00:00
for line in reader.lines() {
2019-12-28 08:21:41 +00:00
let mut line = line.trim_end_matches("\r").to_string();
2019-12-28 05:06:33 +00:00
match line.chars().filter(|&c| c == '\t').count() {
2019-12-28 05:50:26 +00:00
0 => {
2019-12-28 20:17:06 +00:00
// Insert `i` prefix to any prefix-less lines without tabs.
2019-12-28 05:50:26 +00:00
if line.chars().nth(0) != Some('i') {
line.insert(0, 'i');
}
line.push_str(&format!("\t(null)\t{}\t{}", req.host, req.port))
}
2019-12-28 20:17:06 +00:00
// Auto-add host and port to lines with just a selector.
2019-12-28 05:06:33 +00:00
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())?;
}
Ok(())
}
2019-12-28 21:02:55 +00:00
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);
w.write_all(line.as_bytes())?;
Ok(())
}
2019-12-27 23:42:57 +00:00
/// Determine the gopher type for a DirEntry on disk.
fn file_type(dir: &fs::DirEntry) -> ItemType {
2019-12-28 03:19:09 +00:00
let metadata = match dir.metadata() {
Err(_) => return ItemType::Error,
Ok(md) => md,
};
2019-12-27 06:01:28 +00:00
2019-12-27 23:42:57 +00:00
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
2019-12-27 05:48:29 +00:00
} else {
2019-12-27 23:42:57 +00:00
ItemType::File
2019-12-27 05:48:29 +00:00
}
} else {
2019-12-28 20:17:06 +00:00
ItemType::Error
2019-12-27 05:48:29 +00:00
}
2019-12-27 23:42:57 +00:00
} else if metadata.is_dir() {
ItemType::Directory
2019-12-27 05:48:29 +00:00
} else {
2019-12-27 23:42:57 +00:00
ItemType::Error
2019-12-27 05:48:29 +00:00
}
}
2019-12-28 08:21:41 +00:00
2019-12-28 21:02:55 +00:00
/// Does the file exist? Y'know.
fn fs_exists(path: &str) -> bool {
Path::new(path).exists()
}
2019-12-28 08:21:41 +00:00
/// 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.
2019-12-28 09:13:01 +00:00
fn shell(path: &str, args: &[&str]) -> Result<String> {
2019-12-28 08:21:41 +00:00
let output = Command::new(path).args(args).output()?;
if output.status.success() {
2019-12-28 09:13:01 +00:00
Ok(str::from_utf8(&output.stdout)?.to_string())
2019-12-28 08:21:41 +00:00
} else {
2019-12-28 09:13:01 +00:00
Ok(str::from_utf8(&output.stderr)?.to_string())
2019-12-28 08:21:41 +00:00
}
}