1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2017 Oracle and/or its affiliates. All Rights Reserved.
4  */
5 
6 #define _GNU_SOURCE
7 #include <sched.h>
8 #include <stdlib.h>
9 #include <errno.h>
10 
11 #include "tst_test.h"
12 #include "clone_platform.h"
13 #include "lapi/syscalls.h"
14 #include "lapi/namespaces_constants.h"
15 
16 static void *child_stack;
17 static int sysctl_net = -1;
18 static int sysctl_net_new = -1;
19 static const char sysctl_path[] = "/proc/sys/net/ipv4/conf/lo/tag";
20 static const char sysctl_path_def[] = "/proc/sys/net/ipv4/conf/default/tag";
21 static int flags = CLONE_NEWNET | CLONE_VM | SIGCHLD;
22 
setup(void)23 static void setup(void)
24 {
25 	child_stack = SAFE_MALLOC(CHILD_STACK_SIZE);
26 }
27 
cleanup(void)28 static void cleanup(void)
29 {
30 	if (sysctl_net != -1)
31 		SAFE_FILE_PRINTF(sysctl_path, "%d", sysctl_net);
32 
33 	free(child_stack);
34 }
35 
newnet(void * arg LTP_ATTRIBUTE_UNUSED)36 static int newnet(void *arg LTP_ATTRIBUTE_UNUSED)
37 {
38 	SAFE_FILE_SCANF(sysctl_path, "%d", &sysctl_net_new);
39 	tst_syscall(__NR_exit, 0);
40 	return 0;
41 }
42 
clone_child(void)43 static long clone_child(void)
44 {
45 	TEST(ltp_clone(flags, newnet, NULL, CHILD_STACK_SIZE, child_stack));
46 
47 	if (TST_RET == -1 && TST_ERR == EINVAL)
48 		tst_brk(TCONF, "CONFIG_NET_NS was disabled");
49 
50 	if (TST_RET == -1)
51 		tst_brk(TBROK | TTERRNO, "clone(CLONE_NEWNET) failed");
52 
53 	return TST_RET;
54 }
55 
do_test(void)56 static void do_test(void)
57 {
58 	int def_val;
59 
60 	tst_res(TINFO, "create clone in a new netns with 'CLONE_NEWNET' flag");
61 
62 	SAFE_FILE_SCANF(sysctl_path, "%d", &sysctl_net);
63 	SAFE_FILE_PRINTF(sysctl_path, "%d", sysctl_net + 1);
64 
65 	clone_child();
66 	tst_reap_children();
67 
68 	if (sysctl_net_new == (sysctl_net + 1)) {
69 		tst_res(TFAIL, "sysctl params equal: %s=%d",
70 			sysctl_path, sysctl_net_new);
71 	}
72 
73 	SAFE_FILE_SCANF(sysctl_path_def, "%d", &def_val);
74 
75 	if (sysctl_net_new != def_val) {
76 		tst_res(TFAIL, "netns param init to non-default value %d",
77 			sysctl_net_new);
78 	}
79 
80 	/* restore previous value */
81 	SAFE_FILE_PRINTF(sysctl_path, "%d", sysctl_net);
82 
83 	tst_res(TPASS, "sysctl params differ in new netns");
84 }
85 
86 static struct tst_test test = {
87 	.test_all = do_test,
88 	.setup = setup,
89 	.cleanup = cleanup,
90 	.needs_root = 1,
91 	.min_kver = "2.6.24",
92 };
93