abuild-rmtemp.c 1.05 KB
Newer Older
1 2 3 4 5 6
/*
 * abuild-rmtemp
 * Copyright (c) 2017 Kaarle Ritvanen
 * Distributed under GPL-2
 */

7
#define _XOPEN_SOURCE 700
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <err.h>
#include <errno.h>
#include <ftw.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define PREFIX "/var/tmp/abuild."

static void fail() {
	errx(1, "%s", strerror(errno));
}

static int handler(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
	return remove(fpath);
}

int main(int argc, char **argv) {
	if (argc < 2) return 0;

	if (getuid()) {
		argv[0] = "-abuild-rmtemp";
		execv("/usr/bin/abuild-sudo", argv);
	}

	if (strncmp(argv[1], PREFIX, strlen(PREFIX)) || \
		strchr(argv[1] + strlen(PREFIX), '/'))
		errx(1, "Invalid path: %s", argv[1]);

	struct stat s;
	if (lstat(argv[1], &s)) fail();
	struct passwd *p = getpwnam(getenv("USER"));
	if (!p) errx(1, "Incorrect user");
	if (s.st_uid != p->pw_uid) errx(1, "Permission denied");

47
	if (nftw(argv[1], handler, 512, FTW_DEPTH|FTW_PHYS)) fail();
48 49 50

	return 0;
}