1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 */
5
6 /*
7 * DESCRIPTION
8 * 1) msgget(2) fails if a message queue exists for key and msgflg
9 * specified both IPC_CREAT and IPC_EXCL.
10 * 2) msgget(2) fails if no message queue exists for key and msgflg
11 * did not specify IPC_CREAT.
12 * 3) msgget(2) fails if a message queue exists for key, but the
13 * calling process does not have permission to access the queue,
14 * and does not have the CAP_IPC_OWNER capability.
15 *
16 */
17 #include <errno.h>
18 #include <stdlib.h>
19 #include <sys/types.h>
20 #include <sys/ipc.h>
21 #include <sys/msg.h>
22 #include <pwd.h>
23
24 #include "tst_test.h"
25 #include "tst_safe_sysv_ipc.h"
26 #include "libnewipc.h"
27
28 static key_t msgkey, msgkey1;
29 static int queue_id = -1;
30 static struct passwd *pw;
31
32 static struct tcase {
33 int *key;
34 int flags;
35 int exp_err;
36 /*1: nobody expected 0: root expected */
37 int exp_user;
38 } tcases[] = {
39 {&msgkey, IPC_CREAT | IPC_EXCL, EEXIST, 0},
40 {&msgkey1, IPC_PRIVATE, ENOENT, 0},
41 {&msgkey1, IPC_EXCL, ENOENT, 0},
42 {&msgkey, MSG_RD, EACCES, 1},
43 {&msgkey, MSG_WR, EACCES, 1},
44 {&msgkey, MSG_RW, EACCES, 1}
45 };
46
verify_msgget(struct tcase * tc)47 static void verify_msgget(struct tcase *tc)
48 {
49 TEST(msgget(*tc->key, tc->flags));
50
51 if (TST_RET != -1) {
52 tst_res(TFAIL, "msgget() succeeded unexpectedly");
53 return;
54 }
55
56 if (TST_ERR == tc->exp_err) {
57 tst_res(TPASS | TTERRNO, "msgget() failed as expected");
58 } else {
59 tst_res(TFAIL | TTERRNO, "msgget() failed unexpectedly,"
60 " expected %s", tst_strerrno(tc->exp_err));
61 }
62 }
63
do_test(unsigned int n)64 static void do_test(unsigned int n)
65 {
66 pid_t pid;
67 struct tcase *tc = &tcases[n];
68
69 if (tc->exp_user == 0) {
70 verify_msgget(tc);
71 } else {
72 pid = SAFE_FORK();
73 if (pid) {
74 tst_reap_children();
75 } else {
76 SAFE_SETUID(pw->pw_uid);
77 verify_msgget(tc);
78 exit(0);
79 }
80 }
81 }
82
setup(void)83 static void setup(void)
84 {
85 msgkey = GETIPCKEY();
86 msgkey1 = GETIPCKEY();
87
88 queue_id = SAFE_MSGGET(msgkey, IPC_CREAT | IPC_EXCL);
89
90 pw = SAFE_GETPWNAM("nobody");
91 }
92
cleanup(void)93 static void cleanup(void)
94 {
95 if (queue_id != -1)
96 SAFE_MSGCTL(queue_id, IPC_RMID, NULL);
97 }
98
99 static struct tst_test test = {
100 .needs_tmpdir = 1,
101 .needs_root = 1,
102 .forks_child = 1,
103 .tcnt = ARRAY_SIZE(tcases),
104 .setup = setup,
105 .cleanup = cleanup,
106 .test = do_test
107 };
108