xref: /linux/tools/testing/selftests/bpf/prog_tests/socket_cookie.c (revision a4eb44a6435d6d8f9e642407a4a06f65eb90ca04)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2020 Google LLC.
3 // Copyright (c) 2018 Facebook
4 
5 #include <test_progs.h>
6 #include "socket_cookie_prog.skel.h"
7 #include "network_helpers.h"
8 
9 static int duration;
10 
11 struct socket_cookie {
12 	__u64 cookie_key;
13 	__u32 cookie_value;
14 };
15 
16 void test_socket_cookie(void)
17 {
18 	int server_fd = 0, client_fd = 0, cgroup_fd = 0, err = 0;
19 	socklen_t addr_len = sizeof(struct sockaddr_in6);
20 	struct socket_cookie_prog *skel;
21 	__u32 cookie_expected_value;
22 	struct sockaddr_in6 addr;
23 	struct socket_cookie val;
24 
25 	skel = socket_cookie_prog__open_and_load();
26 	if (!ASSERT_OK_PTR(skel, "skel_open"))
27 		return;
28 
29 	cgroup_fd = test__join_cgroup("/socket_cookie");
30 	if (CHECK(cgroup_fd < 0, "join_cgroup", "cgroup creation failed\n"))
31 		goto out;
32 
33 	skel->links.set_cookie = bpf_program__attach_cgroup(
34 		skel->progs.set_cookie, cgroup_fd);
35 	if (!ASSERT_OK_PTR(skel->links.set_cookie, "prog_attach"))
36 		goto close_cgroup_fd;
37 
38 	skel->links.update_cookie_sockops = bpf_program__attach_cgroup(
39 		skel->progs.update_cookie_sockops, cgroup_fd);
40 	if (!ASSERT_OK_PTR(skel->links.update_cookie_sockops, "prog_attach"))
41 		goto close_cgroup_fd;
42 
43 	skel->links.update_cookie_tracing = bpf_program__attach(
44 		skel->progs.update_cookie_tracing);
45 	if (!ASSERT_OK_PTR(skel->links.update_cookie_tracing, "prog_attach"))
46 		goto close_cgroup_fd;
47 
48 	server_fd = start_server(AF_INET6, SOCK_STREAM, "::1", 0, 0);
49 	if (CHECK(server_fd < 0, "start_server", "errno %d\n", errno))
50 		goto close_cgroup_fd;
51 
52 	client_fd = connect_to_fd(server_fd, 0);
53 	if (CHECK(client_fd < 0, "connect_to_fd", "errno %d\n", errno))
54 		goto close_server_fd;
55 
56 	err = bpf_map_lookup_elem(bpf_map__fd(skel->maps.socket_cookies),
57 				  &client_fd, &val);
58 	if (!ASSERT_OK(err, "map_lookup(socket_cookies)"))
59 		goto close_client_fd;
60 
61 	err = getsockname(client_fd, (struct sockaddr *)&addr, &addr_len);
62 	if (!ASSERT_OK(err, "getsockname"))
63 		goto close_client_fd;
64 
65 	cookie_expected_value = (ntohs(addr.sin6_port) << 8) | 0xFF;
66 	ASSERT_EQ(val.cookie_value, cookie_expected_value, "cookie_value");
67 
68 close_client_fd:
69 	close(client_fd);
70 close_server_fd:
71 	close(server_fd);
72 close_cgroup_fd:
73 	close(cgroup_fd);
74 out:
75 	socket_cookie_prog__destroy(skel);
76 }
77