xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/open/open08.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (c) 2013 Wanlong Gao <[email protected]>
4  *   Copyright (c) 2018 Linux Test Project
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Verify that open() fails with:
11  *
12  * - EEXIST when pathname already exists and O_CREAT and O_EXCL were used
13  * - EISDIR when pathname refers to a directory and the access requested
14  * involved writing
15  * - ENOTDIR when O_DIRECTORY was specified and pathname was not a directory
16  * - ENAMETOOLONG when pathname was too long
17  * - EACCES when requested access to the file is not allowed
18  * - EFAULT when pathname points outside the accessible address space
19  */
20 
21 #define _GNU_SOURCE		/* for O_DIRECTORY */
22 
23 #include <pwd.h>
24 #include "tst_test.h"
25 
26 #define FLAGS_DESC(x) .flags = x, .desc = #x
27 
28 static char *existing_fname = "open08_testfile";
29 static char *toolong_fname = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyz";
30 static char *dir_fname = "/tmp";
31 static char *user2_fname = "user2_0600";
32 static char *unmapped_fname;
33 
34 struct test_case_t;
35 
36 static struct test_case_t {
37 	char **fname;
38 	int flags;
39 	const char *desc;
40 	int error;
41 } tcases[] = {
42 	{&existing_fname, FLAGS_DESC(O_CREAT | O_EXCL), EEXIST},
43 	{&dir_fname, FLAGS_DESC(O_RDWR), EISDIR},
44 	{&existing_fname, FLAGS_DESC(O_DIRECTORY), ENOTDIR},
45 	{&toolong_fname, FLAGS_DESC(O_RDWR), ENAMETOOLONG},
46 	{&user2_fname, FLAGS_DESC(O_WRONLY), EACCES},
47 	{&unmapped_fname, FLAGS_DESC(O_CREAT), EFAULT},
48 };
49 
verify_open(unsigned int i)50 static void verify_open(unsigned int i)
51 {
52 	TST_EXP_FAIL2(open(*tcases[i].fname, tcases[i].flags, 0644),
53 				tcases[i].error, "%s", tcases[i].desc);
54 }
55 
setup(void)56 static void setup(void)
57 {
58 	int fildes;
59 	char nobody_uid[] = "nobody";
60 	struct passwd *ltpuser;
61 
62 	umask(0);
63 
64 	SAFE_CREAT(user2_fname, 0600);
65 
66 	/* Switch to nobody user for correct error code collection */
67 	ltpuser = getpwnam(nobody_uid);
68 	SAFE_SETGID(ltpuser->pw_gid);
69 	SAFE_SETUID(ltpuser->pw_uid);
70 
71 	fildes = SAFE_CREAT(existing_fname, 0600);
72 	SAFE_CLOSE(fildes);
73 
74 	unmapped_fname = tst_get_bad_addr(NULL);
75 }
76 
77 static struct tst_test test = {
78 	.tcnt = ARRAY_SIZE(tcases),
79 	.needs_tmpdir = 1,
80 	.needs_root = 1,
81 	.setup = setup,
82 	.test = verify_open,
83 };
84