1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * Ported to LTP: Wayne Boyer
5 * 06/2017 Modified by Guangwen Feng <fenggw-fnst@cn.fujitsu.com>
6 */
7 /*
8 * DESCRIPTION
9 * 1. open a new file without O_CREAT, ENOENT should be returned.
10 * 2. open a file with O_RDONLY | O_NOATIME and the caller was not
11 * privileged, EPERM should be returned.
12 */
13
14 #define _GNU_SOURCE
15
16 #include <stdio.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <pwd.h>
22 #include "tst_test.h"
23
24 #define TEST_FILE "test_file"
25 #define TEST_FILE2 "test_file2"
26
27 static struct tcase {
28 char *filename;
29 int flag;
30 int exp_errno;
31 } tcases[] = {
32 {TEST_FILE, O_RDWR, ENOENT},
33 {TEST_FILE2, O_RDONLY | O_NOATIME, EPERM},
34 };
35
setup(void)36 void setup(void)
37 {
38 struct passwd *ltpuser;
39
40 SAFE_TOUCH(TEST_FILE2, 0644, NULL);
41
42 ltpuser = SAFE_GETPWNAM("nobody");
43
44 SAFE_SETEUID(ltpuser->pw_uid);
45 }
46
verify_open(unsigned int n)47 static void verify_open(unsigned int n)
48 {
49 struct tcase *tc = &tcases[n];
50
51 TEST(open(tc->filename, tc->flag, 0444));
52
53 if (TST_RET != -1) {
54 tst_res(TFAIL, "open(%s) succeeded unexpectedly",
55 tc->filename);
56 return;
57 }
58
59 if (tc->exp_errno != TST_ERR) {
60 tst_res(TFAIL | TTERRNO,
61 "open() should fail with %s",
62 tst_strerrno(tc->exp_errno));
63 return;
64 }
65
66 tst_res(TPASS | TTERRNO, "open() failed as expected");
67 }
68
cleanup(void)69 void cleanup(void)
70 {
71 SAFE_SETEUID(0);
72 }
73
74 static struct tst_test test = {
75 .tcnt = ARRAY_SIZE(tcases),
76 .needs_root = 1,
77 .needs_tmpdir = 1,
78 .setup = setup,
79 .cleanup = cleanup,
80 .test = verify_open,
81 };
82