1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Copyright (c) International Business Machines Corp., 2009
4 *				Veerendra C <vechandr@in.ibm.com>
5 * Copyright (C) 2022 SUSE LLC Andrea Cervesato <andrea.cervesato@suse.com>
6 */
7
8/*\
9 * [Description]
10 *
11 * Test SysV IPC message passing through different namespaces.
12 *
13 * [Algorithm]
14 *
15 * In parent process create a new mesgq with a specific key.
16 * In cloned process try to access the created mesgq.
17 *
18 * Test will PASS if the mesgq is readable when flag is None.
19 * Test will FAIL if the mesgq is readable when flag is Unshare or Clone or
20 * the message received is wrong.
21 */
22
23#define _GNU_SOURCE
24
25#include <sys/wait.h>
26#include <sys/msg.h>
27#include <sys/types.h>
28#include "tst_safe_sysv_ipc.h"
29#include "tst_test.h"
30#include "common.h"
31
32#define KEY_VAL 154326L
33#define MSG_TYPE 5
34#define MSG_TEXT "My message!"
35
36static char *str_op;
37static int use_clone;
38static int ipc_id = -1;
39
40struct msg_buf {
41	long mtype;
42	char mtext[80];
43};
44
45static void check_mesgq(void)
46{
47	int id, n;
48	struct msg_buf msg = {};
49
50	id = msgget(KEY_VAL, 0);
51
52	if (id < 0) {
53		if (use_clone == T_NONE)
54			tst_res(TFAIL, "Plain cloned process didn't find mesgq");
55		else
56			tst_res(TPASS, "%s: container didn't find mesgq", str_op);
57
58		return;
59	}
60
61	if (use_clone == T_NONE) {
62		tst_res(TPASS, "Plain cloned process found mesgq inside container");
63
64		n = SAFE_MSGRCV(id, &msg, sizeof(msg.mtext), MSG_TYPE, 0);
65
66		tst_res(TINFO, "Mesg read of %d bytes, Type %ld, Msg: %s", n, msg.mtype, msg.mtext);
67
68		if (strcmp(msg.mtext, MSG_TEXT))
69			tst_res(TFAIL, "Received the wrong text message");
70
71		return;
72	}
73
74	tst_res(TFAIL, "%s: container init process found mesgq", str_op);
75}
76
77static void run(void)
78{
79	struct msg_buf msg = {
80		.mtype = MSG_TYPE,
81		.mtext = MSG_TEXT,
82	};
83
84	if (use_clone == T_NONE)
85		SAFE_MSGSND(ipc_id, &msg, strlen(msg.mtext), 0);
86
87	tst_res(TINFO, "mesgq namespaces test: %s", str_op);
88
89	clone_unshare_test(use_clone, CLONE_NEWIPC, check_mesgq);
90}
91
92static void setup(void)
93{
94	use_clone = get_clone_unshare_enum(str_op);
95	ipc_id = SAFE_MSGGET(KEY_VAL, IPC_CREAT | IPC_EXCL | 0600);
96}
97
98static void cleanup(void)
99{
100	if (ipc_id != -1) {
101		tst_res(TINFO, "Destroying message queue");
102		SAFE_MSGCTL(ipc_id, IPC_RMID, NULL);
103	}
104}
105
106static struct tst_test test = {
107	.test_all = run,
108	.setup = setup,
109	.cleanup = cleanup,
110	.needs_root = 1,
111	.forks_child = 1,
112	.options = (struct tst_option[]) {
113		{ "m:", &str_op, "Test execution mode <clone|unshare|none>" },
114		{},
115	},
116};
117