initial commit

This commit is contained in:
2024-05-04 10:41:58 +02:00
parent fc26a9921a
commit cf23beb84e
9 changed files with 3419 additions and 0 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
/target
/public
.env
build*
Dockerfile

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/target
/public

2791
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

26
Cargo.toml Normal file
View File

@@ -0,0 +1,26 @@
[package]
name = "webserver"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release]
strip = "debuginfo"
opt-level = "z"
[dependencies]
file-format = "0.24"
axum = { version = "0.7", features = [] }
serde = { version = "1.0", features = ["derive"] }
tera = { version = "1.19", features = [] }
tokio = { version = "1.37", features = ["full"] }
tokio-stream = { version = "0.1", features = ["full"] }
time = { version = "0.3", features = ["serde", "formatting"] }
tower-http = { version = "0.5.2", features = ["fs"] }
once_cell = "1.19"
base64 = "0.22"
human_bytes = "0.4"
exe = "0.5"
image = { version = "0.25", features = ["ico"] }
urlencoding = "2.1"
markdown = "1.0.0-alpha.16"

12
Dockerfile Normal file
View File

@@ -0,0 +1,12 @@
# Build stage
FROM rust:alpine AS build
WORKDIR /app
COPY . .
RUN apk update && apk add --no-cache musl-dev
RUN cargo build --release
# Deploy stage
FROM alpine
WORKDIR /app
COPY --from=build /app/target/release/webserver .
CMD ["./webserver"]

3
build.nu Normal file
View File

@@ -0,0 +1,3 @@
docker build --progress=plain -t webserver .
docker image tag webserver registry.avii.nl/aviinl/webserver:latest
docker image push --all-tags registry.avii.nl/aviinl/webserver

32
src/icon.rs Normal file
View File

@@ -0,0 +1,32 @@
use exe::pe::VecPE;
use exe::types::ResourceDirectory;
use image::io::Reader as ImageReader;
use std::fs::File;
use std::io::{Cursor, Read};
use std::path::Path;
pub fn extract_icon(file: &Path) -> Result<Option<Vec<u8>>, Box<dyn std::error::Error>> {
let mut buffer = [0u8; 1024 * 512]; // 512kb should be enough to extract icons
let mut file = File::open(file)?;
file.read_exact(&mut buffer)?;
let image = VecPE::from_data(exe::PEType::Disk, buffer);
let import_directory = ResourceDirectory::parse(&image)?;
let mut icon = None;
if let Some(ic) = import_directory.icon_groups(&image)?.iter().next() {
let ico_data = ic.1.to_icon_buffer(&image)?;
let img =
ImageReader::with_format(Cursor::new(&ico_data), image::ImageFormat::Ico).decode()?;
let img = img.resize_to_fill(20, 22, image::imageops::FilterType::Lanczos3);
let mut buffer = Cursor::new(vec![]);
img.write_to(&mut buffer, image::ImageFormat::Png)?;
icon = Some(buffer.into_inner());
}
Ok(icon)
}

356
src/main.rs Normal file
View File

@@ -0,0 +1,356 @@
mod icon;
use std::{collections::HashMap, fs, io::ErrorKind, path::PathBuf, str::FromStr};
use icon::extract_icon;
use once_cell::sync::{Lazy, OnceCell};
use axum::{extract::Request, http::StatusCode, response::Html, routing::get, Router};
use base64::prelude::*;
use serde::Serialize;
use tera::{to_value, Context, Result as TeraResult, Tera, Value};
use time::OffsetDateTime;
use tokio::time::Instant;
use tokio_stream::{wrappers::ReadDirStream, StreamExt};
use tower_http::services::ServeDir;
pub type AError = Box<dyn std::error::Error>;
pub type AResult<T> = Result<T, AError>;
pub static TERA: Lazy<Tera> = Lazy::new(|| {
let mut tera = Tera::default();
tera.add_raw_template(
"index.html.jinja",
include_str!("../templates/index.html.jinja"),
)
.unwrap();
tera.register_filter("iconize", iconize);
tera.register_filter("from_ico", from_ico);
tera.register_filter("size", size);
tera.register_filter("time", time);
tera.register_filter("md", md);
tera
});
pub static ICONS: Lazy<HashMap<&str, String>> = Lazy::new(|| {
let mut map = HashMap::new();
map.insert(
"unknown",
BASE64_STANDARD.encode(include_bytes!("../icons/unknown.png")),
);
map.insert(
"back",
BASE64_STANDARD.encode(include_bytes!("../icons/back.png")),
);
map.insert(
"dir",
BASE64_STANDARD.encode(include_bytes!("../icons/dir.png")),
);
map.insert(
"binary",
BASE64_STANDARD.encode(include_bytes!("../icons/binary.png")),
);
map.insert(
"image",
BASE64_STANDARD.encode(include_bytes!("../icons/image2.png")),
);
map.insert(
"compressed",
BASE64_STANDARD.encode(include_bytes!("../icons/compressed.png")),
);
map
});
fn from_ico(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
let Some(icon) = value.as_array() else {
return iconize(
&Value::String(String::from("")),
&std::default::Default::default(),
);
};
let icon = icon
.iter()
.map(|n| n.as_u64().unwrap() as u8)
.collect::<Vec<_>>();
let data = BASE64_STANDARD.encode(icon);
let str = format!("<img src=\"data:image/png;base64,{}\" alt=\"\"/>", data);
Ok(to_value(str).unwrap())
}
fn iconize(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
let icon = value.as_str().unwrap_or("unknown");
let icon = match icon {
"DIR" | "BACK" => "dir",
"image/png" | "image/jpg" | "image/webp" => "image",
"application/zip" => "compressed",
"application/octet-stream" => "binary",
_ => "unknown",
};
let icons = &*ICONS;
let icon = if icons.contains_key(icon) {
&icons[icon]
} else {
println!("Unknown filetype: {}", icon);
&icons["unknown"]
};
let str = format!("<img src=\"data:image/png;base64,{}\" alt=\"\" />", icon);
Ok(to_value(str).unwrap())
}
fn size(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
let Some(value) = value.as_f64() else {
return Ok(value.clone());
};
Ok(to_value(human_bytes::human_bytes(value)).unwrap())
}
fn time(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
let time_format: std::vec::Vec<time::format_description::FormatItem<'_>> =
time::format_description::parse("[day]-[month]-[year] [hour]:[minute]:[second]").unwrap();
let Some(time) = value.as_array() else {
return Ok(value.clone());
};
let time: Vec<i64> = time.iter().map(|v| v.as_i64().unwrap()).collect();
let new_time: OffsetDateTime = OffsetDateTime::now_utc();
let new_time = new_time.replace_year(time[0] as i32).unwrap();
let new_time = new_time.replace_ordinal(time[1] as u16).unwrap();
let new_time = new_time.replace_hour(time[2] as u8).unwrap();
let new_time = new_time.replace_minute(time[3] as u8).unwrap();
let new_time = new_time.replace_second(time[4] as u8).unwrap();
let new_time = new_time.replace_nanosecond(time[5] as u32).unwrap();
Ok(to_value(new_time.format(&time_format).unwrap()).unwrap())
}
fn md(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
// parse value as markdown and return html
if let Some(value) = value.as_str() {
if let Ok(md) = markdown::to_html_with_options(value, &markdown::Options::gfm()) {
return Ok(to_value(md).unwrap());
}
}
Ok(to_value(value).unwrap())
}
pub static BASE_DIR: OnceCell<PathBuf> = OnceCell::new();
#[derive(Debug, Serialize)]
struct FileInfo {
filename: String,
size: usize,
format: String,
icon: Option<Vec<u8>>,
// created: OffsetDateTime,
modified: OffsetDateTime,
description: Option<String>,
}
#[tokio::main]
async fn main() -> AResult<()> {
let base_dir = BASE_DIR.get_or_init(|| {
PathBuf::from_str(&std::env::var("BASE_DIR").unwrap_or(String::from("./public"))).unwrap()
});
// let app = Router::new().fallback_service(get(handler));
let app = Router::new().fallback_service(ServeDir::new(base_dir).fallback(get(handler)));
let listener = tokio::net::TcpListener::bind("[::]:3000").await.unwrap();
Ok(axum::serve(listener, app).await?)
}
async fn handler(request: Request) -> Result<Html<String>, StatusCode> {
let start = Instant::now();
let base_dir = BASE_DIR.get().unwrap();
let mut path = base_dir.clone();
let uri = urlencoding::decode(&request.uri().path()[1..]).map_err(|e| {
println!("{:?}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
path.push(&*uri);
let full_path = fs::canonicalize(&path).map_err(|e| {
println!("{:?}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let full_base_path = fs::canonicalize(base_dir).map_err(|e| {
println!("{:?}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
if !full_path.starts_with(full_base_path) {
return Err(StatusCode::BAD_REQUEST);
}
let body = match render_dir(&path, start).await {
Ok(body) => Ok(body),
Err(e) => {
let ioerror: Option<&std::io::Error> = e.downcast_ref();
if let Some(ioerror) = ioerror {
if ioerror.kind() == ErrorKind::NotFound {
Err(StatusCode::NOT_FOUND)
} else {
println!("{:?}", ioerror);
Err(StatusCode::INTERNAL_SERVER_ERROR)
}
} else {
println!("{:?}", e);
Err(StatusCode::INTERNAL_SERVER_ERROR)
}
}
};
Ok(Html(body?))
}
async fn render_dir(path: &PathBuf, time: Instant) -> AResult<String> {
let base_dir = BASE_DIR.get().unwrap();
let time2 = Instant::now();
let base = base_dir.display().to_string();
let dirname = path
.display()
.to_string()
.replace(&base, "")
.replace('\\', "/");
let filename = path.file_name().unwrap().to_string_lossy().to_string();
let description = PathBuf::from_str(&format!(
"{}/.{}.info",
path.parent().unwrap().to_string_lossy(),
filename
))?;
let description = if description.exists() {
Some(fs::read_to_string(description)?)
} else {
None
};
let directories = get_directories(path).await?;
let files = get_files(path).await?;
let tera = &*TERA;
let mut context = Context::new();
context.insert("description", &description);
context.insert("dirname", &dirname);
context.insert("directories", &directories);
context.insert("files", &files);
let loading = time2.elapsed() + time.elapsed();
context.insert("loading", &loading.as_millis());
Ok(tera.render("index.html.jinja", &context)?)
}
async fn get_directories(path: &PathBuf) -> AResult<Vec<FileInfo>> {
let mut contents = ReadDirStream::new(tokio::fs::read_dir(&path).await?);
let mut files = vec![];
while let Some(file) = contents.next().await {
let file = file?;
let metadata = file.metadata().await?;
if !metadata.is_dir() {
continue;
}
let filename = file.file_name().to_string_lossy().to_string();
if filename.starts_with('.') {
continue;
}
// let created: OffsetDateTime = metadata.created()?.into();
let modified: OffsetDateTime = metadata.modified()?.into();
let description = PathBuf::from_str(&format!(
"{}/.{}.info",
file.path().parent().unwrap().to_string_lossy(),
filename
))?;
let description = if description.exists() {
Some(fs::read_to_string(description)?)
} else {
None
};
files.push(FileInfo {
filename,
format: "DIR".to_string(),
size: 0,
icon: None,
// created,
modified,
description,
});
}
Ok(files)
}
async fn get_files(path: &PathBuf) -> AResult<Vec<FileInfo>> {
let mut contents = ReadDirStream::new(tokio::fs::read_dir(&path).await?);
let mut files = vec![];
while let Some(file) = contents.next().await {
let file = file?;
let metadata = file.metadata().await?;
if metadata.is_dir() {
continue;
}
let filename = file.file_name().to_string_lossy().to_string();
if filename.starts_with('.') {
continue;
}
let format = file_format::FileFormat::from_file(file.path())?;
let format = format.media_type();
let icon = if format == "application/x-dosexec" {
// ..
extract_icon(&file.path()).ok().flatten()
} else {
None
};
// let created: OffsetDateTime = metadata.created()?.into();
let modified: OffsetDateTime = metadata.modified()?.into();
let description = PathBuf::from_str(&format!(
"{}/.{}.info",
file.path().parent().unwrap().to_string_lossy(),
filename
))?;
let description = if description.exists() {
Some(fs::read_to_string(description)?)
} else {
None
};
files.push(FileInfo {
filename,
format: format.to_string(),
size: metadata.len() as usize,
icon,
// created,
modified,
description,
});
}
Ok(files)
}

192
templates/index.html.jinja Normal file
View File

@@ -0,0 +1,192 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index of {{dirname}}</title>
<style>
@media (prefers-color-scheme: dark) {
:root {
--background: #111;
--color: #CCC;
--link: #004ffc;
--visited: #2149a0;
}
}
@media (prefers-color-scheme: light) {
:root {
--background: #FFF;
--color: #000;
--link: #004ffc;
--visited: #2149a0;
}
}
body {
font-family: monospace;
font-size: 1.2em;
background-color: var(--background);
color: var(--color);
}
a {
color: var(--link);
}
a:visited {
color: var(--visited);
}
td {
margin: 0px;
border: 0px;
padding: 0px 8px;
}
tr:nth-child(2) td {
padding-top: 4px;
}
td:first-child {
text-align: center;
}
th {
border-bottom: double;
padding-bottom: 4px;
cursor: pointer;
}
footer {
padding-top: 15px;
font-size: 0.8em;
}
h1 {
margin-bottom: 0.25em;
}
p {
margin: 0.25em auto 0.50em auto;
padding: 0;
}
td p {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<h1>Index of {{dirname}}</h1>
{% if description %}{{ description | md }}{% endif %}
<table>
<tr>
<th>
</th>
<th>
Name
</th>
<th>
Last Modified
</th>
<th>
Size
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
{{ "BACK" | iconize }}
</td>
<td>
<a href="..">..</a>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
{% for file in directories %}
<tr>
<td data-value="{{ file.format }}">
{{ file.format | iconize }}
</td>
<td data-value="{{ file.filename }}">
<a href="{{ file.filename }}">{{ file.filename }}</a>
</td>
<td data-value="{{ file.modified }}">
{{ file.modified | time }}
</td>
<td data-value="">
</td>
<td>
{{ file.description | md }}
</td>
</tr>
{% endfor %}
{% for file in files %}
<tr>
<td data-value="{{ file.format }}">
{% if not file.icon %}
{{ file.format | iconize }}
{% else %}
{{ file.icon | from_ico }}
{% endif %}
</td>
<td data-value="{{ file.filename }}">
<a href="{{ file.filename }}">{{ file.filename }}</a>
</td>
<td data-value="{{ file.modified }}">
{{ file.modified | time }}
</td>
<td data-value="{{ file.size }}">
{{ file.size | size }}
</td>
<td>
{{ file.description | md }}
</td>
</tr>
{% endfor %}
</table>
<footer>
Directory index by <a href="https://github.com/aviinl" target="_BLANK">Avii</a> - Loading took {{ loading }}ms
</footer>
<script>
var getCellValue = function (tr, idx) { console.log(tr, idx); return tr.children[idx].dataset.value || tr.children[idx].innerText || tr.children[idx].textContent; }
var comparer = function (idx, asc) {
return function (a, b) {
return function (v1, v2) {
return v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2);
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}
};
// do the work...
Array.prototype.slice.call(document.querySelectorAll('th')).forEach(function (th) {
th.addEventListener('click', function () {
var table = th.parentNode;
while (table.tagName.toUpperCase() != 'TABLE') table = table.parentNode;
Array.prototype.slice.call(table.querySelectorAll('tr:nth-child(n+2)'))
.sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(function (tr) { table.appendChild(tr) });
});
});
</script>
</body>
</html>