#include "macros.h"
#include <sys/stat.h>
#include "atf-c.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <unistd.h>
static char path[] = "unlink";
ATF_TC_WITH_CLEANUP(unlink_basic);
ATF_TC_HEAD(unlink_basic, tc)
{
atf_tc_set_md_var(tc, "descr", "A basic test of unlink(2)");
}
ATF_TC_BODY(unlink_basic, tc)
{
const size_t n = 512;
size_t i;
int fd;
for (i = 0; i < n; i++) {
fd = open(path, O_RDWR | O_CREAT, 0666);
ATF_REQUIRE(fd != -1);
ATF_REQUIRE(close(fd) == 0);
ATF_REQUIRE(unlink(path) == 0);
errno = 0;
ATF_REQUIRE_ERRNO(ENOENT, open(path, O_RDONLY) == -1);
}
}
ATF_TC_CLEANUP(unlink_basic, tc)
{
(void)unlink(path);
}
ATF_TC_WITH_CLEANUP(unlink_err);
ATF_TC_HEAD(unlink_err, tc)
{
atf_tc_set_md_var(tc, "descr", "Test error conditions of unlink(2)");
}
ATF_TC_BODY(unlink_err, tc)
{
char buf[PATH_MAX + 1];
(void)memset(buf, 'x', sizeof(buf));
errno = 0;
ATF_REQUIRE(unlink("/") == -1);
errno = 0;
ATF_REQUIRE_ERRNO(ENAMETOOLONG, unlink(buf) == -1);
errno = 0;
ATF_REQUIRE_ERRNO(ENOENT, unlink("/a/b/c/d/e/f/g/h/i/j/k/l/m") == -1);
}
ATF_TC_CLEANUP(unlink_err, tc)
{
(void)unlink(path);
}
ATF_TC_WITH_CLEANUP(unlink_fifo);
ATF_TC_HEAD(unlink_fifo, tc)
{
atf_tc_set_md_var(tc, "descr", "Test unlink(2) for a FIFO");
}
ATF_TC_BODY(unlink_fifo, tc)
{
ATF_REQUIRE(mkfifo(path, 0666) == 0);
ATF_REQUIRE(unlink(path) == 0);
errno = 0;
ATF_REQUIRE_ERRNO(ENOENT, open(path, O_RDONLY) == -1);
}
ATF_TC_CLEANUP(unlink_fifo, tc)
{
(void)unlink(path);
}
ATF_TC_WITH_CLEANUP(unlink_perm);
ATF_TC_HEAD(unlink_perm, tc)
{
atf_tc_set_md_var(tc, "descr", "Test permissions with unlink(2)");
atf_tc_set_md_var(tc, "require.user", "unprivileged");
}
ATF_TC_BODY(unlink_perm, tc)
{
int rv;
errno = 0;
rv = unlink("/etc");
ATF_REQUIRE_MSG(rv == -1 && (errno == EACCES || errno == EPERM),
"unlinking a directory did not fail with EPERM or EACCESS; "
"unlink() returned %d, errno %d", rv, errno);
errno = 0;
ATF_REQUIRE_ERRNO(EACCES, unlink("/root/.profile") == -1);
}
ATF_TC_CLEANUP(unlink_perm, tc)
{
(void)unlink(path);
}
ATF_TP_ADD_TCS(tp)
{
ATF_TP_ADD_TC(tp, unlink_basic);
ATF_TP_ADD_TC(tp, unlink_err);
ATF_TP_ADD_TC(tp, unlink_fifo);
ATF_TP_ADD_TC(tp, unlink_perm);
return atf_no_error();
}