#include <sys/param.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <dirent.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <libutil.h>
#include <spawn.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "pwupd.h"
static bool try_dataset_remove(const char *home);
extern char **environ;
bool
rm_r(int rootfd, const char *path, uid_t uid)
{
int dirfd;
DIR *d;
struct dirent *e;
struct stat st;
const char *fullpath;
bool skipped = false;
fullpath = path;
if (*path == '/')
path++;
dirfd = openat(rootfd, path, O_DIRECTORY);
if (dirfd == -1) {
return (true);
}
d = fdopendir(dirfd);
if (d == NULL) {
(void)close(dirfd);
return (true);
}
while ((e = readdir(d)) != NULL) {
if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0)
continue;
if (fstatat(dirfd, e->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0)
continue;
if (S_ISDIR(st.st_mode)) {
if (rm_r(dirfd, e->d_name, uid) == true)
skipped = true;
} else if (S_ISLNK(st.st_mode) || st.st_uid == uid)
unlinkat(dirfd, e->d_name, 0);
else
skipped = true;
}
closedir(d);
if (fstatat(rootfd, path, &st, AT_SYMLINK_NOFOLLOW) != 0)
return (skipped);
if (S_ISLNK(st.st_mode)) {
if (unlinkat(rootfd, path, 0) == -1)
skipped = true;
} else if (st.st_uid == uid) {
if (unlinkat(rootfd, path, AT_REMOVEDIR) == -1) {
if (errno == EBUSY && skipped == false)
skipped = try_dataset_remove(fullpath);
else
skipped = true;
}
} else
skipped = true;
return (skipped);
}
static bool
try_dataset_remove(const char *path)
{
bool skipped = true;
struct statfs stat;
const char *argv[] = {
"/sbin/zfs",
"destroy",
NULL,
NULL
};
int status;
pid_t pid;
if (*path != '/')
return (skipped);
if (kld_isloaded("zfs") == 0)
return (skipped);
if (strcmp(conf.rootdir, "/") != 0) {
warnx("cannot destroy home dataset when -R was used");
return (skipped);
}
if (statfs(path, &stat) != 0) {
warn("statfs %s", path);
return (skipped);
}
if (strcmp(stat.f_mntonname, path) != 0)
return (skipped);
argv[2] = stat.f_mntfromname;
if ((skipped = posix_spawn(&pid, argv[0], NULL, NULL,
(char *const *) argv, environ)) != 0) {
warn("Failed to execute '%s %s %s'",
argv[0], argv[1], argv[2]);
} else {
if (waitpid(pid, &status, 0) != -1 && status != 0) {
warnx("'%s %s %s' exit status %d\n",
argv[0], argv[1], argv[2], status);
}
}
return (skipped);
}