1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
4 */
5
6 /*
7 * Description:
8 * The testcase checks the various errnos of the unlink(2).
9 * 1) unlink() returns EACCES when deleting file in unwritable directory
10 * as an unprivileged user.
11 * 2) unlink() returns EACCES when deleting file in "unsearchable directory
12 * as an unprivileged user.
13 * 3) unlink() returns EISDIR when deleting directory for root
14 * 4) unlink() returns EISDIR when deleting directory for regular user
15 */
16
17 #include <errno.h>
18 #include <stdlib.h>
19 #include <sys/types.h>
20 #include <pwd.h>
21 #include "tst_test.h"
22
23 static struct passwd *pw;
24
25 static struct test_case_t {
26 char *name;
27 char *desc;
28 int exp_errno;
29 int exp_user;
30 } tcases[] = {
31 {"unwrite_dir/file", "unwritable directory", EACCES, 1},
32 {"unsearch_dir/file", "unsearchable directory", EACCES, 1},
33 {"regdir", "directory", EISDIR, 0},
34 {"regdir", "directory", EISDIR, 1},
35 };
36
verify_unlink(struct test_case_t * tc)37 static void verify_unlink(struct test_case_t *tc)
38 {
39 TEST(unlink(tc->name));
40 if (TST_RET != -1) {
41 tst_res(TFAIL, "unlink(<%s>) succeeded unexpectedly",
42 tc->desc);
43 return;
44 }
45
46 if (TST_ERR == tc->exp_errno) {
47 tst_res(TPASS | TTERRNO, "unlink(<%s>) failed as expected",
48 tc->desc);
49 } else {
50 tst_res(TFAIL | TTERRNO,
51 "unlink(<%s>) failed, expected errno: %s",
52 tc->desc, tst_strerrno(tc->exp_errno));
53 }
54 }
55
do_unlink(unsigned int n)56 static void do_unlink(unsigned int n)
57 {
58 struct test_case_t *cases = &tcases[n];
59 pid_t pid;
60
61 if (cases->exp_user) {
62 pid = SAFE_FORK();
63 if (!pid) {
64 SAFE_SETUID(pw->pw_uid);
65 verify_unlink(cases);
66 exit(0);
67 }
68
69 SAFE_WAITPID(pid, NULL, 0);
70 } else {
71 verify_unlink(cases);
72 }
73 }
74
setup(void)75 static void setup(void)
76 {
77 SAFE_MKDIR("unwrite_dir", 0777);
78 SAFE_TOUCH("unwrite_dir/file", 0777, NULL);
79 SAFE_CHMOD("unwrite_dir", 0555);
80
81 SAFE_MKDIR("unsearch_dir", 0777);
82 SAFE_TOUCH("unsearch_dir/file", 0777, NULL);
83 SAFE_CHMOD("unsearch_dir", 0666);
84
85 SAFE_MKDIR("regdir", 0777);
86
87 pw = SAFE_GETPWNAM("nobody");
88 }
89
90 static struct tst_test test = {
91 .needs_root = 1,
92 .forks_child = 1,
93 .needs_tmpdir = 1,
94 .setup = setup,
95 .tcnt = ARRAY_SIZE(tcases),
96 .test = do_unlink,
97 };
98