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) The calling process does not have write permission on the message
9 * queue, so msgsnd(2) fails and sets errno to EACCES.
10 * 2) msgsnd(2) fails and sets errno to EFAULT if the message buffer address
11 * is invalid.
12 * 3) msgsnd(2) fails and sets errno to EINVAL if the queue ID is invalid.
13 * 4) msgsnd(2) fails and sets errno to EINVAL if the message type is not
14 * positive (0).
15 * 5) msgsnd(2) fails and sets errno to EINVAL if the message type is not
16 * positive (>0).
17 * 6) msgsnd(2) fails and sets errno to EINVAL if the message size is less
18 * than zero.
19 */
20
21 #include <errno.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <sys/types.h>
25 #include <sys/ipc.h>
26 #include <sys/msg.h>
27 #include <pwd.h>
28
29 #include "tst_test.h"
30 #include "tst_safe_sysv_ipc.h"
31 #include "libnewipc.h"
32
33 static key_t msgkey;
34 static int queue_id = -1;
35 static int bad_id = -1;
36 static struct passwd *pw;
37 static struct buf {
38 long type;
39 char text[MSGSIZE];
40 } snd_buf[] = {
41 {1, "hello"},
42 {0, "hello"},
43 {-1, "hello"}
44 };
45
46 static struct tcase {
47 int *id;
48 struct buf *buffer;
49 int msgsz;
50 int exp_err;
51 /*1: nobody expected 0: root expected */
52 int exp_user;
53 } tcases[] = {
54 {&queue_id, &snd_buf[0], MSGSIZE, EACCES, 1},
55 {&queue_id, NULL, MSGSIZE, EFAULT, 0},
56 {&bad_id, &snd_buf[0], MSGSIZE, EINVAL, 0},
57 {&queue_id, &snd_buf[1], MSGSIZE, EINVAL, 0},
58 {&queue_id, &snd_buf[2], MSGSIZE, EINVAL, 0},
59 {&queue_id, &snd_buf[0], -1, EINVAL, 0}
60 };
61
verify_msgsnd(struct tcase * tc)62 static void verify_msgsnd(struct tcase *tc)
63 {
64 TST_EXP_FAIL(msgsnd(*tc->id, tc->buffer, tc->msgsz, 0), tc->exp_err,
65 "msgsnd(%i, %p, %i, 0)", *tc->id, tc->buffer, tc->msgsz);
66 }
67
do_test(unsigned int n)68 static void do_test(unsigned int n)
69 {
70 pid_t pid;
71 struct tcase *tc = &tcases[n];
72
73 if (tc->exp_user == 0) {
74 verify_msgsnd(tc);
75 return;
76 }
77
78 pid = SAFE_FORK();
79 if (pid) {
80 tst_reap_children();
81 } else {
82 SAFE_SETUID(pw->pw_uid);
83 verify_msgsnd(tc);
84 }
85 }
86
setup(void)87 static void setup(void)
88 {
89 msgkey = GETIPCKEY();
90
91 queue_id = SAFE_MSGGET(msgkey, IPC_CREAT | IPC_EXCL | MSG_RW);
92
93 pw = SAFE_GETPWNAM("nobody");
94 }
95
cleanup(void)96 static void cleanup(void)
97 {
98 if (queue_id != -1)
99 SAFE_MSGCTL(queue_id, IPC_RMID, NULL);
100 }
101
102 static struct tst_test test = {
103 .needs_tmpdir = 1,
104 .needs_root = 1,
105 .forks_child = 1,
106 .tcnt = ARRAY_SIZE(tcases),
107 .setup = setup,
108 .cleanup = cleanup,
109 .test = do_test
110 };
111