//! Private Git hosting over OpenSSH and Git's native pack protocol. use std::collections::BTreeMap; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode, Stdio}; use base64::Engine; use clap::{Parser, Subcommand}; use gitv_core::{ DESCRIPTION_LIMIT, NAME_RULE, RepoDir, chown_tree, config, entries, git, git_command, git_in, keys_path, kind_at, open_dir_at, open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, unix_now, valid_name, }; use nix::errno::Errno; use nix::fcntl::{Flock, FlockArg, OFlag, RenameFlags, openat, renameat2}; use nix::sys::stat::{Mode, fchmod, fstat, mkdirat}; use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, geteuid, unlinkat}; use std::ffi::OsStr; use std::os::fd::{AsFd, OwnedFd}; use std::os::unix::ffi::OsStrExt; use std::time::{SystemTime, UNIX_EPOCH}; /// What `help` prints. fn help() -> String { let host = config::host(); format!( "Commands for your key, run as: ssh git@{host} list list your repositories create create an empty repository visibility public|private set web access protect [on|off] show or set whether pushes may rewrite or delete branches description [] show or set the one-line description (\"\" removes it) default-branch [] show or set the branch the web shows and clones check out delete --yes move a repository to the trash (the operator can restore it for 30 days) Pushing to a repository that does not exist yet creates it." ) } #[derive(Parser)] #[command(about = "Private Git hosting over OpenSSH and Git's native pack protocol")] struct Cli { #[command(subcommand)] action: Action, } #[derive(Subcommand)] enum Action { /// Create an empty repository (root) Create { #[arg(value_parser = name)] owner: String, #[arg(value_parser = name)] name: String, }, /// Set repository web visibility to public or private (root) Visibility { owner: String, name: String, visibility: String }, /// Show or set whether pushes may force-update or delete branches (root) Protect { #[arg(value_parser = name)] owner: String, #[arg(value_parser = name)] name: String, /// on: branches only move forwards and are never deleted; off: anything value: Option, }, /// Show or set a repository's one-line description; "" removes it (root) Description { #[arg(value_parser = name)] owner: String, #[arg(value_parser = name)] name: String, text: Option, }, /// Show or set the branch a repository's web pages show and clones check out (root) DefaultBranch { #[arg(value_parser = name)] owner: String, #[arg(value_parser = name)] name: String, branch: Option, }, /// Move a repository to its owner's trash (root) Delete { #[arg(value_parser = name)] owner: String, #[arg(value_parser = name)] name: String, /// Confirm deletion #[arg(long)] yes: bool, }, /// List deleted repositories waiting in the trash (root) Trash, /// Put a deleted repository back, under its old name or another (root) Restore { #[arg(value_parser = name)] owner: String, /// The trash entry, as `gitv trash` lists it: . entry: String, /// Restore under this name instead #[arg(long = "as", value_parser = name)] as_name: Option, }, /// Copy a bare repository, such as one gitv-restore brought back, into place (root) Import { #[arg(value_parser = name)] owner: String, /// The name to give it; anything already there is never replaced #[arg(value_parser = name)] name: String, /// The restored repository's directory source: PathBuf, }, /// Permanently remove trash entries deleted at least this many days ago (root) Purge { #[arg(long, default_value_t = TRASH_DAYS)] older_than_days: u64, }, /// Register an Ed25519 public key for an owner (root) AddKey { #[arg(value_parser = name)] owner: String, public_key: PathBuf, /// A name for the device that holds the key, shown by `gitv keys` #[arg(long, value_parser = label)] label: Option, }, /// List registered keys with their owner, fingerprint and label (root) Keys { /// Only this owner's keys #[arg(value_parser = name)] owner: Option, }, /// Revoke a key by its fingerprint, as `gitv keys` lists it (root) RemoveKey { /// SHA256:, with or without the SHA256: prefix fingerprint: String, }, /// Handle one SSH request (forced command from authorized_keys) Serve { #[arg(value_parser = name)] owner: String, }, } /// [`check_name`], for clap's argument parsing. fn name(value: &str) -> Result { check_name(value).map(str::to_string) } /// A key's label becomes the comment field of its authorized_keys line, so it must stay on one /// line and hold nothing a terminal would act on. fn label(value: &str) -> Result { let value = value.trim(); if value.is_empty() || value.chars().count() > 64 || value.chars().any(char::is_control) { return Err("a label is 1 to 64 characters, with no control characters".into()); } Ok(value.to_string()) } fn check_name(value: &str) -> Result<&str, String> { if valid_name(value) { Ok(value) } else { Err(NAME_RULE.into()) } } /// Record something for the operator. SSH users only ever see generic errors, so details go to /// syslog (facility daemon, tag `gitv`), or, when `GITV_LOG` names a file, are appended there /// for local runs and tests. fn log_operator(message: &str) { let mut message = message.to_string(); if let Some(path) = std::env::var_os("GITV_LOG") { // Only a record that was actually written counts; otherwise fall back to syslog, so // the message is never lost, and say why it ended up there. match append_line(Path::new(&path), &format!("gitv: {message}")) { Ok(()) => return, Err(e) => message = format!("{message} (couldn't write {}: {e})", Path::new(&path).display()), } } let message = std::ffi::CString::new(message.replace('\0', " ")).unwrap_or_default(); // SAFETY: both strings are NUL-terminated and outlive the calls; "%s" keeps the message // from being read as a format string. unsafe { nix::libc::openlog(c"gitv".as_ptr(), nix::libc::LOG_PID, nix::libc::LOG_DAEMON); nix::libc::syslog(nix::libc::LOG_WARNING, c"%s".as_ptr(), message.as_ptr()); } } /// Append one line to a file, creating it if needed, and make sure it reached the file. fn append_line(path: &Path, line: &str) -> std::io::Result<()> { let mut file = fs::File::options().create(true).append(true).open(path)?; file.write_all(format!("{line}\n").as_bytes())?; file.flush() } fn is_root() -> bool { nix::unistd::geteuid().is_root() } /// The `git` account's ids, when running as root and new files must be handed to it. fn git_account() -> Result, String> { if !is_root() { return Ok(None); } let user = nix::unistd::User::from_name("git").map_err(|e| e.to_string())?.ok_or("no git account")?; Ok(Some((user.uid, user.gid))) } /// The owner's directory, created if needed and returned open. Anything else at that name, /// including a symlink to a directory, is refused rather than followed. fn owner_directory(owner: &str) -> Result { let root = open_root().ok_or("cannot open the repository root")?; let display = repos_root().join(owner); // Another push may create it at the same moment; either way, open what's there after. match mkdirat(&root, owner, Mode::from_bits_truncate(0o755)) { Ok(()) | Err(Errno::EEXIST) => {} Err(e) => return Err(format!("cannot create {}: {e}", display.display())), } let directory = open_dir_at(&root, OsStr::new(owner)).map_err(|_| format!("{} is not a directory", display.display()))?; if let Some((uid, gid)) = git_account()? { fchown(&directory, Some(uid), Some(gid)).map_err(|e| e.to_string())?; } Ok(directory) } /// Create `/.git`. /// /// The repository is built inside a private staging directory (mode 0700, made fresh under the /// open owner directory), so no other user can rename, replace or remove anything inside it. /// Initialisation, permissions and ownership all go through handles, and publication renames /// out of the staging directory's own handle into the owner directory's, refusing to replace /// anything at the name. What gets published is therefore exactly what git initialised. fn create(owner: &str, name: &str) -> Result { publish_new(owner, name, Contents::Empty) } /// What a new repository starts as. #[derive(Clone, Copy)] enum Contents<'a> { /// `git init --bare`. Empty, /// A copy of the bare repository at this path, outside the live tree: one restored from a /// backup, say. CopyOf(&'a Path), } /// Make `/.git` from `contents`, as described for [`create`]. fn publish_new(owner: &str, name: &str, contents: Contents) -> Result { let directory = owner_directory(owner).map_err(CreateError::Failed)?; let target = format!("{name}.git"); if kind_at(&directory, OsStr::new(&target)).is_some() { return Err(CreateError::EXISTS); } let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); let staging_name = format!(".create-{}-{nanos}-{name}", std::process::id()); mkdirat(&directory, staging_name.as_str(), Mode::S_IRWXU) .map_err(|e| CreateError::Failed(format!("couldn't make a staging directory: {e}")))?; let built = open_dir_at(&directory, OsStr::new(&staging_name)) .map_err(|e| CreateError::Failed(format!("couldn't open the staging directory: {e}"))) .and_then(|staging| { // The directory just made must be ours and private; anything else at the name means // someone got there first, so give up rather than build in it. let stat = fstat(staging.as_fd()).map_err(|e| CreateError::Failed(e.to_string()))?; if stat.st_uid != geteuid().as_raw() || stat.st_mode & 0o077 != 0 { return Err(CreateError::Failed("the staging directory isn't private".into())); } build_and_publish(&directory, &staging, &target, contents) }); // The staging directory is empty now, whether the repository was published or rolled // back. Removing it by name only ever removes an empty directory. let leftover = unlinkat(&directory, staging_name.as_str(), UnlinkatFlags::RemoveDir).err().map(|e| { format!("couldn't remove the staging directory {}: {e}", repos_root().join(owner).join(&staging_name).display()) }); if let Some(leftover) = &leftover { // Whatever the outcome and whoever asked, the operator needs to know. log_operator(&format!("creating {owner}/{name}.git: {leftover}")); } match built { Ok(()) => Ok(Created { leftover }), // A failure that also left something behind carries both, so whoever reads the detail // (an administrator, or the operator log) learns about the directory to clean up. Err(error) => Err(match leftover { None => error, Some(leftover) => error.with_leftover(leftover), }), } } /// A repository was created; `leftover` describes anything the operator must clean up. struct Created { leftover: Option, } /// Why creation didn't happen. `Exists` is safe to tell anyone; `Failed` carries server details /// (paths, git's own messages) that only the operator or an administrator should see. enum CreateError { /// Something is already at the name. `leftover` notes anything the attempt left behind. Exists { leftover: Option, }, Failed(String), } impl CreateError { const EXISTS: CreateError = CreateError::Exists { leftover: None }; /// The full story, for the operator or an administrator. fn detail(&self) -> String { match self { CreateError::Exists { leftover: None } => "repository already exists".into(), CreateError::Exists { leftover: Some(leftover) } => format!("repository already exists; also {leftover}"), CreateError::Failed(detail) => detail.clone(), } } fn with_leftover(self, leftover: String) -> CreateError { match self { CreateError::Exists { .. } => CreateError::Exists { leftover: Some(leftover) }, CreateError::Failed(detail) => CreateError::Failed(format!("{detail}; also {leftover}")), } } } /// Run a command whose output only an operator should see: stdout is dropped, and stderr is /// captured into the error instead of reaching whoever is connected. fn run_privately(mut command: Command, what: &str) -> Result<(), String> { let output = command.stdout(Stdio::null()).output().map_err(|e| format!("{what} couldn't start: {e}"))?; if output.status.success() { Ok(()) } else { let message = String::from_utf8_lossy(&output.stderr).trim().to_string(); Err(format!( "{what} failed ({}){}", output.status, if message.is_empty() { String::new() } else { format!(": {message}") } )) } } /// Build a bare repository at `repo` inside the private `staging` directory, then move it to /// `target` in `directory`. If anything fails after `repo` was made, it is removed again; it /// never removes a `repo` this call didn't make. fn build_and_publish( directory: &OwnedFd, staging: &OwnedFd, target: &str, contents: Contents, ) -> Result<(), CreateError> { let failed = |e: &dyn std::fmt::Display| CreateError::Failed(e.to_string()); // Only once this succeeds is `repo` ours to roll back. mkdirat(staging, "repo", Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; let built = (|| { let repo = open_dir_at(staging, OsStr::new("repo")).map_err(|e| failed(&e))?; match contents { Contents::Empty => { // A clean environment, so no caller's init.templateDir can plant hooks in it; // and its output stays private, whoever is connected. let mut init = git_in(&repo); init.args(["init", "--quiet", "--bare", "--initial-branch=main", "."]); run_privately(init, "git init").map_err(CreateError::Failed)?; } Contents::CopyOf(source) => { // Everything, the visibility marker, description and HEAD included, with modes and // times; links are copied as links, never followed. Not owners (set below) and // not SELinux labels: new files take the repository tree's own, not those of // the folder a restore was staged in. let mut copy = gitv_core::command_in(&repo, "cp"); copy.args(["-R", "-P", "--preserve=mode,timestamps,links", "--"]).arg(source.join(".")).arg("."); run_privately(copy, "copying the repository").map_err(CreateError::Failed)?; // Nothing is published that git can't read whole. let mut fsck = git_in(&repo); fsck.args(["--git-dir=.", "fsck", "--no-progress", "--full"]); run_privately(fsck, "git fsck").map_err(CreateError::Failed)?; } } fchmod(&repo, Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; if let Some((uid, gid)) = git_account().map_err(CreateError::Failed)? { chown_tree(&repo, uid, gid).map_err(|e| failed(&e))?; } renameat2(staging, "repo", directory, target, RenameFlags::RENAME_NOREPLACE) .map_err(|e| if e == Errno::EEXIST { CreateError::EXISTS } else { failed(&e) }) })(); if let Err(error) = built { return Err(match remove_tree_at(staging, OsStr::new("repo")) { Ok(()) => error, Err(e) => { let problem = format!("couldn't remove a half-built repository after \"{}\": {e}", error.detail()); log_operator(&problem); CreateError::Failed(problem) } }); } Ok(()) } /// Copy the bare repository at `source` into the live tree as `/.git`, never /// replacing anything already there: how a repository restored from a backup goes back. fn import(owner: &str, name: &str, source: &Path) -> Result<(), String> { // Only a real bare repository is copied: a directory, not a link to one, with a HEAD file. let from = gitv_core::open_dir(source).map_err(|e| format!("can't open {}: {e}", source.display()))?; if kind_at(&from, OsStr::new("HEAD")) != Some(nix::sys::stat::SFlag::S_IFREG) { return Err(format!("{} isn't a bare repository", source.display())); } match publish_new(owner, name, Contents::CopyOf(source)) { Ok(created) => { println!("imported git@{}:{owner}/{name}.git", config::host()); if let Some(leftover) = created.leftover { eprintln!("gitv: imported {owner}/{name}.git, but {leftover}"); } Ok(()) } Err(CreateError::Exists { .. }) => { Err(format!("{owner}/{name}.git already exists; import under another name, or delete it first")) } Err(error) => Err(error.detail()), } } /// Deleted repositories wait in `/.trash` for this many days before `gitv purge` removes them. const TRASH_DAYS: u64 = 30; /// The trash directory inside each owner's directory. Its leading dot keeps it out of every listing. const TRASH: &str = ".trash"; /// The owner's trash directory, created (private, and the git account's) if needed. fn trash_directory(owner_dir: &OwnedFd) -> Result { match mkdirat(owner_dir, TRASH, Mode::S_IRWXU) { Ok(()) | Err(Errno::EEXIST) => {} Err(e) => return Err(format!("cannot create the trash: {e}")), } let trash = open_dir_at(owner_dir, OsStr::new(TRASH)).map_err(|_| "the trash is not a directory".to_string())?; if let Some((uid, gid)) = git_account()? { fchown(&trash, Some(uid), Some(gid)).map_err(|e| e.to_string())?; } Ok(trash) } /// A trash entry's repository name and deletion time: `.`. fn parse_trash_entry(entry: &str) -> Option<(&str, u64)> { let (name, stamp) = entry.rsplit_once('.')?; (valid_name(name) && !stamp.is_empty() && stamp.bytes().all(|b| b.is_ascii_digit())) .then_some((name, stamp.parse().ok()?)) } /// Move `/.git` into the owner's trash, returning the trash entry's name. One handle /// on the owner directory serves the check and the move; if the entry were swapped for a symlink /// after the check, only the link would be moved. Nothing is removed until `gitv purge`. fn delete(owner: &str, name: &str) -> Result { let directory = open_owner(owner).ok_or("repository unavailable")?; repo_in(&directory, owner, name).ok_or("repository unavailable")?; let trash = trash_directory(&directory)?; let entry = format!("{name}.{}", unix_now()); renameat2(&directory, format!("{name}.git").as_str(), &trash, entry.as_str(), RenameFlags::RENAME_NOREPLACE) .map_err(|e| match e { Errno::EEXIST => "the repository was deleted moments ago under the same name; try again".to_string(), e => e.to_string(), })?; Ok(entry) } /// Every trash entry: owner, entry name, and deletion time when the name carries one. fn trash_entries() -> Result)>, String> { let root = open_root().ok_or("cannot open the repository root")?; let mut found = Vec::new(); for owner in entries(&root).into_iter().filter_map(|o| o.into_string().ok()).filter(|o| valid_name(o)) { let Some(owner_dir) = open_owner(&owner) else { continue }; let trash = match open_dir_at(&owner_dir, OsStr::new(TRASH)) { Ok(trash) => trash, Err(Errno::ENOENT) => continue, Err(e) => return Err(format!("cannot open {owner}/{TRASH}: {e}")), }; let names = gitv_core::try_entries(&trash).map_err(|e| format!("cannot list {owner}/{TRASH}: {e}"))?; for entry in names { let entry = entry.to_string_lossy().into_owned(); let stamp = parse_trash_entry(&entry).map(|(_, stamp)| stamp); found.push((owner.clone(), entry, stamp)); } } found.sort(); Ok(found) } fn list_trash() -> Result<(), String> { let now = unix_now(); for (owner, entry, stamp) in trash_entries()? { match stamp { Some(stamp) => { let days = now.saturating_sub(stamp) / 86_400; let left = TRASH_DAYS.saturating_sub(days); println!("{owner} {entry} deleted {days} days ago, purged in {left} days"); } None => println!("{owner} {entry} (not a trash entry; purge leaves it alone)"), } } Ok(()) } /// Move a trash entry back to `/.git`, never replacing anything at that name. fn restore(owner: &str, entry: &str, as_name: Option<&str>) -> Result<(), String> { let (original, _) = parse_trash_entry(entry).ok_or("not a trash entry; see `gitv trash`")?; let name = as_name.unwrap_or(original); let directory = open_owner(owner).ok_or("no such owner")?; let trash = open_dir_at(&directory, OsStr::new(TRASH)).map_err(|_| "this owner has no trash")?; renameat2(&trash, entry, &directory, format!("{name}.git").as_str(), RenameFlags::RENAME_NOREPLACE).map_err( |e| match e { Errno::EEXIST => format!("{owner}/{name}.git already exists; restore with --as "), Errno::ENOENT => "no such trash entry; see `gitv trash`".to_string(), e => e.to_string(), }, )?; println!("restored git@{}:{owner}/{name}.git", config::host()); Ok(()) } /// Remove trash entries deleted at least `days` days ago, through handles and without following /// symlinks. Entries that don't look like `.