2020-10-30 22:38:23 +00:00
|
|
|
// Static file server that can plug into the PTTH reverse server
|
|
|
|
|
2020-11-29 19:05:28 +00:00
|
|
|
// I'm not sure if I like this one
|
|
|
|
#![allow (clippy::enum_glob_use)]
|
|
|
|
|
2020-10-30 22:38:23 +00:00
|
|
|
use std::{
|
2020-11-08 18:12:45 +00:00
|
|
|
cmp::min,
|
2020-11-29 19:05:28 +00:00
|
|
|
collections::HashMap,
|
2020-11-29 23:12:56 +00:00
|
|
|
convert::{Infallible, TryFrom},
|
2020-10-30 22:38:23 +00:00
|
|
|
io::SeekFrom,
|
2020-12-20 18:04:19 +00:00
|
|
|
path::{
|
|
|
|
Path,
|
|
|
|
PathBuf,
|
|
|
|
},
|
2020-12-20 19:35:32 +00:00
|
|
|
sync::Arc,
|
2020-10-30 22:38:23 +00:00
|
|
|
};
|
|
|
|
|
2020-12-20 19:35:32 +00:00
|
|
|
use arc_swap::ArcSwap;
|
2020-10-31 02:31:03 +00:00
|
|
|
use handlebars::Handlebars;
|
2020-11-08 15:53:09 +00:00
|
|
|
use serde::Serialize;
|
2020-10-30 22:38:23 +00:00
|
|
|
use tokio::{
|
|
|
|
fs::{
|
2020-11-08 15:53:09 +00:00
|
|
|
DirEntry,
|
2020-10-30 22:38:23 +00:00
|
|
|
File,
|
|
|
|
ReadDir,
|
|
|
|
},
|
|
|
|
io::AsyncReadExt,
|
|
|
|
sync::mpsc::{
|
|
|
|
channel,
|
|
|
|
},
|
|
|
|
};
|
2020-11-08 16:00:31 +00:00
|
|
|
use tracing::instrument;
|
2020-10-30 22:38:23 +00:00
|
|
|
|
2020-11-27 00:03:11 +00:00
|
|
|
use ptth_core::{
|
2020-11-08 17:58:14 +00:00
|
|
|
http_serde::{
|
|
|
|
Method,
|
|
|
|
Response,
|
|
|
|
StatusCode,
|
|
|
|
},
|
2020-11-08 16:00:31 +00:00
|
|
|
prelude::*,
|
2020-11-08 15:53:09 +00:00
|
|
|
};
|
|
|
|
|
2020-11-29 19:19:59 +00:00
|
|
|
pub mod errors;
|
2020-12-18 20:43:34 +00:00
|
|
|
pub mod metrics;
|
|
|
|
|
2020-12-20 18:38:39 +00:00
|
|
|
mod html;
|
2020-11-29 23:12:56 +00:00
|
|
|
mod internal;
|
2020-11-29 22:56:25 +00:00
|
|
|
mod markdown;
|
2020-11-29 22:31:54 +00:00
|
|
|
mod range;
|
2020-11-29 22:12:25 +00:00
|
|
|
|
2020-11-29 22:56:25 +00:00
|
|
|
use errors::FileServerError;
|
2020-11-29 18:50:51 +00:00
|
|
|
|
2020-12-20 18:04:19 +00:00
|
|
|
#[derive (Default)]
|
|
|
|
pub struct Config {
|
|
|
|
pub file_server_root: Option <PathBuf>,
|
|
|
|
}
|
|
|
|
|
2020-12-20 18:23:17 +00:00
|
|
|
pub struct State {
|
2020-12-20 18:10:11 +00:00
|
|
|
pub config: Config,
|
2020-12-20 18:23:17 +00:00
|
|
|
pub handlebars: handlebars::Handlebars <'static>,
|
2020-12-20 19:00:22 +00:00
|
|
|
pub metrics_startup: metrics::Startup,
|
2020-12-20 19:55:20 +00:00
|
|
|
pub metrics_gauges: Arc <ArcSwap <Option <metrics::Gauges>>>,
|
2020-12-20 18:10:11 +00:00
|
|
|
pub hidden_path: Option <PathBuf>,
|
|
|
|
}
|
|
|
|
|
2020-12-15 05:15:17 +00:00
|
|
|
#[derive (Serialize)]
|
|
|
|
struct DirJson {
|
|
|
|
entries: Vec <DirEntryJson>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive (Serialize)]
|
2020-12-20 18:38:39 +00:00
|
|
|
struct DirEntryJson {
|
|
|
|
name: String,
|
|
|
|
size: u64,
|
|
|
|
is_dir: bool,
|
2020-10-31 14:35:18 +00:00
|
|
|
}
|
|
|
|
|
2020-12-15 05:15:17 +00:00
|
|
|
async fn read_dir_entry_json (entry: DirEntry) -> Option <DirEntryJson>
|
|
|
|
{
|
|
|
|
let name = entry.file_name ().into_string ().ok ()?;
|
|
|
|
let metadata = entry.metadata ().await.ok ()?;
|
|
|
|
let is_dir = metadata.is_dir ();
|
|
|
|
let size = metadata.len ();
|
|
|
|
|
|
|
|
Some (DirEntryJson {
|
|
|
|
name,
|
|
|
|
size,
|
|
|
|
is_dir,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn serve_dir_json (
|
|
|
|
mut dir: ReadDir
|
|
|
|
) -> Result <Response, FileServerError>
|
|
|
|
{
|
|
|
|
let mut entries = vec! [];
|
|
|
|
|
|
|
|
while let Ok (Some (entry)) = dir.next_entry ().await {
|
|
|
|
if let Some (entry) = read_dir_entry_json (entry).await {
|
|
|
|
entries.push (entry);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
entries.sort_unstable_by (|a, b| a.name.cmp (&b.name));
|
|
|
|
|
|
|
|
let dir = DirJson {
|
|
|
|
entries,
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut response = Response::default ();
|
|
|
|
response.header ("content-type".to_string (), "application/json; charset=UTF-8".to_string ().into_bytes ());
|
|
|
|
response.body_bytes (serde_json::to_string (&dir).unwrap ().into_bytes ());
|
|
|
|
|
|
|
|
Ok (response)
|
|
|
|
}
|
|
|
|
|
2020-11-07 01:40:29 +00:00
|
|
|
#[instrument (level = "debug", skip (f))]
|
2020-10-30 22:38:23 +00:00
|
|
|
async fn serve_file (
|
|
|
|
mut f: File,
|
|
|
|
should_send_body: bool,
|
2020-11-29 22:41:48 +00:00
|
|
|
range: range::ValidParsed
|
2020-11-08 17:58:14 +00:00
|
|
|
)
|
2020-11-29 19:47:40 +00:00
|
|
|
-> Result <Response, FileServerError>
|
2020-11-08 17:58:14 +00:00
|
|
|
{
|
2020-11-07 01:34:58 +00:00
|
|
|
let (tx, rx) = channel (1);
|
2020-10-30 22:38:23 +00:00
|
|
|
let body = if should_send_body {
|
2020-10-31 01:35:39 +00:00
|
|
|
Some (rx)
|
2020-10-30 22:38:23 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
2020-11-29 22:31:54 +00:00
|
|
|
let (range, range_requested) = (range.range, range.range_requested);
|
|
|
|
|
2020-11-08 18:12:45 +00:00
|
|
|
info! ("Serving range {}-{}", range.start, range.end);
|
2020-10-30 22:38:23 +00:00
|
|
|
|
2020-11-08 18:12:45 +00:00
|
|
|
let content_length = range.end - range.start;
|
2020-10-30 22:38:23 +00:00
|
|
|
|
2020-11-09 00:53:07 +00:00
|
|
|
let seek = SeekFrom::Start (range.start);
|
2020-11-29 19:47:40 +00:00
|
|
|
f.seek (seek).await?;
|
2020-11-09 00:53:07 +00:00
|
|
|
|
2020-10-30 22:38:23 +00:00
|
|
|
if should_send_body {
|
|
|
|
tokio::spawn (async move {
|
|
|
|
let mut tx = tx;
|
2020-11-06 18:47:04 +00:00
|
|
|
let mut bytes_sent = 0;
|
2020-11-08 18:12:45 +00:00
|
|
|
let mut bytes_left = content_length;
|
2020-10-30 22:38:23 +00:00
|
|
|
|
2020-11-09 16:33:13 +00:00
|
|
|
let mark_interval = 200_000;
|
|
|
|
let mut next_mark = mark_interval;
|
|
|
|
|
2020-10-30 22:38:23 +00:00
|
|
|
loop {
|
2020-11-29 19:05:28 +00:00
|
|
|
let mut buffer = vec! [0_u8; 65_536];
|
2020-11-29 19:59:47 +00:00
|
|
|
let bytes_read = f.read (&mut buffer).await.expect ("Couldn't read from file");
|
2020-10-30 22:38:23 +00:00
|
|
|
|
|
|
|
if bytes_read == 0 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2020-11-29 19:59:47 +00:00
|
|
|
buffer.truncate (bytes_read);
|
|
|
|
|
|
|
|
let bytes_read_64 = u64::try_from (bytes_read).expect ("Couldn't fit usize into u64");
|
|
|
|
|
|
|
|
let bytes_read_64 = min (bytes_left, bytes_read_64);
|
|
|
|
|
2020-11-07 01:40:29 +00:00
|
|
|
if tx.send (Ok::<_, Infallible> (buffer)).await.is_err () {
|
2020-11-08 18:12:45 +00:00
|
|
|
warn! ("Cancelling file stream (Sent {} out of {} bytes)", bytes_sent, content_length);
|
2020-10-30 22:38:23 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2020-11-29 19:59:47 +00:00
|
|
|
bytes_left -= bytes_read_64;
|
2020-10-30 22:38:23 +00:00
|
|
|
if bytes_left == 0 {
|
2020-11-07 23:10:01 +00:00
|
|
|
debug! ("Finished");
|
2020-10-30 22:38:23 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2020-11-29 19:59:47 +00:00
|
|
|
bytes_sent += bytes_read_64;
|
2020-11-09 16:33:13 +00:00
|
|
|
while next_mark <= bytes_sent {
|
|
|
|
trace! ("Sent {} bytes", next_mark);
|
|
|
|
next_mark += mark_interval;
|
|
|
|
}
|
2020-10-30 22:38:23 +00:00
|
|
|
|
|
|
|
//delay_for (Duration::from_millis (50)).await;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-11-08 17:58:14 +00:00
|
|
|
let mut response = Response::default ();
|
2020-10-30 22:38:23 +00:00
|
|
|
|
|
|
|
response.header (String::from ("accept-ranges"), b"bytes".to_vec ());
|
|
|
|
|
2020-11-09 00:53:07 +00:00
|
|
|
if range_requested {
|
|
|
|
response.status_code (StatusCode::PartialContent);
|
|
|
|
response.header (String::from ("content-range"), format! ("bytes {}-{}/{}", range.start, range.end - 1, range.end).into_bytes ());
|
2020-11-08 18:12:45 +00:00
|
|
|
}
|
|
|
|
else {
|
2020-11-09 00:53:07 +00:00
|
|
|
response.status_code (StatusCode::Ok);
|
|
|
|
response.header (String::from ("content-length"), range.end.to_string ().into_bytes ());
|
|
|
|
}
|
|
|
|
|
2020-11-29 19:05:28 +00:00
|
|
|
if should_send_body {
|
|
|
|
response.content_length = Some (content_length);
|
2020-10-30 22:38:23 +00:00
|
|
|
}
|
2020-11-09 00:53:07 +00:00
|
|
|
else {
|
2020-11-29 19:05:28 +00:00
|
|
|
response.status_code (StatusCode::NoContent);
|
2020-11-09 00:53:07 +00:00
|
|
|
}
|
2020-10-30 22:38:23 +00:00
|
|
|
|
|
|
|
if let Some (body) = body {
|
|
|
|
response.body (body);
|
|
|
|
}
|
|
|
|
|
2020-11-29 19:47:40 +00:00
|
|
|
Ok (response)
|
2020-10-30 22:38:23 +00:00
|
|
|
}
|
|
|
|
|
2020-12-18 20:43:34 +00:00
|
|
|
// Pass a request to the internal decision-making logic.
|
|
|
|
// When it returns, prettify it as HTML or JSON based on what the client
|
|
|
|
// asked for.
|
|
|
|
|
2020-12-20 19:55:20 +00:00
|
|
|
#[instrument (level = "debug", skip (state, headers))]
|
2020-11-08 18:12:45 +00:00
|
|
|
pub async fn serve_all (
|
2020-12-20 19:55:20 +00:00
|
|
|
state: &State,
|
2020-11-08 18:12:45 +00:00
|
|
|
root: &Path,
|
|
|
|
method: Method,
|
|
|
|
uri: &str,
|
2020-12-20 19:55:20 +00:00
|
|
|
headers: &HashMap <String, Vec <u8>>
|
2020-11-08 18:12:45 +00:00
|
|
|
)
|
2020-11-29 19:19:59 +00:00
|
|
|
-> Result <Response, FileServerError>
|
2020-11-08 18:12:45 +00:00
|
|
|
{
|
2020-12-15 05:15:17 +00:00
|
|
|
use internal::{
|
|
|
|
OutputFormat,
|
|
|
|
Response::*,
|
|
|
|
};
|
2020-11-08 18:12:45 +00:00
|
|
|
|
2020-11-29 22:56:25 +00:00
|
|
|
fn serve_error <S: Into <Vec <u8>>> (
|
|
|
|
status_code: StatusCode,
|
|
|
|
msg: S
|
|
|
|
)
|
|
|
|
-> Response
|
|
|
|
{
|
|
|
|
let mut resp = Response::default ();
|
|
|
|
resp.status_code (status_code);
|
|
|
|
resp.body_bytes (msg.into ());
|
|
|
|
resp
|
|
|
|
}
|
|
|
|
|
2020-12-20 19:55:20 +00:00
|
|
|
Ok (match internal::serve_all (root, method, uri, headers, state.hidden_path.as_ref ().map (|p| p.as_path ())).await? {
|
2020-12-15 05:15:17 +00:00
|
|
|
Favicon => serve_error (StatusCode::NotFound, "Not found\n"),
|
|
|
|
Forbidden => serve_error (StatusCode::Forbidden, "403 Forbidden\n"),
|
|
|
|
MethodNotAllowed => serve_error (StatusCode::MethodNotAllowed, "Unsupported method\n"),
|
|
|
|
NotFound => serve_error (StatusCode::NotFound, "404 Not Found\nAre you missing a trailing slash?\n"),
|
2020-11-08 18:12:45 +00:00
|
|
|
RangeNotSatisfiable (file_len) => {
|
|
|
|
let mut resp = Response::default ();
|
|
|
|
resp.status_code (StatusCode::RangeNotSatisfiable)
|
|
|
|
.header ("content-range".to_string (), format! ("bytes */{}", file_len).into_bytes ());
|
|
|
|
resp
|
|
|
|
},
|
2020-11-29 22:12:25 +00:00
|
|
|
Redirect (location) => {
|
|
|
|
let mut resp = Response::default ();
|
2020-12-15 05:15:17 +00:00
|
|
|
resp.status_code (StatusCode::TemporaryRedirect)
|
|
|
|
.header ("location".to_string (), location.into_bytes ());
|
|
|
|
resp.body_bytes (b"Redirecting...\n".to_vec ());
|
2020-11-29 22:12:25 +00:00
|
|
|
resp
|
|
|
|
},
|
2020-12-15 05:15:17 +00:00
|
|
|
InvalidQuery => serve_error (StatusCode::BadRequest, "Query is invalid for this object\n"),
|
|
|
|
|
2020-12-20 19:55:20 +00:00
|
|
|
Root => html::serve_root (state).await?,
|
2020-11-29 23:15:45 +00:00
|
|
|
ServeDir (internal::ServeDirParams {
|
2020-11-08 18:12:45 +00:00
|
|
|
path,
|
|
|
|
dir,
|
2020-12-15 05:15:17 +00:00
|
|
|
format
|
|
|
|
}) => match format {
|
|
|
|
OutputFormat::Json => serve_dir_json (dir.into_inner ()).await?,
|
2020-12-20 19:55:20 +00:00
|
|
|
OutputFormat::Html => html::serve_dir (&state.handlebars, &state.metrics_startup, path.to_string_lossy (), dir.into_inner ()).await?,
|
2020-12-15 05:15:17 +00:00
|
|
|
},
|
2020-11-29 23:15:45 +00:00
|
|
|
ServeFile (internal::ServeFileParams {
|
2020-11-08 18:12:45 +00:00
|
|
|
file,
|
|
|
|
send_body,
|
|
|
|
range,
|
2020-11-29 22:31:54 +00:00
|
|
|
}) => serve_file (file.into_inner (), send_body, range).await?,
|
2020-11-29 22:56:25 +00:00
|
|
|
MarkdownErr (e) => {
|
|
|
|
use markdown::Error::*;
|
|
|
|
let code = match &e {
|
|
|
|
TooBig => StatusCode::InternalServerError,
|
|
|
|
//NotMarkdown => serve_error (StatusCode::BadRequest, "File is not Markdown"),
|
|
|
|
NotUtf8 => StatusCode::BadRequest,
|
|
|
|
};
|
|
|
|
|
|
|
|
serve_error (code, e.to_string ())
|
2020-11-10 02:39:20 +00:00
|
|
|
},
|
2020-12-20 18:38:39 +00:00
|
|
|
MarkdownPreview (s) => html::serve_html (s),
|
2020-11-29 19:19:59 +00:00
|
|
|
})
|
2020-10-30 22:38:23 +00:00
|
|
|
}
|
2020-10-31 01:35:39 +00:00
|
|
|
|
2020-11-18 23:24:47 +00:00
|
|
|
pub fn load_templates (
|
|
|
|
asset_root: &Path
|
|
|
|
)
|
2020-11-29 21:38:23 +00:00
|
|
|
-> Result <Handlebars <'static>, handlebars::TemplateFileError>
|
2020-10-31 17:56:36 +00:00
|
|
|
{
|
2020-10-31 20:46:38 +00:00
|
|
|
let mut handlebars = Handlebars::new ();
|
|
|
|
handlebars.set_strict_mode (true);
|
2020-10-31 17:56:36 +00:00
|
|
|
|
2020-11-18 23:24:47 +00:00
|
|
|
let asset_root = asset_root.join ("handlebars/server");
|
|
|
|
|
2020-11-29 19:05:28 +00:00
|
|
|
for (k, v) in &[
|
2020-10-31 20:46:38 +00:00
|
|
|
("file_server_dir", "file_server_dir.html"),
|
2020-11-08 15:53:09 +00:00
|
|
|
("file_server_root", "file_server_root.html"),
|
2020-11-29 19:05:28 +00:00
|
|
|
] {
|
2020-11-18 23:24:47 +00:00
|
|
|
handlebars.register_template_file (k, asset_root.join (v))?;
|
2020-10-31 17:56:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok (handlebars)
|
|
|
|
}
|
|
|
|
|
2020-11-08 17:58:14 +00:00
|
|
|
fn pretty_print_bytes (b: u64) -> String {
|
|
|
|
if b < 1024 {
|
|
|
|
format! ("{} B", b)
|
|
|
|
}
|
|
|
|
else if (b + 512) < 1024 * 1024 {
|
|
|
|
format! ("{} KiB", (b + 512) / 1024)
|
|
|
|
}
|
|
|
|
else if (b + 512 * 1024) < 1024 * 1024 * 1024 {
|
|
|
|
format! ("{} MiB", (b + 512 * 1024) / 1024 / 1024)
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
format! ("{} GiB", (b + 512 * 1024 * 1024) / 1024 / 1024 / 1024)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-31 01:35:39 +00:00
|
|
|
#[cfg (test)]
|
2020-11-29 18:50:51 +00:00
|
|
|
mod tests;
|