| @@ -4,7 +4,7 @@ use std::fs; |
| | use std::io::Write; |
| | use std::os::unix::fs::PermissionsExt; |
| | use std::path::{Path, PathBuf}; |
| | use std::process::{ExitCode, Stdio}; |
| | use std::process::{Command, ExitCode, Stdio}; |
| | |
| | use base64::Engine; |
| | use clap::{Parser, Subcommand}; |
| @@ -74,6 +74,35 @@ 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() |
| | } |
| @@ -112,76 +141,127 @@ fn owner_directory(owner: &str) -> Result<OwnedFd, String> { |
| | /// 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, quiet: bool) -> Result<(), String> { |
| | let directory = owner_directory(owner)?; |
| | fn create(owner: &str, name: &str) -> Result<Created, CreateError> { |
| | 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("repository already exists".into()); |
| | 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| e.to_string())?; |
| | let built = open_dir_at(&directory, OsStr::new(&staging_name)).map_err(|e| e.to_string()).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| e.to_string())?; |
| | if stat.st_uid != geteuid().as_raw() || stat.st_mode & 0o077 != 0 { |
| | return Err("staging directory isn't private".to_string()); |
| | } |
| | build_and_publish(&directory, &staging, &target) |
| | }); |
| | 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) |
| | }); |
| | // 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(()) => { |
| | // Created: say so, and mention any leftover separately; retrying would only find |
| | // the repository already there. |
| | if let Some(leftover) = leftover { |
| | eprintln!("gitv: created {owner}/{name}.git, but {leftover}"); |
| | } |
| | if !quiet { |
| | println!("git@{HOST}:{owner}/{name}.git"); |
| | } |
| | Ok(()) |
| | } |
| | 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 { |
| | Some(leftover) => format!("{error}; also {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<String>, |
| | } |
| | |
| | /// 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<String>, |
| | }, |
| | 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) -> Result<(), String> { |
| | fn build_and_publish(directory: &OwnedFd, staging: &OwnedFd, target: &str) -> 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| e.to_string())?; |
| | 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| e.to_string())?; |
| | // A clean environment, so no caller's init.templateDir can plant hooks in it. |
| | let status = git_in(&repo) |
| | .args(["init", "--quiet", "--bare", "--initial-branch=main", "."]) |
| | .stdout(Stdio::null()) |
| | .status() |
| | .map_err(|e| e.to_string())?; |
| | if !status.success() { |
| | return Err("git init failed".to_string()); |
| | } |
| | fchmod(&repo, Mode::from_bits_truncate(0o750)).map_err(|e| e.to_string())?; |
| | if let Some((uid, gid)) = git_account()? { |
| | chown_tree(&repo, uid, gid).map_err(|e| e.to_string())?; |
| | let repo = open_dir_at(staging, OsStr::new("repo")).map_err(|e| failed(&e))?; |
| | // 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)?; |
| | 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 { "repository already exists".to_string() } else { e.to_string() }) |
| | .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) => format!("{error}; also couldn't remove the half-built repository: {e}"), |
| | Err(e) => { |
| | let problem = format!("couldn't remove a half-built repository after \"{}\": {e}", error.detail()); |
| | log_operator(&problem); |
| | CreateError::Failed(problem) |
| | } |
| | }); |
| | } |
| | Ok(()) |
| @@ -303,7 +383,19 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> { |
| | println!("git@{HOST}:{owner}/{name}.git"); |
| | } |
| | } |
| | ["create", name] => create(owner, check_name(name)?, false)?, |
| | ["create", name] => { |
| | // A key holder learns whether it worked, and the clone address; server details go |
| | // to the operator's log. |
| | let name = check_name(name)?; |
| | match create(owner, name) { |
| | Ok(_) => println!("git@{HOST}:{owner}/{name}.git"), |
| | Err(CreateError::Exists { .. }) => return Err("repository already exists".into()), |
| | Err(error) => { |
| | log_operator(&format!("ssh create of {owner}/{name}.git failed: {}", error.detail())); |
| | return Err("couldn't create the repository; the server's operator can see why".into()); |
| | } |
| | } |
| | } |
| | ["delete", name, rest @ ..] => { |
| | let name = check_name(name)?; |
| | if rest != ["--yes"] { |
| @@ -338,10 +430,22 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> { |
| | // never replaces anything at the name, so a symlink or file there is refused. If a |
| | // racing push created the repository first, at any moment, this one opens it afresh; |
| | // either way what it gets must be a real repository. |
| | match create(owner, name, true) { |
| | Ok(()) => eprintln!("gitv: created {owner}/{name}.git"), |
| | Err(_) if repo_dir(owner, name).is_some() => {} |
| | Err(_) => return Err("repository unavailable".into()), |
| | // The client only ever hears "repository unavailable"; the cause goes to the |
| | // operator's log. Losing a race to a push that created it is ordinary, so that stays |
| | // quiet (create() has already logged any cleanup problem either way). |
| | match create(owner, name) { |
| | Ok(_) => eprintln!("gitv: created {owner}/{name}.git"), |
| | // Another push created it first: ordinary, so quiet. |
| | Err(CreateError::Exists { .. }) if repo_dir(owner, name).is_some() => {} |
| | // This attempt genuinely failed, though a racing push's repository lets the |
| | // push carry on: the operator still hears why. |
| | Err(error) if repo_dir(owner, name).is_some() => { |
| | log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail())); |
| | } |
| | Err(error) => { |
| | log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail())); |
| | return Err("repository unavailable".into()); |
| | } |
| | } |
| | repo_dir(owner, name).ok_or("repository unavailable")? |
| | } |
| @@ -398,7 +502,14 @@ fn run() -> Result<u8, String> { |
| | return Err("run repository and key administration as root".into()); |
| | } |
| | match cli.action { |
| | Action::Create { owner, name } => create(&owner, &name, false)?, |
| | Action::Create { owner, name } => { |
| | // An administrator sees everything. |
| | let created = create(&owner, &name).map_err(|e| e.detail())?; |
| | println!("git@{HOST}:{owner}/{name}.git"); |
| | if let Some(leftover) = created.leftover { |
| | eprintln!("gitv: created {owner}/{name}.git, but {leftover}"); |
| | } |
| | } |
| | Action::Delete { owner, name, yes } => { |
| | if !yes { |
| | return Err(format!("deleting {owner}/{name}.git is permanent; pass --yes to confirm")); |
| @@ -430,6 +541,43 @@ mod tests { |
| | open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).unwrap() |
| | } |
| | |
| | #[test] |
| | fn creation_errors_keep_their_leftovers() { |
| | let leftover = || "couldn't remove the staging directory /x".to_string(); |
| | assert_eq!(CreateError::EXISTS.detail(), "repository already exists"); |
| | assert_eq!( |
| | CreateError::EXISTS.with_leftover(leftover()).detail(), |
| | "repository already exists; also couldn't remove the staging directory /x" |
| | ); |
| | assert_eq!( |
| | CreateError::Failed("git init failed".into()).with_leftover(leftover()).detail(), |
| | "git init failed; also couldn't remove the staging directory /x" |
| | ); |
| | // Still "exists" for the callers that treat it specially. |
| | assert!(matches!(CreateError::EXISTS.with_leftover(leftover()), CreateError::Exists { .. })); |
| | } |
| | |
| | #[test] |
| | fn private_commands_keep_their_errors_for_the_operator() { |
| | let mut command = gitv::git_base(); |
| | command.args(["init", "--no-such-option"]); |
| | let error = run_privately(command, "git init").unwrap_err(); |
| | assert!(error.starts_with("git init failed (exit status: 129): "), "{error}"); |
| | assert!(error.contains("no-such-option"), "git's own message is captured: {error}"); |
| | } |
| | |
| | #[test] |
| | fn a_log_file_that_cannot_be_written_is_reported() { |
| | let missing = std::env::temp_dir().join(format!("gitv-no-such-dir-{}/log", std::process::id())); |
| | assert!(append_line(&missing, "x").is_err(), "a failed write must not count as logged"); |
| | let file = std::env::temp_dir().join(format!("gitv-log-{}", std::process::id())); |
| | let _ = fs::remove_file(&file); |
| | append_line(&file, "one").unwrap(); |
| | append_line(&file, "two").unwrap(); |
| | assert_eq!(fs::read_to_string(&file).unwrap(), "one\ntwo\n"); |
| | let _ = fs::remove_file(&file); |
| | } |
| | |
| | #[test] |
| | fn a_failed_build_never_removes_what_it_did_not_make() { |
| | let dir = std::env::temp_dir().join(format!("gitv-build-{}", std::process::id())); |
| @@ -456,7 +604,7 @@ mod tests { |
| | fs::create_dir_all(dir.join("owner/new.git")).unwrap(); |
| | let owner = open_path(&dir.join("owner")); |
| | let staging = open_path(&dir.join("owner/.staging")); |
| | let error = build_and_publish(&owner, &staging, "new.git").unwrap_err(); |
| | let error = build_and_publish(&owner, &staging, "new.git").err().map(|e| e.detail()).unwrap_or_default(); |
| | assert!(error.contains("already exists"), "{error}"); |
| | assert!(fs::read_dir(dir.join("owner/.staging")).unwrap().next().is_none(), "the half-built repo is gone"); |
| | assert!(fs::read_dir(dir.join("owner/new.git")).unwrap().next().is_none(), "the target is untouched"); |