use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use super::paths::InvokingUser;
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
pub(crate) fn create_missing(path: &Path, mode: Option<u32>) -> io::Result<Vec<PathBuf>> {
#[cfg(unix)]
if let Some(user) = invoking().filter(|user| inside_home(user, path)) {
return create_missing_in_home(user, path, mode);
}
let mut missing = Vec::new();
for ancestor in path.ancestors() {
if ancestor.as_os_str().is_empty() {
break;
}
match fs::symlink_metadata(ancestor) {
Ok(_) => break,
Err(e) if e.kind() == io::ErrorKind::NotFound => missing.push(ancestor),
Err(e) => return Err(e),
}
}
let mut created = Vec::new();
for directory in missing.into_iter().rev() {
#[cfg(unix)]
let builder = {
use std::os::unix::fs::DirBuilderExt;
let mut builder = fs::DirBuilder::new();
if let Some(mode) = mode {
builder.mode(mode);
}
builder
};
#[cfg(not(unix))]
let builder = {
let _ = mode;
fs::DirBuilder::new()
};
match builder.create(directory) {
Ok(()) => created.push(directory.to_path_buf()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
}
fs::create_dir_all(path)?;
Ok(created)
}
#[cfg(unix)]
fn create_missing_in_home(
user: &InvokingUser,
path: &Path,
mode: Option<u32>,
) -> io::Result<Vec<PathBuf>> {
let mut existing = path;
let mut missing = Vec::new();
loop {
match fs::symlink_metadata(existing) {
Ok(_) => break,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let (Some(parent), Some(name)) = (existing.parent(), existing.file_name()) else {
return Err(e);
};
missing.push((existing, name));
existing = parent;
}
Err(e) => return Err(e),
}
}
let mode = mode.unwrap_or(0o777) as libc::mode_t;
let mut current = walk_from_home(user, existing, true)?;
let mut created = Vec::new();
for (directory, name) in missing.into_iter().rev() {
let name = c_name(name)?;
if unsafe { libc::mkdirat(current.as_raw_fd(), name.as_ptr(), mode) } == 0 {
created.push(directory.to_path_buf());
} else {
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::AlreadyExists {
return Err(error);
}
}
current = open_at(¤t, &name, libc::O_RDONLY | libc::O_DIRECTORY, 0)?;
}
if !current.metadata()?.is_dir() {
return Err(io::Error::from_raw_os_error(libc::ENOTDIR));
}
Ok(created)
}
#[cfg(unix)]
pub(crate) struct Place {
directory: Option<fs::File>,
name: std::ffi::CString,
}
#[cfg(unix)]
impl Place {
pub(crate) fn of(path: &Path) -> io::Result<Self> {
Self::of_as(invoking(), path)
}
pub(crate) fn of_as(user: Option<&InvokingUser>, path: &Path) -> io::Result<Self> {
if let Some(user) = user.filter(|user| inside_home(user, path)) {
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
return Err(outside(path));
};
return Ok(Self {
directory: Some(walk_from_home(user, parent, true)?),
name: c_name(name)?,
});
}
Ok(Self {
directory: None,
name: c_name(path.as_os_str())?,
})
}
pub(crate) fn open(&self, flags: libc::c_int, mode: libc::mode_t) -> io::Result<fs::File> {
match &self.directory {
Some(directory) => open_at(directory, &self.name, flags, mode),
None => open_at_raw(libc::AT_FDCWD, &self.name, flags, mode),
}
}
#[cfg(feature = "journal-format")]
pub(crate) fn beside(&self, sibling: &std::ffi::OsStr) -> io::Result<Self> {
match &self.directory {
Some(directory) => Ok(Self {
directory: Some(directory.try_clone()?),
name: c_name(sibling)?,
}),
None => {
use std::os::unix::ffi::OsStrExt;
let path = Path::new(std::ffi::OsStr::from_bytes(self.name.as_bytes()));
Ok(Self {
directory: None,
name: c_name(path.with_file_name(sibling).as_os_str())?,
})
}
}
}
#[cfg(feature = "journal-format")]
pub(crate) fn create_directory(&self, mode: libc::mode_t) -> io::Result<()> {
done(unsafe { libc::mkdirat(self.descriptor(), self.name.as_ptr(), mode) })
}
#[cfg(feature = "journal-format")]
pub(crate) fn remove(&self) -> io::Result<()> {
done(unsafe { libc::unlinkat(self.descriptor(), self.name.as_ptr(), 0) })
}
#[cfg(feature = "journal-format")]
pub(crate) fn rename_over(&self, destination: &Self) -> io::Result<()> {
done(unsafe {
libc::renameat(
self.descriptor(),
self.name.as_ptr(),
destination.descriptor(),
destination.name.as_ptr(),
)
})
}
#[cfg(feature = "journal-format")]
pub(crate) fn link_as(&self, destination: &Self) -> io::Result<()> {
done(unsafe {
libc::linkat(
self.descriptor(),
self.name.as_ptr(),
destination.descriptor(),
destination.name.as_ptr(),
0,
)
})
}
#[cfg(feature = "journal-format")]
pub(crate) fn remove_tree(&self) -> io::Result<()> {
if !self.is_directory()? {
return self.remove();
}
let directory = self.open(libc::O_RDONLY | libc::O_DIRECTORY, 0)?;
for name in entries(&directory)? {
let entry = Self {
directory: Some(directory.try_clone()?),
name,
};
match entry.remove_tree() {
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {}
}
}
done(unsafe { libc::unlinkat(self.descriptor(), self.name.as_ptr(), libc::AT_REMOVEDIR) })
}
#[cfg(feature = "journal-format")]
pub(crate) fn is_directory(&self) -> io::Result<bool> {
Ok(self.kind()? == Kind::Directory)
}
#[cfg(feature = "journal-format")]
pub(crate) fn kind(&self) -> io::Result<Kind> {
Ok(match self.stat()?.st_mode & libc::S_IFMT {
libc::S_IFDIR => Kind::Directory,
libc::S_IFLNK => Kind::Link,
_ => Kind::Other,
})
}
#[cfg(feature = "journal-format")]
pub(crate) fn exists(&self) -> io::Result<bool> {
match self.stat() {
Ok(_) => Ok(true),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e),
}
}
#[cfg(feature = "journal-format")]
fn stat(&self) -> io::Result<libc::stat> {
let mut held = std::mem::MaybeUninit::<libc::stat>::uninit();
done(unsafe {
libc::fstatat(
self.descriptor(),
self.name.as_ptr(),
held.as_mut_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
})?;
Ok(unsafe { held.assume_init() })
}
#[cfg(feature = "journal-format")]
fn descriptor(&self) -> libc::c_int {
self.directory
.as_ref()
.map_or(libc::AT_FDCWD, |directory| directory.as_raw_fd())
}
}
#[cfg(feature = "journal-format")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
Directory,
Link,
Other,
}
#[cfg(all(unix, feature = "journal-format"))]
pub(crate) struct Directory {
walked: Option<fs::File>,
path: PathBuf,
}
#[cfg(all(unix, feature = "journal-format"))]
impl Directory {
pub(crate) fn of(path: &Path) -> io::Result<Self> {
Self::of_as(invoking(), path)
}
pub(crate) fn of_as(user: Option<&InvokingUser>, path: &Path) -> io::Result<Self> {
let walked = match user.filter(|user| inside_home(user, path)) {
Some(user) => Some(walk_from_home(user, path, false)?),
None => None,
};
Ok(Self {
walked,
path: path.to_path_buf(),
})
}
pub(crate) fn names(&self) -> io::Result<Vec<std::ffi::OsString>> {
use std::os::unix::ffi::OsStringExt;
match &self.walked {
Some(directory) => Ok(entries(directory)?
.into_iter()
.map(|name| std::ffi::OsString::from_vec(name.into_bytes()))
.collect()),
None => fs::read_dir(&self.path)?
.map(|entry| entry.map(|entry| entry.file_name()))
.collect(),
}
}
pub(crate) fn entry(&self, name: &std::ffi::OsStr) -> io::Result<Place> {
match &self.walked {
Some(directory) => Ok(Place {
directory: Some(directory.try_clone()?),
name: c_name(name)?,
}),
None => Ok(Place {
directory: None,
name: c_name(self.path.join(name).as_os_str())?,
}),
}
}
}
#[cfg(all(not(unix), feature = "journal-format"))]
pub(crate) struct Place {
path: PathBuf,
}
#[cfg(all(not(unix), feature = "journal-format"))]
impl Place {
pub(crate) fn of(path: &Path) -> io::Result<Self> {
Ok(Self {
path: path.to_path_buf(),
})
}
pub(crate) fn path(&self) -> &Path {
&self.path
}
pub(crate) fn beside(&self, sibling: &std::ffi::OsStr) -> io::Result<Self> {
Ok(Self {
path: self.path.with_file_name(sibling),
})
}
pub(crate) fn remove(&self) -> io::Result<()> {
fs::remove_file(&self.path)
}
pub(crate) fn rename_over(&self, destination: &Self) -> io::Result<()> {
fs::rename(&self.path, &destination.path)
}
pub(crate) fn link_as(&self, destination: &Self) -> io::Result<()> {
fs::hard_link(&self.path, &destination.path)
}
pub(crate) fn remove_tree(&self) -> io::Result<()> {
fs::remove_dir_all(&self.path)
}
pub(crate) fn kind(&self) -> io::Result<Kind> {
let held = fs::symlink_metadata(&self.path)?.file_type();
Ok(if held.is_symlink() {
Kind::Link
} else if held.is_dir() {
Kind::Directory
} else {
Kind::Other
})
}
pub(crate) fn exists(&self) -> io::Result<bool> {
match fs::symlink_metadata(&self.path) {
Ok(_) => Ok(true),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e),
}
}
}
#[cfg(all(not(unix), feature = "journal-format"))]
pub(crate) struct Directory {
path: PathBuf,
}
#[cfg(all(not(unix), feature = "journal-format"))]
impl Directory {
pub(crate) fn of(path: &Path) -> io::Result<Self> {
Ok(Self {
path: path.to_path_buf(),
})
}
pub(crate) fn names(&self) -> io::Result<Vec<std::ffi::OsString>> {
fs::read_dir(&self.path)?
.map(|entry| entry.map(|entry| entry.file_name()))
.collect()
}
pub(crate) fn entry(&self, name: &std::ffi::OsStr) -> io::Result<Place> {
Ok(Place {
path: self.path.join(name),
})
}
}
#[cfg(unix)]
pub(crate) fn invoking() -> Option<&'static InvokingUser> {
static INVOKING: std::sync::OnceLock<Option<InvokingUser>> = std::sync::OnceLock::new();
INVOKING.get_or_init(super::paths::invoking_user).as_ref()
}
#[cfg(unix)]
pub(crate) fn give(path: &Path) {
let Some(user) = invoking() else { return };
let Ok(opened) = open_in_home(user, path) else {
return;
};
unsafe {
libc::fchown(opened.as_raw_fd(), user.uid, user.gid);
}
}
#[cfg(all(unix, feature = "import-settings"))]
pub(crate) fn hand_over(leaf: &Path, created: &[PathBuf]) {
let Some(user) = invoking() else { return };
let mut on_the_way: Vec<&Path> = leaf
.ancestors()
.take_while(|directory| inside_home(user, directory))
.collect();
on_the_way.reverse();
for directory in on_the_way {
if created.iter().any(|made| made == directory) {
give(directory);
} else {
reclaim(directory);
}
}
}
#[cfg(all(unix, feature = "journal-format"))]
pub(crate) fn give_open(opened: &fs::File, path: &Path) {
let Some((uid, gid)) = owner_for(invoking(), path) else {
return;
};
unsafe {
libc::fchown(opened.as_raw_fd(), uid, gid);
}
}
#[cfg(unix)]
pub(crate) fn reclaim(path: &Path) {
use std::os::unix::fs::MetadataExt;
let Some(user) = invoking() else { return };
let Ok(opened) = open_in_home(user, path) else {
return;
};
if !opened.metadata().is_ok_and(|held| held.uid() == 0) {
return;
}
let changed = unsafe { libc::fchown(opened.as_raw_fd(), user.uid, user.gid) } == 0;
if changed {
crate::info!(
verbosity = 1,
"{} given back to its user (left to root)",
path.display()
);
}
}
#[cfg(unix)]
fn open_in_home(user: &InvokingUser, path: &Path) -> io::Result<fs::File> {
walk_from_home(user, path, false)
}
#[cfg(unix)]
fn walk_from_home(user: &InvokingUser, path: &Path, home_itself: bool) -> io::Result<fs::File> {
let spelled_inside = inside_home(user, path) || (home_itself && path == user.home);
if !spelled_inside {
return Err(outside(path));
}
let home = fs::canonicalize(&user.home)?;
let resolved = fs::canonicalize(path)?;
let below = resolved
.strip_prefix(&home)
.ok()
.filter(|below| home_itself || !below.as_os_str().is_empty())
.ok_or_else(|| outside(path))?;
let mut current = fs::File::open(&home)?;
for component in below.components() {
let std::path::Component::Normal(name) = component else {
return Err(outside(path));
};
current = open_at(¤t, &c_name(name)?, libc::O_RDONLY, 0)?;
}
Ok(current)
}
#[cfg(unix)]
fn outside(path: &Path) -> io::Error {
io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} leads out of the invoking user's home", path.display()),
)
}
#[cfg(unix)]
fn c_name(name: &std::ffi::OsStr) -> io::Result<std::ffi::CString> {
use std::os::unix::ffi::OsStrExt;
std::ffi::CString::new(name.as_bytes()).map_err(io::Error::other)
}
#[cfg(all(unix, feature = "journal-format"))]
fn done(returned: libc::c_int) -> io::Result<()> {
if returned == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(all(unix, feature = "journal-format"))]
fn entries(directory: &fs::File) -> io::Result<Vec<std::ffi::CString>> {
use std::os::unix::io::IntoRawFd;
let descriptor = directory.try_clone()?.into_raw_fd();
let stream = unsafe { libc::fdopendir(descriptor) };
if stream.is_null() {
let error = io::Error::last_os_error();
unsafe { libc::close(descriptor) };
return Err(error);
}
unsafe { libc::rewinddir(stream) };
let mut names = Vec::new();
loop {
let entry = unsafe { libc::readdir(stream) };
if entry.is_null() {
break;
}
let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) };
if !matches!(name.to_bytes(), b"." | b"..") {
names.push(name.to_owned());
}
}
unsafe { libc::closedir(stream) };
Ok(names)
}
#[cfg(unix)]
fn open_at(
directory: &fs::File,
name: &std::ffi::CStr,
flags: libc::c_int,
mode: libc::mode_t,
) -> io::Result<fs::File> {
open_at_raw(directory.as_raw_fd(), name, flags, mode)
}
#[cfg(unix)]
fn open_at_raw(
directory: libc::c_int,
name: &std::ffi::CStr,
flags: libc::c_int,
mode: libc::mode_t,
) -> io::Result<fs::File> {
use std::os::unix::io::FromRawFd;
let opened = unsafe {
libc::openat(
directory,
name.as_ptr(),
flags | libc::O_NOFOLLOW | libc::O_CLOEXEC,
mode as libc::c_uint,
)
};
if opened < 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { fs::File::from_raw_fd(opened) })
}
#[cfg(not(unix))]
pub(crate) fn give(_path: &Path) {}
#[cfg(all(not(unix), feature = "import-settings"))]
pub(crate) fn hand_over(_leaf: &Path, _created: &[PathBuf]) {}
#[cfg(all(not(unix), feature = "journal-format"))]
pub(crate) fn give_open(_opened: &fs::File, _path: &Path) {}
#[cfg(not(unix))]
pub(crate) fn reclaim(_path: &Path) {}
#[cfg(all(unix, any(test, feature = "journal-format")))]
fn owner_for(invoking: Option<&InvokingUser>, path: &Path) -> Option<(u32, u32)> {
let user = invoking?;
inside_home(user, path).then_some((user.uid, user.gid))
}
#[cfg(unix)]
pub(crate) fn inside_home(user: &InvokingUser, path: &Path) -> bool {
let climbs = path
.components()
.any(|part| part == std::path::Component::ParentDir);
!climbs && path != user.home && path.starts_with(&user.home)
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("zond-ownership-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("scratch root");
dir
}
#[test]
fn creating_reports_exactly_the_directories_it_made() {
let home = scratch("create");
fs::create_dir(home.join(".local")).expect("an existing directory");
let target = home.join(".local/state/zond");
let created = create_missing(&target, Some(0o700)).expect("creates");
assert_eq!(
created,
[home.join(".local/state"), home.join(".local/state/zond")]
);
assert!(target.is_dir());
assert_eq!(
create_missing(&target, None).expect("exists"),
Vec::<PathBuf>::new()
);
let file = home.join("file");
fs::write(&file, b"").expect("writes");
assert!(create_missing(&file, None).is_err());
let _ = fs::remove_dir_all(&home);
}
#[cfg(unix)]
#[test]
fn only_what_lies_inside_the_invoking_users_home_is_given_to_them() {
let user = InvokingUser {
uid: 1000,
gid: 1000,
home: PathBuf::from("/home/user"),
};
for inside in ["/home/user/.local", "/home/user/.config/zond/engine.toml"] {
assert_eq!(
owner_for(Some(&user), Path::new(inside)),
Some((1000, 1000)),
"{inside}"
);
}
for outside in [
"/etc/zond",
"/home/user",
"/home/user2/.config",
"/home/user/../root/.config",
] {
assert_eq!(
owner_for(Some(&user), Path::new(outside)),
None,
"{outside}"
);
}
assert_eq!(owner_for(None, Path::new("/home/user/.local")), None);
}
#[cfg(unix)]
#[test]
fn nothing_is_reached_through_a_link_out_of_the_home() {
let scratch = scratch("links");
let home = scratch.join("home");
let elsewhere = scratch.join("etc");
fs::create_dir_all(elsewhere.join("zond")).expect("a directory outside");
fs::create_dir_all(home.join("dotfiles/config/zond")).expect("a directory inside");
std::os::unix::fs::symlink(&elsewhere, home.join(".config")).expect("links out");
std::os::unix::fs::symlink(home.join("dotfiles/config"), home.join(".cfg"))
.expect("links within");
let user = InvokingUser {
uid: 1000,
gid: 1000,
home: home.clone(),
};
assert!(open_in_home(&user, &home.join(".config/zond")).is_err());
assert!(open_in_home(&user, &home.join(".cfg/zond")).is_ok());
assert!(open_in_home(&user, &home.join("dotfiles/config/zond")).is_ok());
assert!(
open_in_home(&user, &home).is_err(),
"the home is never given"
);
let _ = fs::remove_dir_all(&scratch);
}
#[cfg(all(unix, feature = "journal-format"))]
#[test]
fn a_listing_is_not_led_out_of_the_home_by_a_link() {
let scratch = scratch("lists");
let home = scratch.join("home");
let elsewhere = scratch.join("elsewhere");
fs::create_dir_all(elsewhere.join("state/zond/01ID")).expect("a journal outside");
fs::create_dir_all(home.join("kept/zond/02ID")).expect("a journal inside");
std::os::unix::fs::symlink(&elsewhere, home.join(".local")).expect("links out");
std::os::unix::fs::symlink(&elsewhere, home.join("kept/zond/03ID")).expect("links in");
let user = InvokingUser {
uid: 1000,
gid: 1000,
home: home.clone(),
};
let led_out = Directory::of_as(Some(&user), &home.join(".local/state/zond"))
.and_then(|directory| directory.names());
assert_eq!(
led_out.map_err(|e| e.kind()),
Err(io::ErrorKind::PermissionDenied),
"listed a directory behind a link out of the home"
);
let kept = Directory::of_as(Some(&user), &home.join("kept/zond")).expect("reached");
let mut names = kept.names().expect("lists");
names.sort();
assert_eq!(names, ["02ID", "03ID"]);
let journal = kept.entry("02ID".as_ref()).expect("an entry");
let link = kept.entry("03ID".as_ref()).expect("an entry");
assert!(journal.is_directory().expect("looks"));
assert!(link.exists().expect("looks"), "the link is there");
assert!(
!link.is_directory().expect("looks"),
"a link to a directory was looked at as the directory"
);
let _ = fs::remove_dir_all(&scratch);
}
#[cfg(all(unix, feature = "journal-format"))]
#[test]
fn nothing_is_created_through_a_link_out_of_the_home() {
let scratch = scratch("creates");
let home = scratch.join("home");
let elsewhere = scratch.join("elsewhere");
fs::create_dir_all(elsewhere.join("journal")).expect("a directory outside");
fs::create_dir_all(&home).expect("a home");
std::os::unix::fs::symlink(&elsewhere, home.join(".local")).expect("links out");
let user = InvokingUser {
uid: 1000,
gid: 1000,
home: home.clone(),
};
let directories = create_missing_in_home(&user, &home.join(".local/state/zond"), None);
assert!(
directories.is_err(),
"created through the link: {directories:?}"
);
let file = Place::of_as(Some(&user), &home.join(".local/journal/manifest.json"))
.and_then(|place| place.open(libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL, 0o600));
assert!(file.is_err(), "a file was created through the link");
let directory = Place::of_as(Some(&user), &home.join(".local/journal/01ID"))
.and_then(|place| place.create_directory(0o700));
assert!(
directory.is_err(),
"a directory was created through the link"
);
let behind: Vec<_> = fs::read_dir(&elsewhere)
.expect("lists")
.chain(fs::read_dir(elsewhere.join("journal")).expect("lists"))
.map(|entry| entry.expect("an entry").file_name())
.collect();
assert_eq!(behind, ["journal"], "something appeared behind the link");
let _ = fs::remove_dir_all(&scratch);
}
#[cfg(all(unix, feature = "journal-format"))]
#[test]
fn removing_a_journal_removes_only_what_the_walk_reached() {
let scratch = scratch("removes");
let home = scratch.join("home");
let elsewhere = scratch.join("elsewhere");
let journal = home.join("state/01ID");
fs::create_dir_all(journal.join("inner")).expect("a journal");
fs::write(journal.join("manifest.json"), b"{}").expect("writes");
fs::write(journal.join("inner/stray"), b"").expect("writes");
fs::create_dir_all(elsewhere.join("01ID")).expect("a directory outside");
fs::write(elsewhere.join("01ID/precious"), b"kept").expect("writes");
std::os::unix::fs::symlink(elsewhere.join("01ID"), journal.join("linked"))
.expect("links out from inside");
let user = InvokingUser {
uid: 1000,
gid: 1000,
home: home.clone(),
};
let place = Place::of_as(Some(&user), &journal).expect("reached");
fs::rename(home.join("state"), home.join("kept")).expect("moves aside");
std::os::unix::fs::symlink(&elsewhere, home.join("state")).expect("links out above");
place.remove_tree().expect("removes");
assert!(
!home.join("kept/01ID").exists(),
"the journal the walk reached is still there"
);
assert_eq!(
fs::read(elsewhere.join("01ID/precious")).expect("still there"),
b"kept"
);
fs::remove_file(home.join("state")).expect("removes the link");
fs::create_dir(home.join("state")).expect("a directory");
std::os::unix::fs::symlink(elsewhere.join("01ID"), &journal).expect("links");
Place::of_as(None, &journal)
.and_then(|place| place.remove_tree())
.expect("removes the link");
assert!(
fs::symlink_metadata(&journal).is_err(),
"the link is still there"
);
assert!(elsewhere.join("01ID/precious").is_file());
let _ = fs::remove_dir_all(&scratch);
}
#[cfg(unix)]
#[test]
fn a_link_that_stays_in_the_home_is_created_through() {
let scratch = scratch("creates-within");
let home = scratch.join("home");
fs::create_dir_all(home.join("dotfiles/local")).expect("a directory inside");
std::os::unix::fs::symlink(home.join("dotfiles/local"), home.join(".local"))
.expect("links within");
let user = InvokingUser {
uid: 1000,
gid: 1000,
home: home.clone(),
};
let created = create_missing_in_home(&user, &home.join(".local/state/zond"), Some(0o700))
.expect("creates through a link inside the home");
assert_eq!(
created,
[home.join(".local/state"), home.join(".local/state/zond")]
);
assert!(home.join("dotfiles/local/state/zond").is_dir());
let manifest = home.join(".local/state/zond/manifest.json");
Place::of_as(Some(&user), &manifest)
.and_then(|place| place.open(libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL, 0o600))
.expect("creates a file through a link inside the home");
assert!(
home.join("dotfiles/local/state/zond/manifest.json")
.is_file()
);
assert_eq!(
create_missing_in_home(&user, &home.join(".local/state/zond"), None).expect("exists"),
Vec::<PathBuf>::new()
);
assert!(create_missing_in_home(&user, &manifest, None).is_err());
let elsewhere = scratch.join("elsewhere");
fs::create_dir_all(&elsewhere).expect("a directory outside");
std::os::unix::fs::symlink(&elsewhere, home.join(".cache")).expect("links out");
Place::of_as(None, &home.join(".cache/file"))
.and_then(|place| place.open(libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL, 0o600))
.expect("an unelevated run follows its own user's link");
assert!(elsewhere.join("file").is_file());
let _ = fs::remove_dir_all(&scratch);
}
}