GITv

Harden account writes, stream Git transfers, and batch directory history

Browse files
Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 15:33
Commit
a87990ad1653
Parent
37a7850

16 files changed +1088−485

+9−1
@@ -34,7 +34,7 @@ It prints a generated password (20 random characters, shown only this once), the
- **Change the password** under Account once signed in (it asks for the current password and a code), or on the server with `gitv-web password`. Either way every other session is signed out.
- **Lost the authenticator?** Run `gitv-web setup --force` on the server for a new password and secret.
- The account lives in `/var/lib/gitv-web/login` (or `$GITV_WEB_AUTH`), readable only by its owner. Root-run setup hands the default service directory to `gitv-web`. If you point `GITV_WEB_AUTH` into an existing custom directory, give the service write and search access there first. The password is stored as an Argon2id hash.
- Sessions last 12 hours and end when the browser restarts. The session cookie is `Secure`, so the browser must be reached over HTTPS (or on `localhost`).
- Sessions last up to 12 hours, including across browser restarts. Sign out to end a session on a shared device. The session cookie is `Secure`, so the browser must be reached over HTTPS (or on `localhost`).
- After five failed attempts sign-in locks for a minute, doubling with each further failure up to 15 minutes. A code works once.
Until the account exists, pages requiring sign-in show setup instructions. Public repositories can already be browsed and cloned.
@@ -68,3 +68,11 @@ cargo test
```
`tests/ssh.rs` runs `gitv serve` the way a key does over SSH, pushing and cloning real repositories through a stand-in for ssh. `tests/web.rs` builds a fixture repository and checks every page of a running `gitv-web` over HTTP, signed in, including escaping and the requests it must refuse. `tests/auth.rs` covers signing in, two-factor codes, lockout, sessions and changing the password. Neither needs an SSH server or network access; both write only to `target/tmp`.
## Production configuration
The deployment files are the source copies for the Fedora host. Caddy uses
`deploy/Caddyfile` at `/etc/caddy/Caddyfile`. The web service runs with
`deploy/gitv-web.service` at `/etc/systemd/system/gitv-web.service`, alongside
Fedora's distribution-provided systemd defaults. OpenSSH uses
`deploy/sshd-gitv.conf` at `/etc/ssh/sshd_config.d/90-gitv.conf`.
+3−0
@@ -0,0 +1,3 @@
git.um9i.dev {
reverse_proxy 127.0.0.1:8080
}
@@ -0,0 +1,28 @@
[Unit]
Description=GITv repository browser
After=network.target
[Service]
User=gitv-web
Group=gitv-web
SupplementaryGroups=git
ExecStart=/usr/local/bin/gitv-web serve --port 8080
Restart=on-failure
StateDirectory=gitv-web
StateDirectoryMode=0700
UMask=0077
NoNewPrivileges=yes
ProtectSystem=strict
ReadOnlyPaths=/srv/gitv/repos
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
CapabilityBoundingSet=
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,10 @@
# Per-key forced commands are installed here by gitv add-key.
Match User git
AuthenticationMethods publickey
AuthorizedKeysFile /etc/gitv/authorized_keys
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitTTY no
DisableForwarding yes
PermitUserRC no
Match all
+87−20
@@ -136,16 +136,39 @@ pub struct WriteLock {
/// # Errors
/// [`AuthError::Write`] if the lock file can't be opened or locked.
pub fn lock_for_writing(path: &Path, owner: Owner) -> Result<WriteLock, AuthError> {
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let lock_path = path.with_file_name(format!(".{name}.lock"));
let file = fs::File::options()
.create(true)
.append(true)
.mode(0o600)
.open(&lock_path)
.map_err(|source| AuthError::Write { path: lock_path.clone(), source })?;
// The service must be able to take this lock too, to save password changes.
hand_over(&file, &lock_path, owner)?;
use nix::fcntl::{OFlag, openat};
use nix::sys::stat::Mode;
use std::os::unix::fs::MetadataExt;
let lock_path = sibling(path, "lock");
let write_error = |source| AuthError::Write { path: lock_path.clone(), source };
let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
let directory = fs::File::options()
.read(true)
.custom_flags(nix::libc::O_DIRECTORY | nix::libc::O_NOFOLLOW)
.open(parent)
.map_err(write_error)?;
let name = lock_path.file_name().expect("sibling has a file name");
let flags = OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC | OFlag::O_NONBLOCK | OFlag::O_WRONLY;
let private = Mode::S_IRUSR | Mode::S_IWUSR;
let (fd, created) = match openat(&directory, name, flags | OFlag::O_CREAT | OFlag::O_EXCL, private) {
Ok(fd) => (fd, true),
Err(nix::errno::Errno::EEXIST) => {
(openat(&directory, name, flags, Mode::empty()).map_err(|e| write_error(e.into()))?, false)
}
Err(error) => return Err(write_error(error.into())),
};
let file = fs::File::from(fd);
let meta = file.metadata().map_err(write_error)?;
let expected =
if created { nix::unistd::geteuid() } else { owner.map_or_else(nix::unistd::geteuid, |(service, _)| service) };
if !meta.is_file() || meta.nlink() != 1 || meta.mode() & 0o077 != 0 || meta.uid() != expected.as_raw() {
return Err(write_error(std::io::Error::other("unsafe account lock file")));
}
// Only change ownership of an inode this open created exclusively.
if created {
hand_over(&file, &lock_path, owner)?;
}
let lock = nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusive)
.map_err(|(_, e)| AuthError::Write { path: lock_path, source: e.into() })?;
Ok(WriteLock { _lock: lock })
@@ -186,14 +209,21 @@ pub fn change_password(
/// code is then not accepted.
pub fn consume_code(path: &Path, credentials: &Credentials, code: &str, unix_seconds: u64) -> Result<bool, AuthError> {
let _lock = lock_for_writing(path, None)?;
if Credentials::load(path)?.fingerprint() != credentials.fingerprint() {
return Ok(false);
}
let record = sibling(path, "used");
let secret_id = data_encoding::HEXLOWER.encode(&Sha256::digest(&credentials.totp_secret));
let last_step = match fs::read_to_string(&record) {
Ok(text) => text
.split_once(' ')
.filter(|(id, _)| *id == secret_id)
.and_then(|(_, step)| step.trim().parse::<u64>().ok())
.unwrap_or(0),
Ok(text) => {
let malformed = || AuthError::Malformed { path: record.clone(), reason: "invalid replay record" };
let (id, step) = text.trim_end_matches('\n').split_once(' ').ok_or_else(malformed)?;
if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
return Err(malformed());
}
let step = step.parse::<u64>().map_err(|_| malformed())?;
if id == secret_id { step } else { 0 }
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
Err(source) => return Err(AuthError::Read { path: record, source }),
};
@@ -780,14 +810,45 @@ mod tests {
dir
}
#[test]
fn lock_requires_a_private_regular_file_with_one_link() {
use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink};
let dir = scratch("lock-links");
let path = dir.join("login");
let sentinel = dir.join("sentinel");
fs::write(&sentinel, b"untouched").unwrap();
fs::set_permissions(&sentinel, fs::Permissions::from_mode(0o600)).unwrap();
let before = fs::metadata(&sentinel).unwrap().uid();
let owner = nix::unistd::geteuid()
.is_root()
.then(|| (nix::unistd::Uid::from_raw(65534), nix::unistd::Gid::from_raw(65534)));
let lock = sibling(&path, "lock");
symlink(&sentinel, &lock).unwrap();
assert!(lock_for_writing(&path, owner).is_err());
fs::remove_file(&lock).unwrap();
fs::hard_link(&sentinel, &lock).unwrap();
assert!(lock_for_writing(&path, owner).is_err());
assert_eq!(fs::metadata(&sentinel).unwrap().uid(), before);
assert_eq!(fs::read(&sentinel).unwrap(), b"untouched");
fs::remove_file(&lock).unwrap();
drop(lock_for_writing(&path, owner).unwrap());
if let Some((uid, gid)) = owner {
let handed_over = fs::metadata(&lock).unwrap();
assert_eq!((handed_over.uid(), handed_over.gid()), (uid.as_raw(), gid.as_raw()));
drop(lock_for_writing(&path, owner).unwrap());
}
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_code_is_accepted_once_even_by_a_fresh_reader() {
let dir = scratch("once");
let path = dir.join("login");
account().save(&path, None).unwrap();
assert!(consume_code(&path, &account(), "287082", 59).unwrap());
let original = account();
original.save(&path, None).unwrap();
assert!(consume_code(&path, &original, "287082", 59).unwrap());
// Nothing in memory carries over: the record on disk refuses it.
assert!(!consume_code(&path, &account(), "287082", 59).unwrap());
assert!(!consume_code(&path, &original, "287082", 59).unwrap());
let _ = fs::remove_dir_all(&dir);
}
@@ -795,12 +856,18 @@ mod tests {
fn a_new_authenticator_secret_starts_afresh() {
let dir = scratch("fresh");
let path = dir.join("login");
account().save(&path, None).unwrap();
assert!(consume_code(&path, &account(), "287082", 59).unwrap());
let original = account();
original.save(&path, None).unwrap();
assert!(consume_code(&path, &original, "287082", 59).unwrap());
let mut replaced = account();
replaced.totp_secret = b"another secret of twenty".to_vec();
replaced.save(&path, None).unwrap();
let code = format!("{:06}", totp_code(&replaced.totp_secret, 1));
assert!(consume_code(&path, &replaced, &code, 59).unwrap(), "the old secret's record blocked the new one");
assert!(!consume_code(&path, &original, "287082", 59).unwrap());
assert!(!consume_code(&path, &replaced, &code, 59).unwrap());
fs::write(sibling(&path, "used"), "corrupt").unwrap();
assert!(consume_code(&path, &replaced, &code, 59).is_err());
let _ = fs::remove_dir_all(&dir);
}
}
@@ -0,0 +1,117 @@
//! Bounded, backpressured output from a pinned Git process.
use axum::body::{Body, Bytes};
use futures_util::{StreamExt, stream};
use std::{io, process::Stdio, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
process::Command,
sync::{Semaphore, SemaphorePermit, mpsc, oneshot},
};
pub static RAW_TRANSFERS: Semaphore = Semaphore::const_new(4);
pub struct Output {
child: tokio::process::Child,
stdout: tokio::process::ChildStdout,
}
impl Output {
pub fn start(mut command: Command) -> io::Result<Self> {
let mut child = command.kill_on_drop(true).stdout(Stdio::piped()).spawn()?;
let stdout = child.stdout.take().ok_or_else(|| io::Error::other("missing Git stdout"))?;
Ok(Self { child, stdout })
}
pub async fn prefix(&mut self, len: usize) -> io::Result<Bytes> {
let mut bytes = vec![0; len];
tokio::time::timeout(gitv::GIT_TIMEOUT, self.stdout.read_exact(&mut bytes)).await??;
Ok(bytes.into())
}
pub fn body(
mut self,
prefix: Bytes,
input: Option<Bytes>,
permit: SemaphorePermit<'static>,
timeout: Duration,
) -> Body {
let (tx, rx) = mpsc::channel::<Bytes>(2);
let (finished, status) = oneshot::channel();
let (body_guard, dropped) = oneshot::channel::<()>();
tokio::spawn(async move {
let _permit = permit;
let deadline = tokio::time::Instant::now() + timeout;
let mut stdin = self.child.stdin.take();
let write = async move {
if let Some(input) = input {
stdin.as_mut().ok_or_else(|| io::Error::other("missing Git stdin"))?.write_all(&input).await?;
}
drop(stdin);
Ok::<_, io::Error>(())
};
let read = async {
let mut buf = vec![0; 65536];
loop {
let count = self.stdout.read(&mut buf).await?;
if count == 0 {
break;
}
tx.send(Bytes::copy_from_slice(&buf[..count])).await.map_err(|_| io::ErrorKind::BrokenPipe)?;
}
if !self.child.wait().await?.success() {
return Err(io::Error::other("Git transfer failed"));
}
Ok(())
};
let outcome = tokio::select! {
_ = tx.closed() => return,
result = tokio::time::timeout_at(deadline, async { tokio::try_join!(write, read).map(|_| ()) }) =>
result.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into())),
};
drop(self);
drop(tx);
let _ = finished.send(outcome);
// Hold the slot through buffered delivery, but never beyond the transfer deadline.
let _ = tokio::time::timeout_at(deadline, dropped).await;
});
// The worker's terminal status has its own channel (a oneshot), so a full
// byte queue cannot turn a failed transfer into successful EOF.
let chunks = stream::unfold(rx, |mut rx| async { Some((rx.recv().await?, rx)) }).map(Ok);
let end = stream::once(async move {
let _guard = body_guard;
status.await.map_err(io::Error::other)??;
Ok::<_, io::Error>(Bytes::new())
});
Body::from_stream(stream::iter((!prefix.is_empty()).then_some(Ok(prefix))).chain(chunks).chain(end))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn dropping_a_transfer_body_releases_its_slot() {
static SLOT: Semaphore = Semaphore::const_new(1);
let mut command = Command::new("head");
command.args(["-c", "1048576", "/dev/zero"]);
let output = Output::start(command).unwrap();
let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_secs(300));
drop(body);
let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap();
drop(permit);
}
#[tokio::test]
async fn stalled_body_times_out_and_reports_the_error_after_buffered_bytes() {
static SLOT: Semaphore = Semaphore::const_new(1);
let mut command = Command::new("head");
command.args(["-c", "1048576", "/dev/zero"]);
let output = Output::start(command).unwrap();
let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_millis(50));
assert!(SLOT.try_acquire().is_err());
let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap();
assert!(axum::body::to_bytes(body, 1 << 20).await.is_err());
drop(permit);
}
}
@@ -220,7 +220,6 @@ impl Login {
/// file's lock and recorded on disk, so it works once: across simultaneous requests,
/// restarts and processes alike.
fn settle(&self, credentials: &Credentials, password_ok: bool, code: &str) -> Checked {
let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner());
let code_ok = password_ok
&& match gitv::auth::consume_code(&self.path, credentials, code, unix_now()) {
Ok(accepted) => accepted,
@@ -229,6 +228,7 @@ impl Login {
return Checked::Unavailable;
}
};
let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner());
if code_ok {
guard.failures = 0;
guard.locked_until = None;
@@ -1,14 +1,12 @@
//! Read-only web browser for GITv repositories, served on localhost behind Caddy, behind a
//! sign-in with a password and an authenticator code (see [`login`]).
//!
//! Every repository on the server is visible to anyone who can reach this service: it is meant
//! for one trusted audience behind the proxy's login, not for per-owner access like SSH.
//! Repository browser and read-only HTTP clone service. Anonymous visitors can access public repositories.
//! A session grants the shared web account access to private repositories.
mod login;
mod templates;
use std::borrow::Cow;
use std::cell::OnceCell;
mod repository;
use repository::{Head, Reader};
use std::cmp::Reverse;
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
@@ -18,6 +16,7 @@ use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::{Extension, Router};
mod git_stream;
mod smart_http;
use axum::extract::DefaultBodyLimit;
use axum::extract::{Path, RawQuery};
@@ -27,12 +26,12 @@ use axum::routing::{get, post};
use clap::{Parser, Subcommand};
use gitv::render;
use gitv::{
HOST, RepoDir, entries, git, git_capped, open_dir_at, open_owner, open_root, percent_decode, repo_dir, repo_in,
repos_root, try_entries, try_kind_at,
HOST, RepoDir, entries, git_capped, open_dir_at, open_owner, open_root, percent_decode, repo_dir, repo_in,
repos_root, try_subdirs,
};
use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc};
use nix::sys::stat::SFlag;
use std::os::fd::{AsFd, OwnedFd};
use std::time::Instant;
const STYLESHEET: &str = include_str!("../../../assets/style.css");
const FONT_DISPLAY: &[u8] = include_bytes!("../../../assets/fonts/display.woff2");
@@ -131,8 +130,9 @@ enum Action {
enum View {
LoginRequired,
Html(String),
/// Bytes, content type, and a download name for files the browser shouldn't display.
Raw(Vec<u8>, &'static str, Option<Vec<u8>>),
/// Pinned cat-file command, expected size and original download name.
Raw(Box<std::process::Command>, usize, Vec<u8>),
Busy,
Redirect(String),
Missing(bool),
}
@@ -147,21 +147,14 @@ const SECURITY: [(header::HeaderName, &str); 4] = [
(header::CACHE_CONTROL, "no-store"),
];
impl IntoResponse for View {
fn into_response(self) -> Response {
impl View {
async fn response(self) -> Response {
let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")];
match self {
View::LoginRequired => StatusCode::UNAUTHORIZED.into_response(),
View::Html(body) => (SECURITY, html, body).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::Raw(cmd, size, name) => raw_response(*cmd, size, name).await,
View::Busy => StatusCode::SERVICE_UNAVAILABLE.into_response(),
View::Redirect(to) => Redirect::to(&to).into_response(),
View::Missing(signed_in) => {
(StatusCode::NOT_FOUND, SECURITY, html, view_missing(signed_in)).into_response()
@@ -338,52 +331,20 @@ struct Repo {
signed_in: bool,
owner: String,
name: String,
dir: RepoDir,
heads: OnceCell<Vec<String>>,
tags: OnceCell<Vec<String>>,
}
/// The newest commit on a ref: full hash, subject, author, unix time, short date.
struct Head {
oid: String,
subject: String,
author: String,
stamp: String,
date: String,
}
impl Head {
/// Parse `%H %an %ct %cd %s`, separated by 0x1f. The subject goes last and the split stops
/// at five fields, so a subject that itself contains the separator byte stays whole.
fn parse(out: &str) -> Option<Head> {
let f: Vec<&str> = out.trim_end_matches('\n').splitn(5, '\x1f').collect();
let [oid, author, stamp, date, subject] = <[&str; 5]>::try_from(f).ok()?;
Some(Head {
oid: oid.into(),
subject: subject.into(),
author: author.into(),
stamp: stamp.into(),
date: date.into(),
})
}
reader: Reader,
}
impl Repo {
/// A repository opened through its owner and repository directories with symlinks refused;
/// every git command then runs inside that open directory.
fn open(owner: &str, name: &str) -> Option<Repo> {
Some(Repo::from_dir(owner, name, repo_dir(owner, name)?))
let mut dir = repo_dir(owner, name)?;
dir.limit_until(Instant::now() + gitv::GIT_TIMEOUT);
Some(Repo::from_dir(owner, name, dir))
}
fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo {
Repo {
signed_in: false,
dir,
owner: owner.into(),
name: name.into(),
heads: OnceCell::new(),
tags: OnceCell::new(),
}
Repo { signed_in: false, reader: Reader::new(dir), owner: owner.into(), name: name.into() }
}
fn page(&self, title: &str, body: &str) -> String {
@@ -391,21 +352,13 @@ impl Repo {
}
fn clone_address(&self) -> (&'static str, String) {
if self.dir.is_public() {
if self.reader.dir.is_public() {
("HTTPS", format!("https://{HOST}/{}/{}", self.owner, self.name))
} else {
("SSH", format!("git@{HOST}:{}/{}.git", self.owner, self.name))
}
}
fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> {
git(&self.dir, args).ok()
}
fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> {
self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned())
}
fn url(&self, view: &str, query: &[(&str, &str)]) -> String {
let query: Vec<String> =
query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v.as_bytes()))).collect();
@@ -414,8 +367,11 @@ impl Repo {
}
/// A tree, blob or raw link for a path, which may not be UTF-8.
fn url_at(&self, view: &str, reference: &str, path: &[u8], extra: &str) -> String {
let mut url = self.url(view, &[("ref", reference)]);
fn url_at(&self, view: &str, reference: &[u8], path: &[u8], extra: &str) -> String {
let mut url = self.url(view, &[]);
if !reference.is_empty() {
let _ = write!(url, "?ref={}", encode(reference));
}
if !path.is_empty() {
url.push(if url.contains('?') { '&' } else { '?' });
let _ = write!(url, "path={}", encode(path));
@@ -427,163 +383,9 @@ impl Repo {
url
}
/// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch.
fn default_ref(&self) -> String {
let head = self.git(&["symbolic-ref", "HEAD"]);
// Strip only git's newline: a branch name can end in other (Unicode) whitespace.
let head =
head.as_deref().map(|h| h.strip_suffix('\n').unwrap_or(h)).and_then(|h| h.strip_prefix("refs/heads/"));
let heads = self.heads();
let name = match head.filter(|h| heads.iter().any(|b| b == h)) {
Some(head) => head.to_string(),
None => match ["main", "master"].into_iter().map(String::from).find(|b| heads.contains(b)) {
Some(branch) => branch,
None => match heads.first() {
Some(first) => first.clone(),
None => return "HEAD".into(),
},
},
};
// In the form links use, so a branch named like a commit id still opens itself.
self.branch_ref(&name)
}
/// Names under a namespace exactly as git stores them (not `refname:short`, which can
/// add `heads/` or `tags/` to tell apart a branch and tag of the same name).
fn list_refs(&self, namespace: &str) -> Vec<String> {
self.git(&["for-each-ref", "--format=%(refname:lstrip=2)", namespace])
.map(|s| s.lines().map(str::to_string).collect())
.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 reference names, in this order:
///
/// - `refs/heads/NAME` or `refs/tags/NAME` for an existing branch or tag: the form links
/// use whenever a plain name could be misread (see [`Repo::branch_ref`]);
/// - a full commit id, always as an object, whatever refs are named;
/// - a branch, then a tag, by exact name, so any name git allows works and none is read as
/// revision syntax;
/// - `HEAD`, then an abbreviated commit id, again only as an object.
fn resolve(&self, reference: &str) -> Option<String> {
let is_head = |n: &str| self.heads().iter().any(|h| h == n);
let is_tag = |n: &str| self.tags().iter().any(|t| t == n);
let hex = reference.bytes().all(|b| b.is_ascii_hexdigit());
let full = if let Some(name) = reference.strip_prefix("refs/heads/").filter(|n| is_head(n)) {
format!("refs/heads/{name}")
} else if let Some(name) = reference.strip_prefix("refs/tags/").filter(|n| is_tag(n)) {
format!("refs/tags/{name}")
} else if hex && matches!(reference.len(), 40 | 64) {
return self.commit_object(reference);
} else if is_head(reference) {
format!("refs/heads/{reference}")
} else if is_tag(reference) {
format!("refs/tags/{reference}")
} else if reference == "HEAD" {
"HEAD".to_string()
} else if hex && reference.len() >= 4 {
return self.commit_object(reference);
} else {
return None;
};
let spec = format!("{full}^{{commit}}");
self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into())
}
/// The commit whose id is or starts with `id`, looked up among objects only: a branch or
/// tag that happens to be named like an id can't redirect it. Annotated tag objects peel to
/// their commit. An ambiguous abbreviation finds nothing.
fn commit_object(&self, id: &str) -> Option<String> {
if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let id = id.to_ascii_lowercase();
let candidates = self.git(&["rev-parse", &format!("--disambiguate={id}")])?;
let found: Vec<String> = candidates
.lines()
.filter_map(|oid| {
// A full id: git reads 40 or 64 hex digits as an object before any ref.
let peeled = self.git(&["rev-parse", "--verify", "--quiet", &format!("{oid}^{{commit}}")])?;
Some(peeled.trim().to_string())
})
.collect();
match found.as_slice() {
[one] => Some(one.clone()),
_ => None,
}
}
/// Whether a plain name in a link would resolve to itself: it mustn't look like a full
/// commit id or a qualified ref, which [`Repo::resolve`] reads first.
fn plain_is_safe(name: &str) -> bool {
let full_id = matches!(name.len(), 40 | 64) && name.bytes().all(|b| b.is_ascii_hexdigit());
!full_id && !name.starts_with("refs/") && name != "HEAD"
}
/// How a link names a branch: plainly when that can't be misread, else `refs/heads/NAME`.
fn branch_ref(&self, name: &str) -> String {
if Self::plain_is_safe(name) { name.to_string() } else { format!("refs/heads/{name}") }
}
/// How a link names a tag: plainly when that can't be misread or taken by a same-named
/// branch, else `refs/tags/NAME`.
fn tag_ref(&self, name: &str) -> String {
if Self::plain_is_safe(name) && !self.heads().iter().any(|h| h == name) {
name.to_string()
} else {
format!("refs/tags/{name}")
}
}
/// The newest commit on `rev` that touched `path` (the whole tree when empty). Walking
/// history for a path can be slow, so answers for a fixed commit are cached.
fn latest(&self, rev: &str, path: &[u8]) -> Option<Head> {
Head::parse(&self.latest_raw(rev, path)?)
}
/// [`Repo::latest`] as git printed it, for callers that cache it themselves.
fn latest_raw(&self, rev: &str, path: &[u8]) -> Option<String> {
let lookup = || {
let mut args: Vec<&OsStr> =
["log", "-1", "--date=format:%-d %b %Y", "--format=%H%x1f%an%x1f%ct%x1f%cd%x1f%s", rev, "--"]
.map(OsStr::new)
.to_vec();
if !path.is_empty() {
args.push(OsStr::from_bytes(path));
}
self.git(&args).filter(|out| !out.trim().is_empty())
};
let is_oid = rev.len() >= 40 && rev.bytes().all(|b| b.is_ascii_hexdigit());
if is_oid {
Some(cached(format!("latest:{}:{rev}:{}", self.dir.path.display(), encode(path)), lookup)?.to_string())
} else {
lookup()
}
}
/// Latest change to one entry at this immutable revision. Keep the original path bytes
/// for Git and cache the timestamp itself so relative dates stay fresh.
fn entry_commit(&self, commit: &str, path: &[u8]) -> Option<templates::EntryCommit> {
let key = self.key("entry-commit", commit, &encode(path));
let record = cached(key, || {
let args = [
"log",
"-1",
"--date=format:%-d %b %Y, %H:%M:%S %z",
"--format=%H%x00%ct%x00%cI%x00%cd%x00%s%x00%B",
commit,
"--",
]
.map(OsStr::new);
self.git(&[args.as_slice(), &[OsStr::from_bytes(path)]].concat()).filter(|out| !out.is_empty())
})?;
fn entry_commit(&self, record: &str) -> Option<templates::EntryCommit> {
let mut fields = record.splitn(6, '\0');
let oid = fields.next()?;
let stamp = fields.next()?;
@@ -601,41 +403,18 @@ impl Repo {
})
}
/// 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.dir.path.display());
cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string()))
.and_then(|count| count.parse().ok())
.unwrap_or(0)
}
/// Tag names grouped by the commit they point at, for labelling history.
fn tags_by_commit(&self) -> HashMap<String, Vec<String>> {
let mut found: HashMap<String, Vec<String>> = HashMap::new();
let out = self.git(&["for-each-ref", "--format=%(objectname) %(*objectname) %(refname:lstrip=2)", "refs/tags"]);
for line in out.unwrap_or_default().lines() {
// Tag names can't contain spaces, but an unpeeled tag leaves the middle field empty.
let mut fields = line.splitn(3, ' ');
if let (Some(direct), Some(peeled), Some(name)) = (fields.next(), fields.next(), fields.next()) {
let commit = if peeled.is_empty() { direct } else { peeled };
found.entry(commit.to_string()).or_default().push(name.to_string());
}
}
found
}
/// A cache key for rendered content of `oid` that links within this repository.
fn key(&self, kind: &str, oid: &str, extra: &str) -> String {
format!("{kind}:{}/{}:{oid}:{extra}", self.owner, self.name)
}
/// Render a Markdown file from directory `dir`, linking repository paths at `reference`.
fn markdown(&self, source: &str, dir: &[u8], reference: &str) -> String {
fn markdown(&self, source: &str, dir: &[u8], reference: &[u8]) -> String {
render::markdown(source, dir, &|path, image| {
if image {
self.url_at("raw", reference, path, "")
} else if path.is_empty() {
self.url("tree", &[("ref", reference)])
self.url_at("tree", reference, b"", "")
} else {
self.url_at("blob", reference, path, "")
}
@@ -644,15 +423,19 @@ impl Repo {
/// Name, clone address and tabs, shared by every repository page. `commit` is `reference`
/// already resolved, when the caller has it.
fn masthead(&self, active: &str, reference: &str, commit: Option<&str>) -> String {
let commit = commit.map(str::to_string).or_else(|| self.resolve(reference));
let commits = commit.map_or(0, |c| self.commit_count(&c));
let tags = self.tags().len();
fn masthead(&self, active: &str, reference: &[u8], commit: Option<&str>) -> String {
let commit = commit.map(str::to_string).or_else(|| self.reader.resolve(reference));
let commits = commit.map_or(0, |c| self.reader.commit_count(&c));
let tags = self.reader.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)] };
let tab_ref = if view == "tags" { b"" } else { reference };
let badge = count.map_or(String::new(), |n| format!(r#"<span class="n">{n}</span>"#));
format!(r#"<a href="{}"{current}>{}{label}{badge}</a>"#, attr(&self.url(view, query)), icon(glyph))
format!(
r#"<a href="{}"{current}>{}{label}{badge}</a>"#,
attr(&self.url_at(view, tab_ref, b"", "")),
icon(glyph)
)
};
let (protocol, address) = self.clone_address();
format!(
@@ -669,15 +452,15 @@ impl Repo {
}
/// Branch and tag menu, then the path as breadcrumbs.
fn locator(&self, view: &str, reference: &str, path: &[u8]) -> String {
fn locator(&self, view: &str, reference: &[u8], path: &[u8]) -> String {
// `link` is what the URL carries; `name` is what people see.
let item = |link: String, name: &str| {
let item = |link: Vec<u8>, name: &[u8]| {
let current = if link == reference { r#" aria-current="true""# } else { "" };
let href = self.url_at(view, &link, path, "");
format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name))
format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(&lossy(name)))
};
let branches: String = self.heads().iter().map(|b| item(self.branch_ref(b), b)).collect();
let tags: String = self.tags().iter().map(|t| item(self.tag_ref(t), t)).collect();
let branches: String = self.reader.heads().iter().map(|b| item(self.reader.branch_ref(b), b)).collect();
let tags: String = self.reader.tags().iter().map(|t| item(self.reader.tag_ref(t), t)).collect();
let mut menu = format!("<h2>Branches</h2>{branches}");
if !tags.is_empty() {
menu += &format!("<h2>Tags</h2>{tags}");
@@ -687,7 +470,7 @@ impl Repo {
let _ = write!(
crumbs,
r#"<a href="{}">{}</a>"#,
attr(&self.url("tree", &[("ref", reference)])),
attr(&self.url_at("tree", reference, b"", "")),
esc(&self.name)
);
let parts: Vec<&[u8]> = path.split(|b| *b == b'/').collect();
@@ -706,10 +489,12 @@ impl Repo {
r#"<div class="locator"><details class="refmenu"><summary>{}{}{}</summary><div class="menu">{menu}</div></details>
{crumbs}</div>"#,
icon("branch"),
esc(reference
.strip_prefix("refs/heads/")
.or_else(|| reference.strip_prefix("refs/tags/"))
.unwrap_or(reference)),
esc(&lossy(
reference
.strip_prefix(b"refs/heads/")
.or_else(|| reference.strip_prefix(b"refs/tags/"))
.unwrap_or(reference)
)),
icon("chevron"),
)
}
@@ -758,7 +543,7 @@ fn entry(repo: &Repo, commit: &str, path: &[u8]) -> Option<Entry> {
OsStr::new("--"),
OsStr::from_bytes(path),
];
let out = repo.git_bytes(&args)?;
let out = repo.reader.git_bytes(&args)?;
Entry::list(&out).into_iter().find(|e| e.name == path)
}
@@ -793,17 +578,13 @@ fn refs_fingerprint(repo: &RepoDir) -> Option<String> {
/// makes the whole fingerprint `None`, so a partial one is never trusted.
fn walk(stamp: &mut String, dir: &OwnedFd) -> Option<()> {
note(stamp, dir)?;
let mut names = try_entries(dir).ok()?;
let mut names = try_subdirs(dir).ok()?;
names.sort();
// Ref files (and entries deleted since the listing) are covered by their directory's
// time; only subdirectories need visiting.
for name in names {
// An entry that can't be inspected might be a folder; a fingerprint that skipped it
// could miss a change, so the whole fingerprint is abandoned instead.
if try_kind_at(dir, &name).ok()? == Some(SFlag::S_IFDIR) {
stamp.push('/');
walk(stamp, &open_dir_at(dir, &name).ok()?)?;
}
stamp.push('/');
walk(stamp, &open_dir_at(dir, &name).ok()?)?;
}
Some(())
}
@@ -843,6 +624,7 @@ struct Row {
}
fn view_index(signed_in: bool) -> View {
let deadline = Instant::now() + gitv::GIT_TIMEOUT;
let mut rows = Vec::new();
let root = open_root();
for owner in root.as_ref().map(sorted_names).unwrap_or_default() {
@@ -850,23 +632,26 @@ fn view_index(signed_in: bool) -> View {
let Some(owner_dir) = open_owner(&owner) else { continue };
for entry in sorted_names(&owner_dir) {
let Some(name) = entry.strip_suffix(".git") else { continue };
let Some(dir) = repo_in(&owner_dir, &owner, name) else { continue };
if Instant::now() >= deadline {
return View::Busy;
}
let Some(mut dir) = repo_in(&owner_dir, &owner, name) else { continue };
let public = dir.is_public();
if !signed_in && !public {
continue;
}
dir.limit_until(deadline);
let repo = Repo::from_dir(&owner, name, dir);
// HEAD usually names a real branch; only look further when it doesn't. An empty
// repository caches as an empty answer.
let lookup = || {
Some(
repo.latest_raw("HEAD", b"")
.or_else(|| repo.latest_raw(&repo.default_ref(), b""))
.unwrap_or_default(),
)
let latest = repo.reader.latest_raw("HEAD", b"").or_else(|| {
repo.reader.resolve(&repo.reader.default_ref()).and_then(|id| repo.reader.latest_raw(&id, b""))
});
(Instant::now() < deadline).then(|| latest.unwrap_or_default())
};
let raw = match refs_fingerprint(&repo.dir) {
Some(stamp) => cached(format!("index:{}:{stamp}", repo.dir.path.display()), lookup),
let raw = match refs_fingerprint(&repo.reader.dir) {
Some(stamp) => cached(format!("index:{}:{stamp}", repo.reader.dir.path.display()), lookup),
None => lookup().map(Arc::from),
};
let head = raw.as_deref().and_then(Head::parse);
@@ -893,10 +678,10 @@ fn view_index(signed_in: bool) -> View {
}
fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref());
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref());
let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?;
let Some(commit) = repo.resolve(&reference) else {
if !repo.heads().is_empty() {
let Some(commit) = repo.reader.resolve(&reference) else {
if !repo.reader.heads().is_empty() {
return None;
}
let body = repo.masthead("tree", &reference, None)
@@ -909,7 +694,7 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
return Some(View::Html(repo.page(&format!("{}/{}", repo.owner, repo.name), &body)));
};
let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)];
let Some(listing) = repo.git_bytes(&listing) else {
let Some(listing) = repo.reader.git_bytes(&listing) else {
// A file path: show it in the file view instead.
return entry(repo, &commit, &path)
.filter(|e| e.kind == "blob")
@@ -919,30 +704,16 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
// Folders first, then files and submodules, each alphabetically.
entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase()));
let mut body = repo.masthead("tree", &reference, Some(&commit)) + &repo.locator("tree", &reference, &path);
body += r#"<div class="panel">"#;
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(subject_or_placeholder(&head.subject)),
repo.sha_link(&head.oid),
ago(&head.stamp, &head.date)
);
}
body += r#"<ul class="rows tree-list">"#;
if !path.is_empty() {
let up = repo.url_at("tree", &reference, parent_of(&path), "");
let _ = write!(
body,
r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#,
attr(&up),
icon("up")
);
let page: usize = param(q, "page").and_then(|n| n.parse().ok()).unwrap_or(0);
let offset = page.checked_mul(PAGE)?;
if page != 0 && offset >= entries.len() {
return None;
}
for item in &entries {
let mut rows = Vec::new();
let visible = &entries[offset..entries.len().min(offset + PAGE)];
let names: Vec<_> = visible.iter().map(|item| item.name.as_slice()).collect();
let histories = repo.reader.entry_histories(&commit, &path, &names);
for (item, record) in visible.iter().zip(histories) {
let path = join(&path, &item.name);
let (view, class, glyph) = match item.kind.as_str() {
"tree" => (Some("tree"), "entry dir", "dir"),
@@ -955,16 +726,15 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
icon: icon(glyph),
href: view.map(|view| repo.url_at(view, &reference, &path, "")),
short_id: &item.oid[..item.oid.len().min(7)],
commit: repo.entry_commit(&commit, &path),
commit: record.as_deref().and_then(|record| repo.entry_commit(record)),
};
let _ = write!(body, "{row}");
rows.push(row);
}
body += "</ul></div>";
let page_url = |number| repo.url_at("tree", &reference, &path, &format!("page={number}"));
// README.md over README or README.txt, as people expect.
let readmes = entries.iter().filter(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with(b"readme"));
let readme = readmes.clone().find(|e| render::is_markdown(&lossy(&e.name))).or_else(|| readmes.clone().next());
if let Some(readme) = readme.filter(|e| e.size <= SHOW_LIMIT) {
let readme = readme.filter(|e| e.size <= SHOW_LIMIT).map(|readme| {
let name = lossy(&readme.name);
let rendered =
render_file(repo, &readme.oid, readme.size, &name, &path, &reference, !render::is_markdown(&name));
@@ -972,19 +742,35 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
.as_deref()
.and_then(|r| r.split_once('\x1f'))
.map_or(r#"<p class="note">This README couldn't be read.</p>"#, |(_, html)| html);
let _ = write!(
body,
r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#,
icon("book"),
esc(&name)
);
}
(name.into_owned(), content.to_string())
});
let title = if path.is_empty() {
format!("{}/{}", repo.owner, repo.name)
} else {
format!("{} at {reference}", lossy(&path))
format!("{} at {}", lossy(&path), lossy(&reference))
};
Some(View::Html(repo.page(&title, &body)))
let head = repo.reader.latest(&commit, &path).map(|head| templates::TreeHead {
url: repo.url("commit", &[("id", &head.oid)]),
sha_link: repo.sha_link(&head.oid),
subject: subject_or_placeholder(&head.subject).to_string(),
author: head.author,
when: ago(&head.stamp, &head.date),
});
Some(View::Html(
templates::Tree {
title,
signed_in: repo.signed_in,
masthead: repo.masthead("tree", &reference, Some(&commit)),
locator: repo.locator("tree", &reference, &path),
head,
up: (!path.is_empty()).then(|| repo.url_at("tree", &reference, parent_of(&path), "")),
rows,
previous: page.checked_sub(1).map(page_url),
next: (entries.len() - offset > PAGE).then(|| page_url(page + 1)),
readme,
}
.to_string(),
))
}
/// A file rendered for display, as `facts` 0x1f `html`: highlighted code, or Markdown with
@@ -998,7 +784,7 @@ fn render_file(
file_size: usize,
name: &str,
dir: &[u8],
reference: &str,
reference: &[u8],
as_code: bool,
) -> Option<Arc<str>> {
let key = if as_code {
@@ -1006,10 +792,10 @@ fn render_file(
format!("code:{oid}:{name}")
} else {
// Links depend on the repository, folder and ref too.
repo.key("md", oid, &format!("{}:{reference}", encode(dir)))
repo.key("md", oid, &format!("{}:{}", encode(dir), encode(reference)))
};
cached(key, || {
let data = repo.git_bytes(&["cat-file", "blob", oid])?;
let data = repo.reader.git_bytes(&["cat-file", "blob", oid])?;
if data.iter().take(8000).any(|b| *b == 0) {
let note = r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#;
return Some(format!("{}\x1f{note}", size(file_size)));
@@ -1036,9 +822,9 @@ fn code_view(path: &str, text: &str) -> String {
}
fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref());
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref());
let path = clean_path(q.get("path")?)?;
let commit = repo.resolve(&reference)?;
let commit = repo.reader.resolve(&reference)?;
let item = entry(repo, &commit, &path)?;
match item.kind.as_str() {
"blob" => {}
@@ -1060,20 +846,9 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
),
)));
}
let data = repo.git_bytes(&["cat-file", "blob", &item.oid])?;
let binary = data.iter().take(8000).any(|b| *b == 0);
let kind = match name.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",
};
let download = (kind == "application/octet-stream").then(|| file_name(&path).to_vec());
return Some(View::Raw(data, kind, download));
let mut command = gitv::git_command(&repo.reader.dir);
command.args(["cat-file", "blob", &item.oid]);
return Some(View::Raw(Box::new(command), item.size, file_name(&path).to_vec()));
}
let too_big = item.size > SHOW_LIMIT;
@@ -1113,32 +888,35 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
icon("file"),
esc(&name)
);
Some(View::Html(repo.page(&format!("{} at {reference}", lossy(&path)), &body)))
Some(View::Html(repo.page(&format!("{} at {}", lossy(&path), lossy(&reference)), &body)))
}
fn view_log(repo: &Repo, q: &Q) -> Option<View> {
let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref());
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref());
let number: usize = param(q, "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(&[
let commit = repo.reader.resolve(&reference)?;
let out = repo.reader.git(&[
"log",
&format!("-n{}", PAGE + 1),
&format!("--skip={skip}"),
"--date=format:%-d %b %Y",
"--format=%H%x1f%an%x1f%ct%x1f%cd%x1f%s",
Head::FORMAT,
&commit,
"--",
])?;
let lines: Vec<&str> = out.lines().collect();
let tags = repo.tags_by_commit();
let tags = repo.reader.tags_by_commit();
let mut rows = Vec::new();
for head in lines.iter().take(PAGE).filter_map(|line| Head::parse(line)) {
let labels = tags
.get(&head.oid)
.into_iter()
.flatten()
.map(|name| templates::TagLink { name, url: repo.url("tree", &[("ref", &repo.tag_ref(name))]) })
.map(|name| templates::TagLink {
name: lossy(name),
url: repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""),
})
.collect();
rows.push(templates::CommitRow {
url: repo.url("commit", &[("id", &head.oid)]),
@@ -1149,10 +927,10 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> {
tags: labels,
});
}
let page_url = |n: usize| repo.url("log", &[("ref", &reference), ("page", &n.to_string())]);
let page_url = |n: usize| repo.url_at("log", &reference, b"", &format!("page={n}"));
Some(View::Html(
templates::History {
title: format!("Commits on {reference}"),
title: format!("Commits on {}", lossy(&reference)),
signed_in: repo.signed_in,
masthead: repo.masthead("log", &reference, Some(&commit)),
locator: repo.locator("log", &reference, b""),
@@ -1250,10 +1028,10 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
return None;
}
// Looked up as an object only: a branch named like this id can't redirect the page.
let commit = repo.commit_object(&id)?;
let commit = repo.reader.commit_object(&id)?;
// NUL between fields: a commit message can't contain one, so the subject and body can hold
// any other byte, the separator git output elsewhere uses included.
let meta = repo.git(&[
let meta = repo.reader.git(&[
"show",
"-s",
"--date=format:%-d %b %Y, %H:%M",
@@ -1263,32 +1041,26 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
let f: Vec<&str> = meta.splitn(7, '\0').collect();
let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).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(), None);
let message = message.trim();
let _ = write!(
body,
r#"<section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{}</h2><a class="button" href="{}">Browse files</a></div>{}</div><dl class="facts">
<div><dt>Author</dt><dd>{} <span class="quiet">{}</span></dd></div><div><dt>Date</dt><dd>{}</dd></div>
<div><dt>Commit</dt><dd><span class="sha">{}</span></dd></div>{}</dl></section>"#,
esc(subject_or_placeholder(subject)),
attr(&repo.url("tree", &[("ref", oid)])),
if message.is_empty() { String::new() } else { format!(r#"<p class="cbody">{}</p>"#, esc(message)) },
esc(author),
esc(email),
esc(date),
&oid[..12],
if parent_links.is_empty() {
String::new()
} else {
format!("<div><dt>Parent</dt><dd>{parent_links}</dd></div>")
}
);
// A commit's diff never changes, so its rendering is cached. If git can't produce it, the
// page still shows the commit, with a note.
let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents))
.unwrap_or_else(|| r#"<p class="note">This commit’s changes couldn’t be read.</p>"#.into());
body += &diff;
Some(View::Html(repo.page(subject_or_placeholder(subject), &body)))
Some(View::Html(
templates::Commit {
title: subject_or_placeholder(subject),
signed_in: repo.signed_in,
masthead: repo.masthead("log", &repo.reader.default_ref(), None),
browse: repo.url("tree", &[("ref", oid)]),
message: message.trim(),
author,
email,
date,
short_id: oid.get(..12)?,
parent_links,
diff: &diff,
}
.to_string(),
))
}
/// A commit's changes as one panel per file. Only [`DIFF_LIMIT`] bytes of patch are read; past
@@ -1296,10 +1068,10 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> {
// A merge shows what it brought in relative to its first parent.
let options = ["--format=", "--no-color", "-M", "--diff-merges=first-parent"];
let names = repo.git_bytes(&[&["show", "-z", "--name-status"][..], &options, &[oid]].concat())?;
let names = repo.reader.git_bytes(&[&["show", "-z", "--name-status"][..], &options, &[oid]].concat())?;
let changes = parse_changes(&names);
let (patch, too_big) =
git_capped(&repo.dir, &[&["show", "--patch"][..], &options, &[oid]].concat(), DIFF_LIMIT).ok()?;
git_capped(&repo.reader.dir, &[&["show", "--patch"][..], &options, &[oid]].concat(), DIFF_LIMIT).ok()?;
let files = if too_big { Vec::new() } else { parse_diff(&String::from_utf8_lossy(&patch)) };
// The two listings come from the same diff, in the same order; if they ever disagree, show
// names only rather than pair lines with the wrong file.
@@ -1325,7 +1097,7 @@ fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> {
};
// A deleted file still exists in the parent commit.
let at = if change.status == "Deleted" { parents.split_whitespace().next().unwrap_or(oid) } else { oid };
let link = repo.url_at("blob", at, &change.path, "");
let link = repo.url_at("blob", at.as_bytes(), &change.path, "");
let counts = file.map_or(String::new(), |f| {
format!(r#"<span class="plus">+{}</span><span class="minus">−{}</span>"#, f.added, f.removed)
});
@@ -1367,23 +1139,23 @@ fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> {
}
fn view_tags(repo: &Repo) -> Option<View> {
let out = repo.git(&[
let out = repo.reader.git_bytes(&[
"for-each-ref",
"--sort=-creatordate",
"--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:format:%-d %b %Y)%1f%(objecttype)%1f%(contents:subject)",
"refs/tags",
])?;
let mut rows = String::new();
for line in out.lines() {
for line in out.split(|b| *b == b'\n') {
// The tag's message goes last, so one containing the separator stays whole.
let Ok([name, direct, peeled, stamp, date, kind, note]) =
<[&str; 7]>::try_from(line.splitn(7, '\x1f').collect::<Vec<_>>())
<[&[u8]; 7]>::try_from(line.splitn(7, |b| *b == 0x1f).collect::<Vec<_>>())
else {
continue;
};
let target = if peeled.is_empty() { direct } else { peeled };
let note = if kind == "tag" && !note.is_empty() {
format!(r#"<span class="tnote">{}</span>"#, esc(note))
let note = if kind == b"tag" && !note.is_empty() {
format!(r#"<span class="tnote">{}</span>"#, esc(&lossy(note)))
} else {
String::new()
};
@@ -1391,10 +1163,10 @@ fn view_tags(repo: &Repo) -> Option<View> {
rows,
r#"<li class="tag-row"><span class="tname">{}</span>{note}<span class="tmeta">{}{}</span>
<span class="tacts"><a class="button" href="{}">Browse files</a></span></li>"#,
esc(name),
repo.sha_link(target),
ago(stamp, date),
attr(&repo.url("tree", &[("ref", &repo.tag_ref(name))]))
esc(&lossy(name)),
repo.sha_link(&lossy(target)),
ago(&lossy(stamp), &lossy(date)),
attr(&repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""))
);
}
let listing = if rows.is_empty() {
@@ -1402,7 +1174,7 @@ fn view_tags(repo: &Repo) -> Option<View> {
} else {
format!(r#"<div class="panel"><ul class="rows">{rows}</ul></div>"#)
};
let body = repo.masthead("tags", &repo.default_ref(), None) + &listing;
let body = repo.masthead("tags", &repo.reader.default_ref(), None) + &listing;
Some(View::Html(repo.page(&format!("Tags in {}/{}", repo.owner, repo.name), &body)))
}
@@ -1410,7 +1182,7 @@ fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) ->
let Some(mut repo) = Repo::open(owner, name) else {
return if signed_in { View::Missing(true) } else { View::LoginRequired };
};
if !signed_in && !repo.dir.is_public() {
if !signed_in && !repo.reader.dir.is_public() {
return View::LoginRequired;
}
repo.signed_in = signed_in;
@@ -1427,23 +1199,60 @@ fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) ->
result.unwrap_or(View::Missing(signed_in))
}
/// Pages rendered at once. Each runs several git processes, so a burst of requests queues
/// here instead of starting hundreds of them.
/// Maximum simultaneous render jobs. Reject excess requests before queuing blocking work.
static RENDERS: LazyLock<Arc<tokio::sync::Semaphore>> = LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(16)));
async fn raw_response(command: std::process::Command, size: usize, name: Vec<u8>) -> Response {
let Ok(permit) = git_stream::RAW_TRANSFERS.try_acquire() else {
return StatusCode::SERVICE_UNAVAILABLE.into_response();
};
let Ok(mut output) = git_stream::Output::start(command.into()) else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let Ok(prefix) = output.prefix(size.min(8000)).await else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let binary = prefix.contains(&0);
let filename = lossy(&name);
let kind = match filename.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",
};
let body = output.body(prefix, None, permit, std::time::Duration::from_secs(300));
let mut response = (SECURITY, [(header::CONTENT_TYPE, kind)], body).into_response();
response.headers_mut().insert(header::CONTENT_LENGTH, size.into());
if kind == "application/octet-stream"
&& let Ok(value) = format!("attachment; filename*=UTF-8''{}", encode(&name)).parse()
{
response.headers_mut().insert(header::CONTENT_DISPOSITION, value);
}
response
}
/// Git calls block, so every page renders on the blocking pool. The permit moves into the
/// blocking work itself: if the request is cancelled while rendering, the slot stays taken
/// until the work actually ends.
async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View {
let Ok(permit) = Arc::clone(&RENDERS).acquire_owned().await else { return View::Missing(false) };
async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> Response {
let Ok(permit) = Arc::clone(&RENDERS).try_acquire_owned() else {
return StatusCode::SERVICE_UNAVAILABLE.into_response();
};
let work = move || {
let _permit = permit;
f()
let started = Instant::now();
let view = f();
if started.elapsed() >= gitv::GIT_TIMEOUT { View::Busy } else { view }
};
tokio::task::spawn_blocking(work).await.unwrap_or_else(|error| {
let view = tokio::task::spawn_blocking(work).await.unwrap_or_else(|error| {
eprintln!("gitv-web: a page failed to render: {error}");
View::Missing(false)
})
});
view.response().await
}
fn main() -> std::process::ExitCode {
@@ -1485,7 +1294,7 @@ fn serve(port: u16) -> Result<(), String> {
"/account",
get(login::account).post(login::change_password).layer(DefaultBodyLimit::max(login::FORM_LIMIT)),
)
.fallback(|| async { View::Missing(true) })
.fallback(|| View::Missing(true).response())
.layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login));
let browse = Router::new()
.route("/", get(|Extension(user): Extension<bool>| blocking(move || view_index(user))))
@@ -1526,6 +1335,15 @@ fn serve(port: u16) -> Result<(), String> {
mod tests {
use super::*;
#[tokio::test]
async fn saturated_render_pool_returns_busy_without_starting_work() {
let permits = RENDERS.try_acquire_many(RENDERS.available_permits() as u32).unwrap();
let response = blocking(|| panic!("excess render was admitted")).await;
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
drop(permits);
assert_eq!(blocking(|| View::Html(String::new())).await.status(), StatusCode::OK);
}
#[test]
fn percent_decoding_keeps_raw_bytes() {
assert_eq!(percent_decode("a%2Fb+c"), b"a/b+c", "a plus is literal outside query strings");
@@ -0,0 +1,323 @@
//! Git queries on an already-open repository. Ref and path identities remain byte strings.
use super::{cached, encode, join, lossy};
use gitv::{RepoDir, git};
use std::{sync::Arc, time::Duration};
const ENTRY_FORMAT: &str = "%H%x00%ct%x00%cI%x00%cd%x00%s%x00%B";
const ENTRY_DATE: &str = "--date=format:%-d %b %Y, %H:%M:%S %z";
use std::{cell::OnceCell, collections::HashMap, ffi::OsStr, os::unix::ffi::OsStrExt};
pub(super) struct Reader {
pub(super) dir: RepoDir,
heads: OnceCell<Vec<Vec<u8>>>,
tags: OnceCell<Vec<Vec<u8>>>,
}
/// The newest commit on a ref: full hash, subject, author, unix time, short date.
pub(super) struct Head {
pub(super) oid: String,
pub(super) subject: String,
pub(super) author: String,
pub(super) stamp: String,
pub(super) date: String,
}
impl Head {
pub(super) const FORMAT: &'static str = "--format=%H%x00%an%x00%ct%x00%cd%x00%s";
pub(super) fn parse(out: &str) -> Option<Head> {
let f: Vec<&str> = out.trim_end_matches('\n').splitn(5, '\0').collect();
let [oid, author, stamp, date, subject] = <[&str; 5]>::try_from(f).ok()?;
Some(Head {
oid: oid.into(),
subject: subject.into(),
author: author.into(),
stamp: stamp.into(),
date: date.into(),
})
}
}
impl Reader {
pub(super) fn new(dir: RepoDir) -> Self {
Self { dir, heads: OnceCell::new(), tags: OnceCell::new() }
}
pub(super) fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> {
git(&self.dir, args).ok()
}
pub(super) fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> {
self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned())
}
/// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch.
pub(super) fn default_ref(&self) -> Vec<u8> {
let head = self.git_bytes(&["symbolic-ref", "HEAD"]).unwrap_or_default();
let heads = self.heads();
let target = head.strip_suffix(b"\n").and_then(|h| h.strip_prefix(b"refs/heads/"));
let choice = target
.into_iter()
.chain([b"main".as_slice(), b"master"])
.find(|name| heads.iter().any(|h| h == name))
.or_else(|| heads.first().map(Vec::as_slice));
choice.map_or_else(|| b"HEAD".to_vec(), |name| self.branch_ref(name))
}
fn list_refs(&self, namespace: &str) -> Vec<Vec<u8>> {
self.git_bytes(&["for-each-ref", "--format=%(refname:lstrip=2)", namespace])
.unwrap_or_default()
.split(|b| *b == b'\n')
.filter(|r| !r.is_empty())
.map(<[u8]>::to_vec)
.collect()
}
pub(super) fn heads(&self) -> &[Vec<u8>] {
self.heads.get_or_init(|| self.list_refs("refs/heads"))
}
pub(super) fn tags(&self) -> &[Vec<u8>] {
self.tags.get_or_init(|| self.list_refs("refs/tags"))
}
/// The commit a reference names, in this order:
///
/// - `refs/heads/NAME` or `refs/tags/NAME` for an existing branch or tag: the form links
/// use whenever a plain name could be misread (see [`Reader::branch_ref`]);
/// - a full commit id, always as an object, whatever refs are named;
/// - a branch, then a tag, by exact name, so any name git allows works and none is read as
/// revision syntax;
/// - `HEAD`, then an abbreviated commit id, again only as an object.
pub(super) fn resolve(&self, reference: &[u8]) -> Option<String> {
let is_head = |n: &[u8]| self.heads().iter().any(|h| h == n);
let is_tag = |n: &[u8]| self.tags().iter().any(|h| h == n);
let hex = reference.iter().all(u8::is_ascii_hexdigit);
let full = if reference.strip_prefix(b"refs/heads/").is_some_and(is_head)
|| reference.strip_prefix(b"refs/tags/").is_some_and(is_tag)
{
reference.to_vec()
} else if hex && matches!(reference.len(), 40 | 64) {
return self.commit_object(std::str::from_utf8(reference).ok()?);
} else if is_head(reference) {
[b"refs/heads/".as_slice(), reference].concat()
} else if is_tag(reference) {
[b"refs/tags/".as_slice(), reference].concat()
} else if reference == b"HEAD" {
reference.to_vec()
} else if hex && reference.len() >= 4 {
return self.commit_object(std::str::from_utf8(reference).ok()?);
} else {
return None;
};
let spec = [full.as_slice(), b"^{commit}"].concat();
let args = ["rev-parse", "--verify", "--quiet", "--end-of-options"].map(OsStr::new);
self.git(&[args.as_slice(), &[OsStr::from_bytes(&spec)]].concat()).map(|s| s.trim().into())
}
/// The commit whose id is or starts with `id`, looked up among objects only: a branch or
/// tag that happens to be named like an id can't redirect it. Annotated tag objects peel to
/// their commit. An ambiguous abbreviation finds nothing.
pub(super) fn commit_object(&self, id: &str) -> Option<String> {
if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let id = id.to_ascii_lowercase();
let candidates = self.git(&["rev-parse", &format!("--disambiguate={id}")])?;
let found: Vec<String> = candidates
.lines()
.filter_map(|oid| {
// A full id: git reads 40 or 64 hex digits as an object before any ref.
let peeled = self.git(&["rev-parse", "--verify", "--quiet", &format!("{oid}^{{commit}}")])?;
Some(peeled.trim().to_string())
})
.collect();
match found.as_slice() {
[one] => Some(one.clone()),
_ => None,
}
}
/// Whether a plain name in a link would resolve to itself: it mustn't look like a full
/// commit id or a qualified ref, which [`Reader::resolve`] reads first.
fn plain_is_safe(name: &[u8]) -> bool {
let full_id = matches!(name.len(), 40 | 64) && name.iter().all(u8::is_ascii_hexdigit);
!full_id && !name.starts_with(b"refs/") && name != b"HEAD"
}
pub(super) fn branch_ref(&self, name: &[u8]) -> Vec<u8> {
if Self::plain_is_safe(name) { name.to_vec() } else { [b"refs/heads/".as_slice(), name].concat() }
}
pub(super) fn tag_ref(&self, name: &[u8]) -> Vec<u8> {
if Self::plain_is_safe(name) && !self.heads().iter().any(|h| h == name) {
name.to_vec()
} else {
[b"refs/tags/".as_slice(), name].concat()
}
}
/// The newest commit on `rev` that touched `path` (the whole tree when empty). Walking
/// history for a path can be slow, so answers for a fixed commit are cached.
pub(super) fn latest(&self, rev: &str, path: &[u8]) -> Option<Head> {
Head::parse(&self.latest_raw(rev, path)?)
}
/// [`Reader::latest`] as git printed it, for callers that cache it themselves.
pub(super) fn latest_raw(&self, rev: &str, path: &[u8]) -> Option<String> {
let lookup = || {
let mut args: Vec<&OsStr> =
["log", "-1", "--date=format:%-d %b %Y", Head::FORMAT, rev, "--"].map(OsStr::new).to_vec();
if !path.is_empty() {
args.push(OsStr::from_bytes(path));
}
self.git(&args).filter(|out| !out.trim().is_empty())
};
let is_oid = rev.len() >= 40 && rev.bytes().all(|b| b.is_ascii_hexdigit());
if is_oid {
Some(cached(format!("latest:{}:{rev}:{}", self.dir.path.display(), encode(path)), lookup)?.to_string())
} else {
lookup()
}
}
/// Resolve just the displayed entries. A warm page needs no history query. On a cold
/// page one bounded linear walk handles recent changes, with Git's path-specific
/// history simplification retained for anything older or behind a merge.
pub(super) fn entry_histories(&self, commit: &str, dir: &[u8], names: &[&[u8]]) -> Vec<Option<Arc<str>>> {
let recent = OnceCell::new();
names
.iter()
.map(|&name| {
let path = join(dir, name);
let key = format!("entry-commit:{}:{commit}:{}", self.dir.path.display(), encode(&path));
cached(key, || {
if names.len() > 1 {
let matches = recent.get_or_init(|| self.recent_entry_histories(commit, dir, names));
if let Some(record) = matches.as_ref().and_then(|m| m.get(name)) {
return Some(record.to_string());
}
}
let format = format!("--format={ENTRY_FORMAT}");
let args = ["log", "-1", ENTRY_DATE, &format, commit, "--"].map(OsStr::new);
self.git(&[args.as_slice(), &[OsStr::from_bytes(&path)]].concat()).filter(|out| !out.is_empty())
})
})
.collect()
}
fn recent_entry_histories<'a>(
&self,
commit: &str,
dir: &[u8],
names: &[&'a [u8]],
) -> Option<HashMap<&'a [u8], Arc<str>>> {
let format = format!("--format=%x00%P%x00{ENTRY_FORMAT}");
let args = [
"log",
"-16",
"--first-parent",
"--diff-merges=off",
"--root",
"--no-renames",
"--name-only",
"-z",
ENTRY_DATE,
&format,
commit,
"--",
];
let (bytes, truncated) = gitv::git_capped_for(&self.dir, &args, 1 << 20, Duration::from_millis(500)).ok()?;
if truncated {
return None;
}
recent_changes(&bytes, dir, names)
}
/// Commits reachable from `commit`. A commit's history never changes, so the count is cached.
pub(super) fn commit_count(&self, commit: &str) -> usize {
let key = format!("count:{}:{commit}", self.dir.path.display());
cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string()))
.and_then(|count| count.parse().ok())
.unwrap_or(0)
}
/// Tag names grouped by the commit they point at, for labelling history.
pub(super) fn tags_by_commit(&self) -> HashMap<String, Vec<Vec<u8>>> {
let mut found: HashMap<String, Vec<Vec<u8>>> = HashMap::new();
let out =
self.git_bytes(&["for-each-ref", "--format=%(objectname) %(*objectname) %(refname:lstrip=2)", "refs/tags"]);
for line in out.unwrap_or_default().split(|b| *b == b'\n') {
let mut fields = line.splitn(3, |b| *b == b' ');
if let (Some(direct), Some(peeled), Some(name)) = (fields.next(), fields.next(), fields.next()) {
let commit = if peeled.is_empty() { direct } else { peeled };
found.entry(lossy(commit).into_owned()).or_default().push(name.to_vec());
}
}
found
}
}
/// A record begins with an empty NUL field (impossible as a pathname), followed by
/// parents, six metadata fields, then Git's newline and NUL-terminated changed paths.
fn recent_changes<'a>(mut data: &[u8], dir: &[u8], names: &[&'a [u8]]) -> Option<HashMap<&'a [u8], Arc<str>>> {
fn field<'b>(data: &mut &'b [u8]) -> Option<&'b [u8]> {
let end = data.iter().position(|&b| b == 0)?;
let value = &data[..end];
*data = &data[end + 1..];
Some(value)
}
let mut pending: std::collections::HashSet<_> = names.iter().copied().collect();
let mut found = HashMap::new();
while !data.is_empty() && !pending.is_empty() {
data = data.strip_prefix(b"\0")?;
if field(&mut data)?.contains(&b' ') {
break;
}
let start = data;
for _ in 0..6 {
field(&mut data)?;
}
let metadata = &start[..start.len() - data.len() - 1];
let record = OnceCell::new();
if let Some(paths) = data.strip_prefix(b"\n") {
data = paths;
while !data.is_empty() && data[0] != 0 {
let path = field(&mut data)?;
let relative = if dir.is_empty() {
path
} else {
let Some(rest) = path.strip_prefix(dir).and_then(|r| r.strip_prefix(b"/")) else { continue };
rest
};
let name = relative.split(|&b| b == b'/').next()?;
if let Some(name) = pending.take(name) {
let value = record.get_or_init(|| Arc::<str>::from(lossy(metadata)));
found.insert(name, Arc::clone(value));
}
}
}
}
Some(found)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn batch_uses_newest_change_and_stops_at_the_first_merge() {
let input = b"\0parent\0tip\0time\0iso\0date\0subject\0full\nmessage\0\nother/file\0docs/\xff/new\0docs/\nfile\0\0older\0previous\0time\0iso\0date\0subject\0message\0\ndocs/\xff/old\0\0one two\0merge\0time\0iso\0date\0subject\0message\0\ndocs/side\0";
let names = [b"\xff".as_slice(), b"\nfile", b"side", b"file"];
let result = recent_changes(input, b"docs", &names).unwrap();
assert_eq!(result.len(), 2);
for name in &names[..2] {
assert_eq!(&*result[name], "tip\0time\0iso\0date\0subject\0full\nmessage");
}
}
#[test]
fn control_characters_in_git_names_do_not_shift_fields() {
let head = Head::parse("commit\0First\x1fLast\0timestamp\0date\0subject\x1fmore").unwrap();
assert_eq!(head.author, "First\x1fLast");
assert_eq!(head.stamp, "timestamp");
assert_eq!(head.subject, "subject\x1fmore");
}
}
@@ -1,18 +1,14 @@
//! Read-only Git smart HTTP, using upload-pack's stateless protocol.
use super::git_stream::Output;
use axum::{
body::{Body, Bytes},
body::Bytes,
extract::{Path, RawQuery, Request},
http::{StatusCode, header},
response::{IntoResponse, Response},
};
use futures_util::stream;
use gitv::{git_command, repo_dir};
use std::{io, process::Stdio, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
process::Command,
sync::{Semaphore, mpsc},
};
use std::{process::Stdio, time::Duration};
use tokio::{process::Command, sync::Semaphore};
static TRANSFERS: Semaphore = Semaphore::const_new(4);
@@ -81,50 +77,10 @@ async fn transfer((owner, name): (String, String), request: Option<Request>) ->
if advertise {
cmd.arg("--advertise-refs");
}
let Ok(mut child) = cmd.arg(".").kill_on_drop(true).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn() else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let mut stdin = child.stdin.take().unwrap();
let mut stdout = child.stdout.take().unwrap();
let (tx, rx) = mpsc::channel::<io::Result<Bytes>>(2);
tokio::spawn(async move {
let _permit = permit;
let write = async move {
if let Some(input) = input {
stdin.write_all(&input).await?;
}
drop(stdin);
Ok::<_, io::Error>(())
};
let send = |bytes| async { tx.send(Ok(bytes)).await.map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe)) };
let read = async {
if advertise {
send(Bytes::from_static(b"001e# service=git-upload-pack\n0000")).await?;
}
let mut buffer = vec![0; 65536];
loop {
let count = stdout.read(&mut buffer).await?;
if count == 0 {
break;
}
send(Bytes::copy_from_slice(&buffer[..count])).await?;
}
if !child.wait().await?.success() {
return Err(io::Error::other("upload-pack failed"));
}
Ok(())
};
let work = async { tokio::try_join!(write, read).map(|_| ()) };
let result = tokio::select! {
_ = tx.closed() => return,
result = tokio::time::timeout(Duration::from_secs(300), work) => result.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into())),
};
if let Err(error) = result {
let _ = child.kill().await;
let _ = tx.try_send(Err(error));
}
});
let body = Body::from_stream(stream::unfold(rx, |mut rx| async { Some((rx.recv().await?, rx)) }));
cmd.arg(".").stdin(Stdio::piped());
let Ok(output) = Output::start(cmd) else { return StatusCode::INTERNAL_SERVER_ERROR.into_response() };
let prefix = if advertise { Bytes::from_static(b"001e# service=git-upload-pack\n0000") } else { Bytes::new() };
let body = output.body(prefix, input, permit, Duration::from_secs(300));
let kind =
if advertise { "application/x-git-upload-pack-advertisement" } else { "application/x-git-upload-pack-result" };
([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "no-store")], body).into_response()
@@ -19,7 +19,7 @@ pub(super) struct SignIn<'a> {
}
pub(super) struct TagLink<'a> {
pub name: &'a str,
pub name: std::borrow::Cow<'a, str>,
pub url: String,
}
@@ -84,3 +84,42 @@ pub(super) struct Repositories<'a> {
pub branch: String,
pub host: &'a str,
}
#[derive(Template)]
#[template(path = "commit.html")]
pub(super) struct Commit<'a> {
pub title: &'a str,
pub signed_in: bool,
pub masthead: String,
pub browse: String,
pub message: &'a str,
pub author: &'a str,
pub email: &'a str,
pub date: &'a str,
pub short_id: &'a str,
pub parent_links: String,
pub diff: &'a str,
}
pub(super) struct TreeHead {
pub author: String,
pub subject: String,
pub url: String,
pub sha_link: String,
pub when: String,
}
#[derive(Template)]
#[template(path = "tree.html")]
pub(super) struct Tree<'a> {
pub title: String,
pub signed_in: bool,
pub masthead: String,
pub locator: String,
pub head: Option<TreeHead>,
pub up: Option<String>,
pub rows: Vec<TreeRow<'a>>,
pub previous: Option<String>,
pub next: Option<String>,
pub readme: Option<(String, String)>,
}
+65−7
@@ -79,6 +79,7 @@ pub struct RepoDir {
/// Where it was found, for messages and cache keys only; never reopened.
pub path: PathBuf,
fd: OwnedFd,
deadline: Option<Instant>,
}
impl RepoDir {
@@ -86,7 +87,11 @@ impl RepoDir {
/// code finds repositories through [`repo_dir`] or [`repo_in`].
pub fn at(path: &Path) -> Option<RepoDir> {
let fd = open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW, Mode::empty()).ok()?;
Some(RepoDir { path: path.to_path_buf(), fd })
Some(RepoDir { path: path.to_path_buf(), fd, deadline: None })
}
pub fn limit_until(&mut self, deadline: Instant) {
self.deadline = Some(deadline);
}
/// A command that starts inside this directory, whatever happens to its path meanwhile.
@@ -172,6 +177,21 @@ pub fn git<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S]) -> Result<Vec<u8>, St
/// Like [`git`], but output beyond `cap` bytes stops the command and comes back truncated, with
/// `true` to say so, rather than as an error.
pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> Result<(Vec<u8>, bool), String> {
git_capped_for(git_dir, args, cap, GIT_TIMEOUT)
}
/// Apply a shorter budget to optional work while respecting the overall page deadline.
pub fn git_capped_for<S: AsRef<OsStr>>(
git_dir: &RepoDir,
args: &[S],
cap: usize,
timeout: Duration,
) -> Result<(Vec<u8>, bool), String> {
let deadline = Instant::now() + timeout.min(GIT_TIMEOUT);
let deadline = git_dir.deadline.map_or(deadline, |limit| limit.min(deadline));
if Instant::now() >= deadline {
return Err("page time budget exhausted".into());
}
let mut child = git_command(git_dir)
.args(args)
.stdout(Stdio::piped())
@@ -186,13 +206,14 @@ pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) ->
let _ = child.kill();
}
};
let deadline = Instant::now() + GIT_TIMEOUT;
// The watchdog covers a read that blocks; nobody holds the lock while blocked.
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) {
if let Err(RecvTimeoutError::Timeout) =
wait.recv_timeout(deadline.saturating_duration_since(Instant::now()))
{
kill(&child);
}
})
@@ -299,14 +320,32 @@ pub fn entries(dir: &impl AsFd) -> Vec<OsString> {
/// The names in an open directory, or the error that stopped the listing part way.
pub fn try_entries(dir: &impl AsFd) -> nix::Result<Vec<OsString>> {
list_entries(dir, false)
}
/// List only child directories, using directory-entry types when the filesystem supplies them.
pub fn try_subdirs(dir: &impl AsFd) -> nix::Result<Vec<OsString>> {
list_entries(dir, true)
}
fn list_entries(dir: &impl AsFd, directories_only: bool) -> nix::Result<Vec<OsString>> {
let fresh = openat(dir, ".", OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty())?;
let mut listing = Dir::from_fd(fresh)?;
let mut names = Vec::new();
for entry in listing.iter() {
let name = OsStr::from_bytes(entry?.file_name().to_bytes()).to_os_string();
if name != "." && name != ".." {
names.push(name);
let entry = entry?;
let name = OsStr::from_bytes(entry.file_name().to_bytes());
if name == "." || name == ".." {
continue;
}
if directories_only {
match entry.file_type() {
Some(nix::dir::Type::Directory) => {}
None if try_kind_at(dir, name)? == Some(SFlag::S_IFDIR) => {}
_ => continue,
}
}
names.push(name.to_owned());
}
Ok(names)
}
@@ -360,7 +399,7 @@ pub fn repo_in(owner_dir: &impl AsFd, owner: &str, name: &str) -> Option<RepoDir
if kind_at(&fd, OsStr::new("HEAD")) != Some(SFlag::S_IFREG) {
return None;
}
Some(RepoDir { path: repos_root().join(owner).join(file), fd })
Some(RepoDir { path: repos_root().join(owner).join(file), fd, deadline: None })
}
/// [`repo_in`], opening the owner's directory first.
@@ -390,6 +429,25 @@ mod tests {
(dir, oid)
}
#[test]
fn git_commands_share_the_page_deadline_even_while_blocked_on_io() {
let (mut dir, oid) = repo_with_blob("deadline", 10);
let pipe = dir.path.join("pending-config");
nix::unistd::mkfifo(&pipe, Mode::S_IRUSR | Mode::S_IWUSR).unwrap();
// Holding both ends open keeps Git waiting for more bytes until its watchdog fires.
let _writer = fs::OpenOptions::new().read(true).write(true).open(&pipe).unwrap();
let deadline = Instant::now() + Duration::from_millis(250);
dir.limit_until(deadline);
let result = git(&dir, &["config", "--file", "pending-config", "--list"]);
let finished = Instant::now();
assert!(result.unwrap_err().contains("SIGKILL"), "the watchdog must kill the running Git command");
assert!(finished >= deadline);
assert!(finished.duration_since(deadline) < Duration::from_secs(5), "used the per-command timeout");
// Even a fast command must be refused once the same page has spent its budget.
assert_eq!(git(&dir, &["cat-file", "-s", &oid]).unwrap_err(), "page time budget exhausted");
fs::remove_dir_all(&dir.path).unwrap();
}
#[test]
fn capped_output_stops_early_and_says_so() {
let (dir, oid) = repo_with_blob("capped", 1 << 20);
@@ -122,8 +122,19 @@ pub fn markdown(source: &str, dir: &[u8], link: &dyn Fn(&[u8], bool) -> String)
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) if url.starts_with('#') => format!("#md-{}", &url[1..]).into(),
Target::External(url) => url.into(),
Target::Repo(path) => link(&path, image).into(),
Target::Repo(path) => {
let mut url = link(&path, image);
if let Some((_, fragment)) = dest.split_once('#') {
url.push('#');
if !image && is_markdown(&String::from_utf8_lossy(&path)) {
url.push_str("md-");
}
url.push_str(fragment);
}
url.into()
}
Target::Blocked => "#".into(),
}
};
@@ -163,6 +174,49 @@ pub fn markdown(source: &str, dir: &[u8], link: &dyn Fn(&[u8], bool) -> String)
other => other,
});
}
// Derive anchors from visible heading text. Prefix them so document headings cannot
// shadow page navigation. Duplicate headings get stable suffixes.
let mut used = std::collections::HashSet::new();
let mut suffixes = std::collections::HashMap::new();
let mut heading = None;
for index in 0..events.len() {
match &events[index] {
Event::Start(Tag::Heading { .. }) => heading = Some((index, String::new())),
Event::Text(text) | Event::Code(text) => {
if let Some((_, title)) = &mut heading {
title.push_str(text);
}
}
Event::End(TagEnd::Heading(_)) => {
if let Some((start, title)) = heading.take() {
let base: String = title
.to_lowercase()
.chars()
.filter_map(|c| {
if c.is_whitespace() {
Some('-')
} else if c.is_alphanumeric() || matches!(c, '-' | '_') {
Some(c)
} else {
None
}
})
.collect();
let base = format!("md-{base}");
let mut id = base.clone();
let suffix = suffixes.entry(base.clone()).or_insert(0usize);
while !used.insert(id.clone()) {
*suffix += 1;
id = format!("{base}-{suffix}");
}
if let Event::Start(Tag::Heading { id: target, .. }) = &mut events[start] {
*target = Some(id.into());
}
}
}
_ => {}
}
}
let mut out = String::new();
pulldown_cmark::html::push_html(&mut out, events.into_iter());
out
@@ -183,11 +237,33 @@ mod tests {
assert!(!html.contains("<div"), "{html}");
}
#[test]
fn links_match_unique_heading_ids() {
let html = markdown(
"# Install *Git*
# Install Git
[second](#install-git-1) [guide](guide.md#install-git)",
b"",
&link,
);
for fragment in [
"id=\"md-install-git\"",
"id=\"md-install-git-1\"",
"href=\"#md-install-git-1\"",
"href=\"/blob?path=guide.md#md-install-git\"",
] {
assert!(html.contains(fragment), "{html}");
}
}
#[test]
fn ignores_heading_attributes() {
let html = markdown("# Title {onclick=alert(1) #main .skip style=x}", b"", &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>");
assert!(html.contains(">Title {onclick=alert(1) #main .skip style=x}</h1>"));
assert!(!html.contains(" onclick="));
}
#[test]
@@ -201,7 +277,7 @@ mod tests {
fn rewrites_relative_links_and_images() {
let html =
markdown("[a](guide.md#top) [b](/src/lib.rs) ![c](../img/logo.png) [d](https://x.dev)", b"docs", &link);
assert!(html.contains("href=\"/blob?path=docs/guide.md\""), "{html}");
assert!(html.contains("href=\"/blob?path=docs/guide.md#md-top\""), "{html}");
assert!(html.contains("href=\"/blob?path=src/lib.rs\""), "{html}");
assert!(html.contains("src=\"/raw?path=img/logo.png\""), "{html}");
assert!(html.contains("href=\"https://x.dev\""), "{html}");
@@ -0,0 +1,10 @@
{% extends "base.html" %}
{% block content %}
{{ masthead|safe }}
<section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{{ title }}</h2><a class="button" href="{{ browse }}">Browse files</a></div>
{% if !message.is_empty() %}<p class="cbody">{{ message }}</p>{% endif %}</div>
<dl class="facts"><div><dt>Author</dt><dd>{{ author }} <span class="quiet">{{ email }}</span></dd></div><div><dt>Date</dt><dd>{{ date }}</dd></div>
<div><dt>Commit</dt><dd><span class="sha">{{ short_id }}</span></dd></div>
{% if !parent_links.is_empty() %}<div><dt>Parent</dt><dd>{{ parent_links|safe }}</dd></div>{% endif %}</dl></section>
{{ diff|safe }}
{% endblock %}
@@ -0,0 +1,19 @@
{% extends "base.html" %}
{% block content %}
{{ masthead|safe }}{{ locator|safe }}
<div class="panel">
{% if let Some(h) = head %}
<div class="panel-head"><div class="lead"><b class="who">{{ h.author }}</b><a class="subject" href="{{ h.url }}">{{ h.subject }}</a></div><div class="side">{{ h.sha_link|safe }}<span>{{ h.when }}</span></div></div>
{% endif %}
<ul class="rows tree-list">
{% if let Some(url) = up %}<li><a class="entry" href="{{ url }}">{{ super::icon("up")|safe }}<span class="name">..</span></a></li>{% endif %}
{% for row in rows %}{{ row|safe }}{% endfor %}
</ul></div>
{% if previous.is_some() || next.is_some() %}
<nav class="pager" aria-label="Directory pages">
{% if let Some(url) = previous %}<a class="button" href="{{ url }}">Previous</a>{% endif %}
{% if let Some(url) = next %}<a class="button" href="{{ url }}">Next</a>{% endif %}
</nav>
{% endif %}
{% if let Some((name, content)) = readme %}<section class="panel"><div class="panel-head"><div class="lead">{{ super::icon("book")|safe }}<b>{{ name }}</b></div></div>{{ content|safe }}</section>{% endif %}
{% endblock %}
@@ -263,7 +263,10 @@ fn diff_links_survive_odd_names() {
fn a_markdown_readme_wins_over_a_plain_one() {
let s = server();
let html = s.get("/ada/site/tree?ref=odd&path=pref").text();
assert!(html.contains("<b>README.md</b>") && html.contains("<h1>Markdown readme</h1>"), "{html}");
assert!(
html.contains("<b>README.md</b>") && html.contains("<h1 id=\"md-markdown-readme\">Markdown readme</h1>"),
"{html}"
);
}
#[test]
@@ -337,7 +340,7 @@ fn tree_lists_folders_first_and_renders_the_readme() {
assert!(html.contains("git@git.um9i.dev:ada/site.git"), "clone address");
// README rendering: Markdown, safe links and escaped HTML.
assert!(html.contains("<article class=\"markdown\"><h1>Fixture {onclick=alert(1) #main .skip}</h1>"), "{html}");
assert!(html.contains("<article class=\"markdown\"><h1 id=\"md-fixture-onclickalert1-main-skip\">Fixture {onclick=alert(1) #main .skip}</h1>"), "{html}");
assert!(html.contains("href=\"/ada/site/blob?ref=main&amp;path=docs/guide.md\""));
assert!(html.contains("href=\"/ada/site/blob?ref=main&amp;path=src\""));
assert!(html.contains("href=\"https://example.com\""));
@@ -368,6 +371,24 @@ fn tree_rows_link_each_entry_to_its_own_change() {
}
}
#[test]
fn directory_history_matches_git_on_each_side_of_the_batch_boundary() {
let server = server();
let bare = fixture().repos.join("ada/site.git");
for (reference, path) in [("main", "big.txt"), ("main", "vendor"), ("main", "side.txt"), ("long", "README.md")] {
let expected = git(&bare, &["log", "-1", "--format=%H", reference, "--", path]);
assert!(!expected.is_empty());
let page = server.get(&format!("/ada/site/tree?ref={reference}")).text();
let row = page
.split("<li class=\"tree-row\">")
.skip(1)
.filter_map(|row| row.split_once("</li>").map(|(row, _)| row))
.find(|row| row.contains(&format!(">{path}<")))
.unwrap();
assert!(row.contains(&format!("/ada/site/commit?id={expected}")), "{reference}:{path}: {row}");
}
}
#[test]
fn tree_shows_submodules_without_links() {
let s = server();
@@ -419,7 +440,7 @@ fn file_view_highlights_with_line_numbers() {
fn markdown_files_have_preview_and_code_views() {
let s = server();
let preview = s.get("/ada/site/blob?path=docs/guide.md").text();
assert!(preview.contains("<article class=\"markdown\"><h1>Guide</h1>"), "{preview}");
assert!(preview.contains("<article class=\"markdown\"><h1 id=\"md-guide\">Guide</h1>"), "{preview}");
assert!(preview.contains("<table>"));
assert!(preview.contains("href=\"/ada/site/blob?ref=main&amp;path=src/main.rs\""), "relative link resolved");
assert!(preview.contains("aria-current=\"true\">Preview"));
@@ -821,3 +842,53 @@ fn public_web_clone_and_visibility_changes() {
}
assert_eq!(server.get("/ada/sharing/raw?path=hello").text(), "public content");
}
#[test]
fn byte_named_refs_and_paged_trees_keep_the_selected_revision() {
let host = Host::new("byte-ref-pages");
let work = common::scratch("byte-ref-pages-work");
git(&work, &["init", "-qb", "main"]);
for n in 0..52 {
fs::write(work.join(format!("file-{n:02}")), b"original").unwrap();
}
git(&work, &["add", "."]);
git(&work, &["commit", "-qm", "First"]);
fs::write(work.join("file-51"), b"second").unwrap();
git(&work, &["commit", "-qam", "Second"]);
assert!(host.git(&work, &["push", "ada@test:ada/bytes.git", "main"]).status.success());
let bare = host.repo("ada", "bytes");
for name in [b"refs/heads/odd-\xff".as_slice(), b"refs/tags/odd-\xfe"] {
assert!(
common::git_cmd(&bare)
.arg("update-ref")
.arg(OsStr::from_bytes(name))
.arg("HEAD^")
.status()
.unwrap()
.success()
);
}
assert!(
common::git_cmd(&bare)
.args(["symbolic-ref", "HEAD"])
.arg(OsStr::from_bytes(b"refs/heads/odd-\xff"))
.status()
.unwrap()
.success()
);
let server = Server::start(&host.repos);
let tree = server.get("/ada/bytes/tree").text();
assert!(
html_escape::decode_html_entities(&tree).contains("ref=odd-%FF&page=1"),
"{}",
tree.lines().filter(|l| l.contains("Next")).collect::<String>()
);
assert!(!tree.contains("file-51"));
assert!(server.get("/ada/bytes/tree?ref=odd-%FF&page=1").text().contains("file-51"));
assert_eq!(server.get("/ada/bytes/raw?ref=odd-%FF&path=file-51").text(), "original");
assert_eq!(server.get("/ada/bytes/raw?ref=odd-%FE&path=file-51").text(), "original");
assert_eq!(server.get("/ada/bytes/raw?ref=main&path=file-51").text(), "second");
assert!(server.get("/ada/bytes/tags").text().contains("ref=odd-%FE"));
assert!(server.get("/ada/bytes/log").text().contains("ref=odd-%FE"));
assert_eq!(server.get("/ada/bytes/tree?page=2").status, 404);
}