• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 (stat_buf.st_nlink != 1) {
75 		tst_res(TFAIL, "stat_buf.st_nlink = %lu expected 1",
76 			stat_buf.st_nlink);
77 		fail++;
78 	}
79 
80 	if (!fail)
81 		tst_res(TPASS, "stat(%s)", tc->pathname);
82 }
83 
setup(void)84 static void setup(void)
85 {
86 	unsigned int i;
87 
88 	ltpuser = SAFE_GETPWNAM("nobody");
89 	SAFE_SETUID(ltpuser->pw_uid);
90 
91 	for (i = 0; i < ARRAY_SIZE(TC); i++) {
92 		if (tst_fill_file(TC[i].pathname, 'a', 256, 4))
93 			tst_brk(TBROK, "Failed to create tst file %s",
94 				TC[i].pathname);
95 		SAFE_CHMOD(TC[i].pathname, TC[i].mode);
96 	}
97 
98 	user_id = getuid();
99 	group_id = getgid();
100 }
101 
102 static struct tst_test test = {
103 	.tcnt = ARRAY_SIZE(TC),
104 	.setup = setup,
105 	.test = verify_stat,
106 	.needs_root = 1,
107 	.needs_tmpdir = 1,
108 };
109