1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * 07/2001 Ported by Wayne Boyer
5 * Copyright (c) 2021 Xie Ziyao <xieziyao@huawei.com>
6 */
7
8 /*\
9 * [Description]
10 *
11 * Verify that, fchown() succeeds to change the owner and group of a file
12 * specified by file descriptor to any numeric owner(uid)/group(gid) values
13 * when invoked by super-user.
14 */
15
16 #include "tst_test.h"
17 #include "compat_tst_16.h"
18 #include "tst_safe_macros.h"
19
20 #define FILE_MODE (S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
21 #define TESTFILE "testfile"
22
23 static int fd;
24
25 struct test_case_t {
26 char *desc;
27 uid_t uid;
28 gid_t gid;
29 } tc[] = {
30 {"change owner/group ids", 700, 701},
31 {"change owner id only", 702, -1},
32 {"change owner id only", 703, 701},
33 {"change group id only", -1, 704},
34 {"change group id only", 703, 705},
35 {"no change", -1, -1}
36 };
37
run(unsigned int i)38 static void run(unsigned int i)
39 {
40 struct stat stat_buf;
41 uid_t expect_uid = tc[i].uid == (uid_t)-1 ? tc[i - 1].uid : tc[i].uid;
42 gid_t expect_gid = tc[i].gid == (uid_t)-1 ? tc[i - 1].gid : tc[i].gid;
43
44 TST_EXP_PASS(FCHOWN(fd, tc[i].uid, tc[i].gid), "fchown(%i, %i, %i), %s",
45 fd, tc[i].uid, tc[i].gid, tc[i].desc);
46
47 SAFE_FSTAT(fd, &stat_buf);
48 if (stat_buf.st_uid != expect_uid || stat_buf.st_gid != expect_gid) {
49 tst_res(TFAIL, "%s: incorrect ownership set, expected %d %d",
50 TESTFILE, expect_uid, expect_gid);
51 }
52 }
53
setup(void)54 static void setup(void)
55 {
56 fd = SAFE_OPEN(TESTFILE, O_RDWR | O_CREAT, FILE_MODE);
57 }
58
cleanup(void)59 static void cleanup(void)
60 {
61 if (fd > 0)
62 SAFE_CLOSE(fd);
63 }
64
65 static struct tst_test test = {
66 .tcnt = ARRAY_SIZE(tc),
67 .needs_root = 1,
68 .needs_tmpdir = 1,
69 .setup = setup,
70 .cleanup = cleanup,
71 .test = run,
72 };
73