GITv

Fix bugs found in a full review, and speed up page rendering

Browse files

Security: stop Markdown heading attributes injecting ids, classes and event handlers; run git init without the caller's config so a templateDir can't plant hooks; take pathspecs literally; kill git commands after 15 seconds or 64 MB of output; check file sizes before reading, and refuse rather than truncate oversized raw downloads. Bugs: show merge diffs against the first parent; reject page numbers that overflow; link deleted files to their parent commit; list submodules instead of linking to a 404; redirect file and folder links to the right view; fall back to main, master or the first branch when HEAD dangles; serve SVG images; name binary downloads; lock the keys file while adding a key. Speed: highlight with Oniguruma (about 2.5x faster), cache rendered files, READMEs and commit counts by object id, fetch refs once per page, look up type, id and size in one git call, pass GIT_PROTOCOL through for protocol v2, and load syntaxes at startup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 11:18
Commit
450fc4153137
Parent
13ff131

7 files changed +348−132

+42−44
@@ -8,15 +8,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
@@ -140,21 +131,6 @@ dependencies = [
"serde",
]
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -167,6 +143,16 @@ version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "cc"
version = "1.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
@@ -235,15 +221,10 @@ dependencies = [
]
[[package]]
name = "fancy-regex"
version = "0.16.2"
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f"
dependencies = [
"bit-set",
"regex-automata",
"regex-syntax",
]
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "flate2"
@@ -488,6 +469,28 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "onig"
version = "6.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"
dependencies = [
"bitflags",
"libc",
"once_cell",
"onig_sys",
]
[[package]]
name = "onig_sys"
version = "69.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -500,6 +503,12 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -536,17 +545,6 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
@@ -697,10 +695,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"
dependencies = [
"bincode",
"fancy-regex",
"flate2",
"fnv",
"once_cell",
"onig",
"regex-syntax",
"serde",
"serde_derive",
@@ -11,5 +11,5 @@ html-escape = "0.3.1"
nix = { version = "0.32.0", features = ["user", "fs"] }
pulldown-cmark = { version = "0.13.6", default-features = false, features = ["html"] }
shlex = "2.0.1"
syntect = { version = "5.3.0", default-features = false, features = ["default-syntaxes", "html", "regex-fancy"] }
syntect = { version = "5.3.0", default-features = false, features = ["default-syntaxes", "html", "regex-onig"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net"] }
@@ -105,6 +105,7 @@ a.entry:hover .name{color:var(--accent)}
.entry .name{flex:1;min-width:0;overflow-wrap:anywhere}
.entry .ic{color:var(--ink-2)}
.entry.dir .ic{color:var(--accent);fill:var(--accent-wash)}
.entry.sub .quiet{font-size:13px}
.sha{font:500 12.5px var(--f-mono);padding:2px 7px;border-radius:6px;white-space:nowrap;
color:var(--accent);background:var(--accent-wash)}
.sha:hover{text-decoration:none;box-shadow:inset 0 0 0 1px var(--accent)}
@@ -1,8 +1,11 @@
//! Read-only web browser for GITv repositories, served on localhost behind Caddy.
use std::cell::OnceCell;
use std::cmp::Reverse;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::extract::{Path, Query};
@@ -22,7 +25,7 @@ const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3
/// The stylesheet's URL carries a hash of its contents, so browsers can cache it for good and
/// still pick up every change.
static STYLE_URL: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
static STYLE_URL: LazyLock<String> = LazyLock::new(|| {
use std::hash::{Hash, Hasher};
let mut hasher = std::hash::DefaultHasher::new();
STYLESHEET.hash(&mut hasher);
@@ -33,9 +36,40 @@ static STYLE_URL: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
const LOGO: &str = r#"<svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>"#;
const PAGE: usize = 50;
/// Largest file the Raw view serves; bigger files are for `git clone`.
const RAW_LIMIT: usize = 50 << 20;
/// Largest file shown on a page; bigger files offer Raw instead.
const SHOW_LIMIT: usize = 1 << 20;
const DIFF_LIMIT: usize = 2 << 20;
/// Rendered HTML and commit counts keyed by immutable object ids, so repeat views skip the
/// expensive work. Emptied whenever it outgrows its budget.
#[derive(Default)]
struct Cache {
entries: HashMap<String, Arc<str>>,
bytes: usize,
}
static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(Default::default);
const CACHE_BUDGET: usize = 32 << 20;
fn cached(key: String, make: impl FnOnce() -> String) -> Arc<str> {
if let Some(hit) = CACHE.lock().ok().and_then(|c| c.entries.get(&key).cloned()) {
return hit;
}
let value: Arc<str> = make().into();
if let Ok(mut cache) = CACHE.lock() {
let cost = key.len() + value.len();
if cache.bytes + cost > CACHE_BUDGET {
cache.entries.clear();
cache.bytes = 0;
}
cache.bytes += cost;
cache.entries.insert(key, Arc::clone(&value));
}
value
}
#[derive(Parser)]
#[command(about = "Read-only web browser for GITv repositories")]
struct Cli {
@@ -56,7 +90,8 @@ type Q = HashMap<String, String>;
enum View {
Html(String),
Raw(Vec<u8>, &'static str),
/// Bytes, content type, and a download name for files the browser shouldn't display.
Raw(Vec<u8>, &'static str, Option<String>),
Redirect(String),
Missing,
}
@@ -74,7 +109,15 @@ impl IntoResponse for View {
let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")];
match self {
View::Html(body) => (SECURITY, html, body).into_response(),
View::Raw(data, kind) => (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response(),
View::Raw(data, kind, download) => {
let mut response = (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response();
if let Some(value) = download
.and_then(|name| format!("attachment; filename*=UTF-8''{}", encode(&name)).parse().ok())
{
response.headers_mut().insert(header::CONTENT_DISPOSITION, value);
}
response
}
View::Redirect(to) => Redirect::to(&to).into_response(),
View::Missing => (StatusCode::NOT_FOUND, SECURITY, html, view_missing()).into_response(),
}
@@ -104,6 +147,7 @@ fn icon(name: &str) -> String {
"commits" => r#"<circle cx="8" cy="8" r="2.4"/><path d="M1.5 8h4.1M10.4 8h4.1"/>"#,
"chevron" => r#"<path d="M4.5 6.5 8 10l3.5-3.5"/>"#,
"up" => r#"<path d="M8 13V3.5M4 7.5l4-4 4 4"/>"#,
"module" => r#"<rect x="2.5" y="2.5" width="11" height="11" rx="2"/><path d="M5.5 8h5M8 5.5v5"/>"#,
_ => "",
};
format!(r#"<svg class="ic" viewBox="0 0 16 16" aria-hidden="true">{path}</svg>"#)
@@ -192,6 +236,8 @@ struct Repo {
owner: String,
name: String,
path: PathBuf,
heads: OnceCell<Vec<String>>,
tags: OnceCell<Vec<String>>,
}
/// The newest commit on a ref: full hash, subject, author, unix time, short date.
@@ -209,7 +255,13 @@ impl Repo {
return None;
}
let path = repos_root().join(owner).join(format!("{name}.git"));
path.join("HEAD").is_file().then(|| Repo { owner: owner.into(), name: name.into(), path })
path.join("HEAD").is_file().then(|| Repo {
owner: owner.into(),
name: name.into(),
path,
heads: OnceCell::new(),
tags: OnceCell::new(),
})
}
fn git(&self, args: &[&str]) -> Option<String> {
@@ -223,8 +275,19 @@ impl Repo {
if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) }
}
/// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch.
fn default_ref(&self) -> String {
self.git(&["symbolic-ref", "--short", "HEAD"]).map_or("HEAD".into(), |s| s.trim().into())
let head = self.git(&["symbolic-ref", "--short", "HEAD"]).map(|s| s.trim().to_string());
let heads = self.heads();
if let Some(head) = head.filter(|h| heads.contains(h)) {
return head;
}
["main", "master"]
.into_iter()
.map(String::from)
.find(|b| heads.contains(b))
.or_else(|| heads.first().cloned())
.unwrap_or_else(|| "HEAD".into())
}
fn list_refs(&self, namespace: &str) -> Vec<String> {
@@ -233,6 +296,14 @@ impl Repo {
.unwrap_or_default()
}
fn heads(&self) -> &[String] {
self.heads.get_or_init(|| self.list_refs("refs/heads"))
}
fn tags(&self) -> &[String] {
self.tags.get_or_init(|| self.list_refs("refs/tags"))
}
/// The commit a ref names, rejecting anything that could read as an option or range.
fn resolve(&self, reference: &str) -> Option<String> {
let ok = (1..=200).contains(&reference.len())
@@ -246,15 +317,25 @@ impl Repo {
self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into())
}
fn latest(&self, rev: &str) -> Option<Head> {
let out = self.git(&["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"])?;
/// The newest commit on `rev` that touched `path` (the whole tree when empty).
fn latest(&self, rev: &str, path: &str) -> Option<Head> {
let mut args = vec!["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"];
if !path.is_empty() {
args.push(path);
}
let out = self.git(&args)?;
let f: Vec<&str> = out.trim_end().split('\x1f').collect();
let [oid, subject, author, stamp, date] = <[&str; 5]>::try_from(f).ok()?;
Some(Head { oid: oid.into(), subject: subject.into(), author: author.into(), stamp: stamp.into(), date: date.into() })
}
fn commit_count(&self, rev: &str) -> usize {
self.git(&["rev-list", "--count", rev, "--"]).and_then(|s| s.trim().parse().ok()).unwrap_or(0)
/// Commits reachable from `commit`. A commit's history never changes, so the count is cached.
fn commit_count(&self, commit: &str) -> usize {
let key = format!("count:{}:{commit}", self.path.display());
let count = cached(key, || {
self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string()).unwrap_or_default()
});
count.parse().unwrap_or(0)
}
/// Tag names grouped by the commit they point at, for labelling history.
@@ -286,7 +367,7 @@ impl Repo {
/// Name, clone address and tabs, shared by every repository page.
fn masthead(&self, active: &str, reference: &str) -> String {
let commits = self.resolve(reference).map_or(0, |c| self.commit_count(&c));
let tags = self.list_refs("refs/tags").len();
let tags = self.tags().len();
let tab = |view: &str, glyph: &str, label: &str, count: Option<usize>| {
let current = if view == active { r#" aria-current="page""# } else { "" };
let query: &[(&str, &str)] = if view == "tags" { &[] } else { &[("ref", reference)] };
@@ -313,8 +394,8 @@ impl Repo {
let href = self.url(view, &[("ref", name), ("path", path)]);
format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name))
};
let branches: String = self.list_refs("refs/heads").iter().map(item).collect();
let tags: String = self.list_refs("refs/tags").iter().map(item).collect();
let branches: String = self.heads().iter().map(item).collect();
let tags: String = self.tags().iter().map(item).collect();
let mut menu = format!("<h2>Branches</h2>{branches}");
if !tags.is_empty() {
menu += &format!("<h2>Tags</h2>{tags}");
@@ -370,11 +451,11 @@ fn view_index() -> View {
for entry in sorted_dir(&root.join(&owner)) {
let Some(name) = entry.strip_suffix(".git") else { continue };
let Some(repo) = Repo::open(&owner, name) else { continue };
let head = repo.latest(&repo.default_ref());
let head = repo.latest(&repo.default_ref(), "");
rows.push((head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0), repo, head));
}
}
rows.sort_by(|a, b| b.0.cmp(&a.0));
rows.sort_by_key(|row| Reverse(row.0));
let items: String = rows
.iter()
.map(|(_, repo, head)| {
@@ -402,7 +483,7 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let path = clean_path(q.get("path").map_or("", String::as_str))?;
let Some(commit) = repo.resolve(&reference) else {
if !repo.list_refs("refs/heads").is_empty() {
if !repo.heads().is_empty() {
return None;
}
let body = repo.masthead("tree", &reference) + &format!(
@@ -410,26 +491,19 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
<code>git push git@{HOST}:{}/{}.git main</code></div>"#, esc(&repo.owner), esc(&repo.name));
return Some(View::Html(page(&format!("{}/{}", repo.owner, repo.name), &body)));
};
let listing = repo.git(&["ls-tree", "-z", &format!("{commit}:{path}")])?;
let mut entries: Vec<(bool, String)> = listing
.split('\0')
.filter_map(|line| {
let (meta, name) = line.split_once('\t')?;
Some((meta.split(' ').nth(1)? == "tree", name.to_string()))
})
.collect();
entries.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.to_lowercase().cmp(&b.1.to_lowercase())));
let Some(listing) = repo.git(&["ls-tree", "-l", "-z", &format!("{commit}:{path}")]) else {
// A file path: show it in the file view instead.
return entry(repo, &commit, &path)
.filter(|e| e.kind == "blob")
.map(|_| View::Redirect(repo.url("blob", &[("ref", &reference), ("path", &path)])));
};
let mut entries: Vec<Entry> = listing.split('\0').filter_map(Entry::parse).collect();
// Folders first, then files and submodules, each alphabetically.
entries.sort_by(|a, b| (a.kind != "tree").cmp(&(b.kind != "tree")).then(a.name.to_lowercase().cmp(&b.name.to_lowercase())));
let mut body = repo.masthead("tree", &reference) + &repo.locator("tree", &reference, &path);
body += r#"<div class="panel">"#;
let path_arg: Vec<&str> = if path.is_empty() { vec![] } else { vec![path.as_str()] };
let mut args = vec!["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", commit.as_str(), "--"];
args.extend(path_arg);
if let Some(head) = repo.git(&args).and_then(|out| {
let f: Vec<String> = out.trim_end().split('\x1f').map(String::from).collect();
let [oid, subject, author, stamp, date] = <[String; 5]>::try_from(f).ok()?;
Some(Head { oid, subject, author, stamp, date })
}) {
if let Some(head) = repo.latest(&commit, &path) {
let _ = write!(body,
r#"<div class="panel-head"><div class="lead"><b class="who">{}</b><a class="subject" href="{}">{}</a></div><div class="side">{}<span>{}</span></div></div>"#,
esc(&head.author), attr(&repo.url("commit", &[("id", &head.oid)])), esc(&head.subject),
@@ -440,32 +514,70 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
let up = repo.url("tree", &[("ref", &reference), ("path", parent_of(&path))]);
let _ = write!(body, r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#, attr(&up), icon("up"));
}
for (is_dir, name) in &entries {
let full = if path.is_empty() { name.clone() } else { format!("{path}/{name}") };
let (view, class, glyph) = if *is_dir { ("tree", "entry dir", "dir") } else { ("blob", "entry", "file") };
for item in &entries {
let full = if path.is_empty() { item.name.clone() } else { format!("{path}/{}", item.name) };
let (view, class, glyph) = match item.kind.as_str() {
"tree" => ("tree", "entry dir", "dir"),
"commit" => {
// A submodule: its commits live in another repository, so there's nothing to open.
let _ = write!(body, r#"<li><span class="entry sub">{}<span class="name">{}</span><span class="quiet">Submodule at {}</span></span></li>"#,
icon("module"), esc(&item.name), &item.oid[..item.oid.len().min(7)]);
continue;
}
_ => ("blob", "entry", "file"),
};
let href = repo.url(view, &[("ref", &reference), ("path", &full)]);
let _ = write!(body, r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#,
attr(&href), icon(glyph), esc(name));
attr(&href), icon(glyph), esc(&item.name));
}
body += "</ul></div>";
let readme = entries.iter().find(|(d, n)| !d && n.to_ascii_lowercase().starts_with("readme"));
if let Some((_, readme)) = readme {
let full = if path.is_empty() { readme.clone() } else { format!("{path}/{readme}") };
if let Some(text) = repo.git(&["cat-file", "blob", &format!("{commit}:{full}")]) {
let content = if render::is_markdown(readme) {
let readme = entries.iter().find(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with("readme"));
if let Some(readme) = readme.filter(|e| e.size <= SHOW_LIMIT) {
let content = if render::is_markdown(&readme.name) {
// Links in the rendered README depend on the folder and ref as well as the content.
cached(format!("md:{}:{path}:{reference}", readme.oid), || {
let text = repo.git(&["cat-file", "blob", &readme.oid]).unwrap_or_default();
format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, &path, &reference))
} else {
code_view(readme, &text)
};
let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#,
icon("book"), esc(readme));
}
})
} else {
cached(format!("code:{}:{}", readme.oid, readme.name), || {
code_view(&readme.name, &repo.git(&["cat-file", "blob", &readme.oid]).unwrap_or_default())
})
};
let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#,
icon("book"), esc(&readme.name));
}
let title = if path.is_empty() { format!("{}/{}", repo.owner, repo.name) } else { format!("{path} at {reference}") };
Some(View::Html(page(&title, &body)))
}
/// One entry of a tree listing: `blob`, `tree` or `commit` (a submodule), its object id, its
/// size when it's a blob, and its name.
struct Entry {
kind: String,
oid: String,
size: usize,
name: String,
}
impl Entry {
/// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs.
fn parse(record: &str) -> Option<Entry> {
let (meta, name) = record.split_once('\t')?;
let mut fields = meta.split_whitespace().skip(1);
let (kind, oid) = (fields.next()?.to_string(), fields.next()?.to_string());
let size = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0);
Some(Entry { kind, oid, size, name: name.to_string() })
}
}
/// The entry at `path` in `commit`, with its type, object id and size, in one git call.
fn entry(repo: &Repo, commit: &str, path: &str) -> Option<Entry> {
let out = repo.git(&["ls-tree", "-l", "-z", commit, "--", path])?;
out.split('\0').filter_map(Entry::parse).find(|e| e.name == path)
}
/// Highlighted source with a line-number gutter.
fn code_view(path: &str, text: &str) -> String {
let lines = text.lines().count().max(1);
@@ -478,26 +590,38 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let path = clean_path(q.get("path")?)?;
let commit = repo.resolve(&reference)?;
let spec = format!("{commit}:{path}");
// Markdown links can't tell files from directories, so a blob link to a directory lands here.
if repo.git(&["cat-file", "-t", &spec]).is_some_and(|t| t.trim() == "tree") {
return Some(View::Redirect(repo.url("tree", &[("ref", &reference), ("path", &path)])));
let item = entry(repo, &commit, &path)?;
match item.kind.as_str() {
"blob" => {}
// Markdown links can't tell files from folders, so a file link to a folder lands here.
"tree" => return Some(View::Redirect(repo.url("tree", &[("ref", &reference), ("path", &path)]))),
_ => return None,
}
let data = git(&repo.path, &["cat-file", "blob", &spec]).ok()?;
let too_big = item.size > if raw { RAW_LIMIT } else { SHOW_LIMIT };
let data = if too_big { Vec::new() } else { git(&repo.path, &["cat-file", "blob", &item.oid]).ok()? };
let binary = data.iter().take(8000).any(|b| *b == 0);
if raw {
if too_big {
return Some(View::Html(page("File too large", &format!(
r#"<section class="notfound"><h1 class="title">This file is too large to download here</h1>
<p class="count">{} is {}. Clone the repository to get it.</p><code>git clone git@{HOST}:{}/{}.git</code></section>"#,
esc(file_name(&path)), size(item.size), esc(&repo.owner), esc(&repo.name)))));
}
let kind = match path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() {
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
// Safe to serve as an image: the page's policy blocks any script inside it.
Some("svg") => "image/svg+xml",
_ if binary => "application/octet-stream",
_ => "text/plain; charset=utf-8",
};
return Some(View::Raw(data.into_iter().take(RAW_LIMIT).collect(), kind));
let download = (kind == "application/octet-stream").then(|| file_name(&path).to_string());
return Some(View::Raw(data, kind, download));
}
let text = String::from_utf8_lossy(&data);
let markdown = !binary && render::is_markdown(&path);
let markdown = !binary && !too_big && render::is_markdown(&path);
let as_code = !markdown || q.get("view").is_some_and(|v| v == "code");
let mut side = String::new();
@@ -510,15 +634,20 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
let _ = write!(side, r#"<span class="segmented">{}{}</span>"#, link("Preview", "", !as_code), link("Code", "code", as_code));
}
let _ = write!(side, r#"<a class="button" href="{}">Raw</a>"#, attr(&repo.url("raw", &[("ref", &reference), ("path", &path)])));
let facts = if binary { size(data.len()) } else {
format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(data.len()))
let facts = if binary || too_big { size(item.size) } else {
format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(item.size))
};
let content = if binary {
r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#.to_string()
let content: Arc<str> = if too_big {
r#"<p class="note">This file is too large to show here. Use Raw to open it.</p>"#.into()
} else if binary {
r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#.into()
} else if as_code {
code_view(&path, &text)
// Highlighting depends only on the content and the file's type.
cached(format!("code:{}:{}", item.oid, file_name(&path)), || code_view(&path, &text))
} else {
format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference))
cached(format!("md:{}:{}:{reference}", item.oid, parent_of(&path)), || {
format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference))
})
};
let body = repo.masthead("tree", &reference) + &repo.locator("blob", &reference, &path) + &format!(
r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b><span class="quiet">{facts}</span></div><div class="side">{side}</div></div>{content}</section>"#,
@@ -529,9 +658,10 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
fn view_log(repo: &Repo, q: &Q) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let number: usize = q.get("page").and_then(|p| p.parse().ok()).unwrap_or(0);
let skip = number.checked_mul(PAGE)?;
let commit = repo.resolve(&reference)?;
let out = repo.git(&[
"log", &format!("-n{}", PAGE + 1), &format!("--skip={}", number * PAGE),
"log", &format!("-n{}", PAGE + 1), &format!("--skip={skip}"),
"--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", &commit, "--",
])?;
let lines: Vec<&str> = out.lines().collect();
@@ -628,7 +758,8 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
"--format=%H%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%b", &commit])?;
let f: Vec<&str> = meta.splitn(7, '\x1f').collect();
let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?;
let patch = git(&repo.path, &["show", "--format=", "--no-color", "-M", "--patch", &commit]).ok()?;
// A merge shows what it brought in relative to its first parent.
let patch = git(&repo.path, &["show", "--format=", "--no-color", "-M", "--patch", "--diff-merges=first-parent", &commit]).ok()?;
let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" ");
let mut body = repo.masthead("log", &repo.default_ref());
@@ -651,7 +782,9 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
plural(files.len(), "file", "files"));
for file in &files {
let status = if file.status.is_empty() { String::new() } else { format!(r#"<span class="status">{}</span>"#, file.status) };
let link = repo.url(if file.status == "Deleted" { "log" } else { "blob" }, &[("ref", oid), ("path", &file.name)]);
// A deleted file still exists in the parent commit.
let at = if file.status == "Deleted" { parents.split_whitespace().next().unwrap_or(oid) } else { oid };
let link = repo.url("blob", &[("ref", at), ("path", &file.name)]);
let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<a href="{}"><b>{}</b></a>{status}</div><div class="side"><span class="plus">+{}</span><span class="minus">−{}</span></div></div>"#,
icon("file"), attr(&link), esc(&file.name), file.added, file.removed);
if file.binary {
@@ -723,6 +856,8 @@ async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View {
#[tokio::main]
async fn main() {
let Action::Serve { port } = Cli::parse().action;
// Load the syntax definitions now rather than on the first visitor's request.
tokio::task::spawn_blocking(render::warm_up);
let app = Router::new()
.route("/", get(|| blocking(view_index)))
.route("/style.css", get(|| async { stylesheet() }))
@@ -8,7 +8,8 @@ use std::process::{Command, ExitCode, Stdio};
use base64::Engine;
use clap::{Parser, Subcommand};
use gitv::{HOST, NAME_RULE, git, git_command, keys_path, repos_root, valid_name};
use nix::fcntl::{Flock, FlockArg};
use gitv::{HOST, NAME_RULE, git, git_base, git_command, keys_path, repos_root, valid_name};
const HELP: &str = "Commands for your key, run as: ssh git@git.um9i.dev <command>
list list your repositories
@@ -82,7 +83,8 @@ fn create(owner: &str, name: &str, quiet: bool) -> Result<(), String> {
}
// Build in a hidden staging name, then rename, so a half-made repository never serves.
let staging = directory.join(format!(".create-{}-{name}", std::process::id()));
let status = Command::new("git")
// A clean environment, so no caller's init.templateDir can plant hooks in the repository.
let status = git_base()
.args(["init", "--quiet", "--bare", "--initial-branch=main"])
.arg(&staging)
.status()
@@ -153,15 +155,28 @@ fn add_key(owner: &str, file: &Path) -> Result<(), String> {
}
let token = engine.encode(&blob);
let keys = keys_path();
let old = fs::read_to_string(&keys).unwrap_or_default();
let directory = keys.parent().ok_or("authorized_keys has no directory")?;
// Serialise writers, so two keys added at once can't overwrite each other.
let lock = fs::File::options()
.create(true)
.append(true)
.open(directory.join("keys.lock"))
.map_err(|e| e.to_string())?;
let _lock = Flock::lock(lock, FlockArg::LockExclusive).map_err(|(_, e)| e.to_string())?;
let old = match fs::read_to_string(&keys) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e.to_string()),
};
if old.lines().any(|row| row.split_whitespace().last() == Some(token.as_str())) {
return Err("key already registered".into());
}
let line = format!("restrict,command=\"/usr/local/bin/gitv serve {owner}\" ssh-ed25519 {token}\n");
let temporary = keys.with_extension("tmp");
let temporary = directory.join(format!(".authorized_keys.{}", std::process::id()));
let mut out = fs::File::create(&temporary).map_err(|e| e.to_string())?;
out.write_all(format!("{old}{line}").as_bytes()).map_err(|e| e.to_string())?;
out.set_permissions(fs::Permissions::from_mode(0o644)).map_err(|e| e.to_string())?;
out.sync_all().map_err(|e| e.to_string())?;
fs::rename(&temporary, &keys).map_err(|e| e.to_string())?;
owner_directory(owner)?;
Ok(())
@@ -223,11 +238,17 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
create(owner, name, true)?;
eprintln!("gitv: created {owner}/{name}.git");
}
let status = Command::new(program)
.arg(&repo)
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("HOME", "/var/empty")
let mut command = Command::new(program);
command.arg(&repo).env_clear().env("PATH", "/usr/bin:/bin").env("HOME", "/var/empty");
// Pass the client's protocol request through (when sshd accepts it), so clients can use the
// faster protocol v2.
if let Ok(protocol) = std::env::var("GIT_PROTOCOL")
&& protocol.len() <= 64
&& protocol.bytes().all(|b| b.is_ascii_alphanumeric() || b"=:.".contains(&b))
{
command.env("GIT_PROTOCOL", protocol);
}
let status = command
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.status()
+61−10
@@ -2,8 +2,13 @@
pub mod render;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
pub const HOST: &str = "git.um9i.dev";
@@ -32,8 +37,15 @@ pub fn valid_name(value: &str) -> bool {
pub const NAME_RULE: &str = "use 1–63 lowercase letters, digits, hyphens or underscores";
/// A minimal environment for git so the server's user config never leaks in.
pub fn git_command(git_dir: &Path) -> Command {
/// How long any one git command may run before it is killed.
pub const GIT_TIMEOUT: Duration = Duration::from_secs(15);
/// The most stdout any one git command may produce before it is killed.
pub const GIT_OUTPUT_LIMIT: usize = 64 << 20;
/// A `git` command with a minimal environment, so no user or system config (hooks templates,
/// aliases, pagers) leaks in, and with pathspecs taken literally rather than as globs or magic.
pub fn git_base() -> Command {
let mut command = Command::new("git");
command
.env_clear()
@@ -41,20 +53,59 @@ pub fn git_command(git_dir: &Path) -> Command {
.env("HOME", "/var/empty")
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_LITERAL_PATHSPECS", "1")
.env("LC_ALL", "C.UTF-8")
.args(["-c", "safe.directory=*", "-c", "core.quotePath=false", "--git-dir"])
.arg(git_dir)
.stdin(Stdio::null());
command
}
/// Run a read-only git command and return stdout, or git's error message.
/// [`git_base`] pointed at a bare repository.
pub fn git_command(git_dir: &Path) -> Command {
let mut command = git_base();
command.args(["-c", "safe.directory=*", "-c", "core.quotePath=false", "--git-dir"]).arg(git_dir);
command
}
/// Run a read-only git command and return its stdout. The command is killed if it runs longer
/// than [`GIT_TIMEOUT`] or writes more than [`GIT_OUTPUT_LIMIT`] bytes.
pub fn git(git_dir: &Path, args: &[&str]) -> Result<Vec<u8>, String> {
let output = git_command(git_dir).args(args).output().map_err(|e| format!("cannot run git: {e}"))?;
if output.status.success() {
Ok(output.stdout)
let mut child = git_command(git_dir)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("cannot run git: {e}"))?;
let mut stdout = child.stdout.take().ok_or("git has no stdout")?;
let child = Arc::new(Mutex::new(child));
let (finished, wait) = mpsc::channel::<()>();
let watchdog = {
let child = Arc::clone(&child);
thread::spawn(move || {
if let Err(RecvTimeoutError::Timeout) = wait.recv_timeout(GIT_TIMEOUT) {
// Still unreaped while we hold the lock, so the kill cannot hit a reused pid.
let _ = child.lock().map(|mut c| c.kill());
}
})
};
let mut output = Vec::new();
let read = (&mut stdout).take(GIT_OUTPUT_LIMIT as u64 + 1).read_to_end(&mut output);
let too_big = output.len() > GIT_OUTPUT_LIMIT;
let status = {
let mut child = child.lock().map_err(|_| "git watchdog failed")?;
if too_big {
let _ = child.kill();
}
child.wait()
};
let _ = finished.send(());
let _ = watchdog.join();
read.map_err(|e| format!("cannot read git output: {e}"))?;
let status = status.map_err(|e| format!("git failed: {e}"))?;
if too_big {
Err("git output too large".into())
} else if status.success() {
Ok(output)
} else {
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(if message.is_empty() { "git failed".into() } else { message })
Err(format!("git failed ({status})"))
}
}
@@ -17,6 +17,11 @@ const CLASSES: ClassStyle = ClassStyle::SpacedPrefixed { prefix: "hl-" };
static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
/// Load the syntax definitions ahead of the first request.
pub fn warm_up() {
LazyLock::force(&SYNTAXES);
}
/// The syntax for a file, by extension, whole file name, then shebang or modeline.
fn syntax_for(path: &str, first_line: &str) -> Option<&'static SyntaxReference> {
let file = path.rsplit('/').next().unwrap_or(path);
@@ -99,11 +104,9 @@ pub fn resolve_link(dir: &str, target: &str) -> Target {
/// Render Markdown to HTML. Raw HTML in the source is escaped, fenced code is highlighted, and
/// `link(path, is_image)` turns repository paths into URLs.
pub fn markdown(source: &str, dir: &str, link: &dyn Fn(&str, bool) -> String) -> String {
let options = Options::ENABLE_TABLES
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_TASKLISTS
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_HEADING_ATTRIBUTES;
// Heading attributes stay off: `# Title {onclick=… #main}` would let a file set any
// attribute, id or class on the page.
let options = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_FOOTNOTES;
let rewrite = |dest: CowStr<'_>, image: bool| -> CowStr<'static> {
match resolve_link(dir, &dest) {
Target::External(url) => url.into(),
@@ -165,6 +168,13 @@ mod tests {
assert!(!html.contains("<div"), "{html}");
}
#[test]
fn ignores_heading_attributes() {
let html = markdown("# Title {onclick=alert(1) #main .skip style=x}", "", &link);
// The braces stay as heading text instead of becoming attributes.
assert_eq!(html.trim(), "<h1>Title {onclick=alert(1) #main .skip style=x}</h1>");
}
#[test]
fn blocks_dangerous_links() {
let html = markdown("[x](javascript:alert(1)) [y](../../etc/passwd)", "docs", &link);