1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <test_progs.h>
4 #include "netns_cookie_prog.skel.h"
5 #include "network_helpers.h"
6 
7 #ifndef SO_NETNS_COOKIE
8 #define SO_NETNS_COOKIE 71
9 #endif
10 
11 static int duration;
12 
13 void test_netns_cookie(void)
14 {
15 	int server_fd = -1, client_fd = -1, cgroup_fd = -1;
16 	int err, val, ret, map, verdict;
17 	struct netns_cookie_prog *skel;
18 	uint64_t cookie_expected_value;
19 	socklen_t vallen = sizeof(cookie_expected_value);
20 	static const char send_msg[] = "message";
21 
22 	skel = netns_cookie_prog__open_and_load();
23 	if (!ASSERT_OK_PTR(skel, "skel_open"))
24 		return;
25 
26 	cgroup_fd = test__join_cgroup("/netns_cookie");
27 	if (CHECK(cgroup_fd < 0, "join_cgroup", "cgroup creation failed\n"))
28 		goto done;
29 
30 	skel->links.get_netns_cookie_sockops = bpf_program__attach_cgroup(
31 		skel->progs.get_netns_cookie_sockops, cgroup_fd);
32 	if (!ASSERT_OK_PTR(skel->links.get_netns_cookie_sockops, "prog_attach"))
33 		goto done;
34 
35 	verdict = bpf_program__fd(skel->progs.get_netns_cookie_sk_msg);
36 	map = bpf_map__fd(skel->maps.sock_map);
37 	err = bpf_prog_attach(verdict, map, BPF_SK_MSG_VERDICT, 0);
38 	if (!ASSERT_OK(err, "prog_attach"))
39 		goto done;
40 
41 	server_fd = start_server(AF_INET6, SOCK_STREAM, "::1", 0, 0);
42 	if (CHECK(server_fd < 0, "start_server", "errno %d\n", errno))
43 		goto done;
44 
45 	client_fd = connect_to_fd(server_fd, 0);
46 	if (CHECK(client_fd < 0, "connect_to_fd", "errno %d\n", errno))
47 		goto done;
48 
49 	ret = send(client_fd, send_msg, sizeof(send_msg), 0);
50 	if (CHECK(ret != sizeof(send_msg), "send(msg)", "ret:%d\n", ret))
51 		goto done;
52 
53 	err = bpf_map_lookup_elem(bpf_map__fd(skel->maps.sockops_netns_cookies),
54 				  &client_fd, &val);
55 	if (!ASSERT_OK(err, "map_lookup(sockops_netns_cookies)"))
56 		goto done;
57 
58 	err = getsockopt(client_fd, SOL_SOCKET, SO_NETNS_COOKIE,
59 			 &cookie_expected_value, &vallen);
60 	if (!ASSERT_OK(err, "getsockopt"))
61 		goto done;
62 
63 	ASSERT_EQ(val, cookie_expected_value, "cookie_value");
64 
65 	err = bpf_map_lookup_elem(bpf_map__fd(skel->maps.sk_msg_netns_cookies),
66 				  &client_fd, &val);
67 	if (!ASSERT_OK(err, "map_lookup(sk_msg_netns_cookies)"))
68 		goto done;
69 
70 	ASSERT_EQ(val, cookie_expected_value, "cookie_value");
71 
72 done:
73 	if (server_fd != -1)
74 		close(server_fd);
75 	if (client_fd != -1)
76 		close(client_fd);
77 	if (cgroup_fd != -1)
78 		close(cgroup_fd);
79 	netns_cookie_prog__destroy(skel);
80 }
81