use crate::policy::AccessPolicy;
use crate::profile::{private_new_file, runtime_dir, validate_relative_path, Profile};
use std::ffi::OsString;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use zeroize::Zeroizing;
const MODULE: &str = "guth-sync";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Direction {
Push,
Pull,
}
#[derive(Clone, Debug)]
pub struct TransferOptions {
pub dry_run: bool,
pub port: u16,
pub identity: Option<PathBuf>,
pub known_hosts: Option<PathBuf>,
pub remote_program: String,
}
impl Default for TransferOptions {
fn default() -> Self {
Self {
dry_run: false,
port: 22,
identity: None,
known_hosts: None,
remote_program: "guth-sync".to_string(),
}
}
}
impl Direction {
fn host_access(self) -> &'static str {
match self {
Self::Push => "write",
Self::Pull => "read",
}
}
}
pub fn transfer(
profile: &Profile,
direction: Direction,
endpoint: &str,
paths: &[PathBuf],
all: bool,
options: &TransferOptions,
) -> io::Result<ExitStatus> {
if direction == Direction::Pull && !options.dry_run {
let policy = AccessPolicy::load()?;
require_writable(policy.read_only_checked(profile.id(), profile.policy_required())?)?;
}
let (ssh_user, _) = parse_endpoint(endpoint)?;
if options.port == 0 {
return Err(invalid_input("SSH port must be between 1 and 65535"));
}
validate_remote_program(&options.remote_program)?;
if all != paths.is_empty() {
return Err(invalid_input(
"choose either --all or one or more relative paths",
));
}
for path in paths {
validate_relative_path(path)?;
if direction == Direction::Push {
validate_push_source(profile.root(), path)?;
}
}
ensure_rsync_version()?;
ensure_tool("ssh", "-V")?;
let mut remote_shell = format!(
"ssh -F /dev/null -T -l {ssh_user} -p {} -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=yes -o CheckHostIP=no -o UpdateHostKeys=no -o ClearAllForwardings=yes -o ForwardAgent=no -o ForwardX11=no -o PermitLocalCommand=no -o ControlMaster=no -o AddKeysToAgent=no",
options.port,
);
let staged_identity = options
.identity
.as_deref()
.map(|path| stage_option_file(path, "identity", true))
.transpose()?;
let staged_known_hosts = options
.known_hosts
.as_deref()
.map(|path| stage_option_file(path, "known-hosts", false))
.transpose()?;
if let Some(identity) = &staged_identity {
remote_shell.push_str(" -o IdentitiesOnly=yes");
remote_shell.push_str(" -i ");
remote_shell.push_str(&identity.path.to_string_lossy());
}
if let Some(known_hosts) = &staged_known_hosts {
remote_shell.push_str(" -o UserKnownHostsFile=");
remote_shell.push_str(&known_hosts.path.to_string_lossy());
remote_shell.push_str(" -o GlobalKnownHostsFile=/dev/null");
}
let password = RuntimeSecretFile::new("password", profile.key_text().as_bytes())?;
let mut command = Command::new("rsync");
command
.current_dir(profile.root())
.args([
"--recursive",
"--links",
"--perms",
"--times",
"--checksum",
"--relative",
"--safe-links",
"--one-file-system",
"--protect-args",
"--no-owner",
"--no-group",
"--no-devices",
"--no-specials",
"--timeout=120",
"--human-readable",
"--info=progress2,stats1,name0,flist0",
])
.arg(format!("--password-file={}", password.path.display()))
.arg(format!(
"--rsync-path={} host {} {}",
options.remote_program,
profile.id(),
direction.host_access()
))
.arg(format!("--rsh={remote_shell}"))
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
if options.dry_run {
command.arg("--dry-run");
}
command.arg("--");
let remote = format!("{endpoint}::{MODULE}/");
match direction {
Direction::Push => {
if all {
command.arg("./");
} else {
command.args(paths.iter().map(|path| relative_source(path)));
}
command.arg(remote);
}
Direction::Pull => {
if all {
command.arg(remote).arg("./");
} else {
for path in paths {
command.arg(remote_path(endpoint, path)?);
}
command.arg("./");
}
}
}
command.status()
}
pub fn host(profile: &Profile, access: &str) -> io::Result<ExitStatus> {
if std::env::var_os("SSH_CONNECTION").is_none() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"host mode is available only through SSH",
));
}
let read_only = match access {
"read" => true,
"write" => {
let policy = AccessPolicy::load()?;
require_writable(policy.read_only_checked(profile.id(), profile.policy_required())?)?;
false
}
_ => return Err(invalid_input("host access must be read or write")),
};
ensure_rsync_version()?;
let username = remote_username()?;
let key = profile.key_text();
let secret_line = Zeroizing::new(format!("{username}:{}\n", key.as_str()));
let secrets = RuntimeSecretFile::new("secrets", secret_line.as_bytes())?;
let config_text = format!(
"use chroot = false\nlog file = /dev/null\ntransfer logging = false\nlist = false\nmunge symlinks = true\ntimeout = 120\nrefuse options = delete* remove-source-files\n[{}]\npath = {}/\nread only = {}\nwrite only = {}\nauth users = {}\nsecrets file = {}\nstrict modes = true\n",
MODULE,
profile.root().display(),
if read_only { "true" } else { "false" },
if read_only { "false" } else { "true" },
username,
secrets.path.display()
);
let config = RuntimeSecretFile::new("rsyncd", config_text.as_bytes())?;
Command::new("rsync")
.args(["--server", "--daemon"])
.arg(format!("--config={}", config.path.display()))
.arg(".")
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
}
fn read_only_error() -> io::Error {
io::Error::new(
io::ErrorKind::PermissionDenied,
"this Guth Sync profile is read-only on the local instance",
)
}
fn require_writable(read_only: bool) -> io::Result<()> {
if read_only {
Err(read_only_error())
} else {
Ok(())
}
}
fn remote_path(endpoint: &str, path: &Path) -> io::Result<OsString> {
validate_relative_path(path)?;
let mut value = OsString::from(format!("{endpoint}::{MODULE}/./"));
value.push(path.as_os_str());
Ok(value)
}
fn parse_endpoint(endpoint: &str) -> io::Result<(&str, &str)> {
if endpoint.len() < 3
|| endpoint.len() > 255
|| endpoint.starts_with('-')
|| endpoint.contains(['/', '\\', ':'])
|| endpoint.chars().any(|character| {
character.is_control() || character.is_whitespace() || matches!(character, '$' | '`')
})
{
return Err(invalid_input(
"endpoint must be a simple user@hostname without a port",
));
}
let allowed = endpoint
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'@'));
if !allowed || endpoint.matches('@').count() != 1 {
return Err(invalid_input("endpoint contains unsupported characters"));
}
let (user, host) = endpoint
.split_once('@')
.ok_or_else(|| invalid_input("endpoint must include an SSH user"))?;
if user.is_empty()
|| host.is_empty()
|| !user
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
|| !host
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
{
return Err(invalid_input(
"endpoint contains an invalid user or hostname",
));
}
Ok((user, host))
}
fn validate_remote_program(program: &str) -> io::Result<()> {
if program == "guth-sync" {
return Ok(());
}
validate_command_text(program, "remote program")?;
if !Path::new(program).is_absolute() {
return Err(invalid_input(
"remote program must be guth-sync or an absolute path",
));
}
Ok(())
}
fn stage_option_file(path: &Path, label: &str, private: bool) -> io::Result<RuntimeSecretFile> {
let text = path
.to_str()
.ok_or_else(|| invalid_input(format!("{label} path must be valid UTF-8")))?;
validate_command_text(text, label)?;
if !path.is_absolute() {
return Err(invalid_input(format!("{label} path must be absolute")));
}
let owned_fd = rustix::fs::open(
path,
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC | rustix::fs::OFlags::NOFOLLOW,
rustix::fs::Mode::empty(),
)
.map_err(errno_error)?;
let file = fs::File::from(owned_fd);
let metadata = file.metadata()?;
if !metadata.is_file() || metadata.len() > 1024 * 1024 {
return Err(invalid_input(format!("{label} must be a regular file")));
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if metadata.uid() != rustix::process::geteuid().as_raw() || metadata.nlink() != 1 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{label} has unsafe ownership or links"),
));
}
if private && metadata.mode() & 0o077 != 0 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{label} permissions must be private"),
));
}
}
let mut bytes = Zeroizing::new(Vec::with_capacity(metadata.len() as usize));
use std::io::Read as _;
file.take(1024 * 1024 + 1).read_to_end(&mut bytes)?;
RuntimeSecretFile::new(label, &bytes)
}
fn validate_command_text(value: &str, label: &str) -> io::Result<()> {
if value.is_empty()
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'-' | b'_'))
{
return Err(invalid_input(format!(
"{label} contains unsupported characters"
)));
}
Ok(())
}
fn remote_username() -> io::Result<String> {
let username = std::env::var("USER")
.map_err(|_| invalid_input("remote USER is required for rsync authentication"))?;
if username.is_empty()
|| username.len() > 64
|| !username
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
{
return Err(invalid_input("remote USER contains unsupported characters"));
}
Ok(username)
}
fn validate_push_source(root: &Path, path: &Path) -> io::Result<()> {
let mut current = root.to_path_buf();
for component in path.components() {
if let std::path::Component::Normal(component) = component {
current.push(component);
let metadata = fs::symlink_metadata(¤t)?;
if metadata.file_type().is_symlink() {
return Err(invalid_input(
"selected source paths cannot traverse symbolic links",
));
}
}
}
let canonical = fs::canonicalize(¤t)?;
if !canonical.starts_with(root) {
return Err(invalid_input("selected source leaves the profile root"));
}
Ok(())
}
fn relative_source(path: &Path) -> OsString {
let mut source = OsString::from("./");
source.push(path);
source
}
fn ensure_rsync_version() -> io::Result<()> {
let output = Command::new("rsync")
.arg("--version")
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.map_err(|error| io::Error::new(error.kind(), format!("rsync is unavailable: {error}")))?;
if !output.status.success() {
return Err(io::Error::other("rsync version check failed"));
}
let version = String::from_utf8_lossy(&output.stdout)
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(2))
.and_then(parse_version)
.ok_or_else(|| io::Error::other("could not determine rsync version"))?;
if version < (3, 2, 5) {
return Err(io::Error::other("rsync 3.2.5 or newer is required"));
}
Ok(())
}
fn parse_version(value: &str) -> Option<(u32, u32, u32)> {
let mut components = value.split('.');
Some((
components.next()?.parse().ok()?,
components.next()?.parse().ok()?,
components.next()?.parse().ok()?,
))
}
fn ensure_tool(tool: &str, version_argument: &str) -> io::Result<()> {
let status = Command::new(tool)
.arg(version_argument)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map_err(|error| io::Error::new(error.kind(), format!("{tool} is unavailable: {error}")))?;
if !status.success() {
return Err(io::Error::other(format!("{tool} version check failed")));
}
Ok(())
}
struct RuntimeSecretFile {
path: PathBuf,
}
impl RuntimeSecretFile {
fn new(label: &str, content: &[u8]) -> io::Result<Self> {
let directory = runtime_dir()?;
let path = directory.join(format!(
".{label}-{}-{}",
std::process::id(),
runtime_nonce()?
));
let secret = Self { path };
let mut file = private_new_file(&secret.path)?;
file.write_all(content)?;
file.sync_all()?;
Ok(secret)
}
}
impl Drop for RuntimeSecretFile {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
fn runtime_nonce() -> io::Result<String> {
let mut bytes = [0_u8; 8];
getrandom::fill(&mut bytes).map_err(|error| io::Error::other(error.to_string()))?;
Ok(u64::from_ne_bytes(bytes).to_string())
}
fn invalid_input(message: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message.into())
}
fn errno_error(error: rustix::io::Errno) -> io::Error {
io::Error::from_raw_os_error(error.raw_os_error())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn endpoints_reject_options_ports_and_shell_syntax() {
assert_eq!(
parse_endpoint("alice@example.local").unwrap(),
("alice", "example.local")
);
assert!(parse_endpoint("example.local").is_err());
assert!(parse_endpoint("-oProxyCommand=bad").is_err());
assert!(parse_endpoint("alice@example.local:2222").is_err());
assert!(parse_endpoint("alice@$(bad)").is_err());
assert!(parse_endpoint("alice@example.local/path").is_err());
}
#[test]
fn remote_paths_preserve_relative_components() {
assert_eq!(
remote_path("alice@example.local", Path::new("folder/file.txt")).unwrap(),
std::ffi::OsStr::new("alice@example.local::guth-sync/./folder/file.txt")
);
assert!(remote_path("alice@example.local", Path::new("../file")).is_err());
}
#[test]
fn remote_programs_are_fixed_names_or_safe_absolute_paths() {
assert!(validate_remote_program("guth-sync").is_ok());
assert!(validate_remote_program("/home/alice/.cargo/bin/guth-sync").is_ok());
assert!(validate_remote_program("other-program").is_err());
assert!(validate_remote_program("/tmp/guth sync").is_err());
assert!(validate_remote_program("/tmp/guth;bad").is_err());
}
#[test]
fn read_only_policy_rejects_local_write_directions() {
assert_eq!(
require_writable(true).unwrap_err().kind(),
io::ErrorKind::PermissionDenied
);
assert!(require_writable(false).is_ok());
}
#[cfg(unix)]
#[test]
fn selected_push_paths_cannot_cross_symlinks() {
use std::os::unix::fs::symlink;
use std::time::{SystemTime, UNIX_EPOCH};
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let root =
std::env::temp_dir().join(format!("guth-sync-symlink-{}-{nonce}", std::process::id()));
let outside =
std::env::temp_dir().join(format!("guth-sync-outside-{}-{nonce}", std::process::id()));
fs::create_dir(&root).unwrap();
fs::create_dir(&outside).unwrap();
fs::write(outside.join("secret.txt"), b"secret").unwrap();
symlink(&outside, root.join("escape")).unwrap();
assert!(validate_push_source(&root, Path::new("escape/secret.txt")).is_err());
fs::remove_dir_all(root).unwrap();
fs::remove_dir_all(outside).unwrap();
}
}