1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Copyright (c) International Business Machines Corp., 2001
3 * 07/2001 John George
4 * -Ported
5 *
6 * Verify that, stat(2) succeeds to get the status of a file and fills the
7 * stat structure elements regardless of whether process has or doesn't
8 * have read access to the file.
9 */
10
11 #include <sys/types.h>
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <errno.h>
15 #include <pwd.h>
16 #include "tst_test.h"
17
18 #define FILE_SIZE 1024
19 #define TST_FILEREAD "test_fileread"
20 #define TST_FILENOREAD "test_filenoread"
21 #define READ_MODE 0666
22 #define NEW_MODE 0222
23 #define MASK 0777
24
25 uid_t user_id;
26 gid_t group_id;
27 struct passwd *ltpuser;
28
29 static struct tcase{
30 char *pathname;
31 unsigned int mode;
32 } TC[] = {
33 {TST_FILEREAD, READ_MODE},
34 {TST_FILENOREAD, NEW_MODE}
35 };
36
verify_stat(unsigned int n)37 static void verify_stat(unsigned int n)
38 {
39 struct tcase *tc = TC + n;
40 struct stat stat_buf;
41 int fail = 0;
42
43 TEST(stat(tc->pathname, &stat_buf));
44
45 if (TST_RET == -1) {
46 tst_res(TFAIL | TTERRNO, "stat(%s) failed", tc->pathname);
47 return;
48 }
49
50 if (stat_buf.st_uid != user_id) {
51 tst_res(TFAIL, "stat_buf.st_uid = %i expected %i",
52 stat_buf.st_uid, user_id);
53 fail++;
54 }
55
56 if (stat_buf.st_gid != group_id) {
57 tst_res(TFAIL, "stat_buf.st_gid = %i expected %i",
58 stat_buf.st_gid, group_id);
59 fail++;
60 }
61
62 if (stat_buf.st_size != FILE_SIZE) {
63 tst_res(TFAIL, "stat_buf.st_size = %li expected %i",
64 (long)stat_buf.st_size, FILE_SIZE);
65 fail++;
66 }
67
68 if ((stat_buf.st_mode & MASK) != tc->mode) {
69 tst_res(TFAIL, "stat_buf.st_mode = %o expected %o",
70 (stat_buf.st_mode & MASK), tc->mode);
71 fail++;
72 }
73
74 if (!fail)
75 tst_res(TPASS, "stat(%s)", tc->pathname);
76 }
77
setup(void)78 void setup(void)
79 {
80 unsigned int i;
81
82 ltpuser = SAFE_GETPWNAM("nobody");
83 SAFE_SETUID(ltpuser->pw_uid);
84
85 for (i = 0; i < ARRAY_SIZE(TC); i++) {
86 if (tst_fill_file(TC[i].pathname, 'a', 256, 4))
87 tst_brk(TBROK, "Failed to create tst file %s",
88 TC[i].pathname);
89 SAFE_CHMOD(TC[i].pathname, TC[i].mode);
90 }
91
92 user_id = getuid();
93 group_id = getgid();
94 }
95
96 static struct tst_test test = {
97 .tcnt = ARRAY_SIZE(TC),
98 .setup = setup,
99 .test = verify_stat,
100 .needs_root = 1,
101 .needs_tmpdir = 1,
102 };
103