1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 
4 #include <sys/types.h>
5 #include <sys/socket.h>
6 #include <net/if.h>
7 #include <linux/in6.h>
8 
9 #include "test_progs.h"
10 #include "network_helpers.h"
11 #include "decap_sanity.skel.h"
12 
13 #define NS_TEST "decap_sanity_ns"
14 #define IPV6_IFACE_ADDR "face::1"
15 #define UDP_TEST_PORT 7777
16 
17 void test_decap_sanity(void)
18 {
19 	LIBBPF_OPTS(bpf_tc_hook, qdisc_hook, .attach_point = BPF_TC_EGRESS);
20 	LIBBPF_OPTS(bpf_tc_opts, tc_attach);
21 	struct nstoken *nstoken = NULL;
22 	struct decap_sanity *skel;
23 	struct sockaddr_in6 addr;
24 	socklen_t addrlen;
25 	char buf[128] = {};
26 	int sockfd, err;
27 
28 	skel = decap_sanity__open_and_load();
29 	if (!ASSERT_OK_PTR(skel, "skel open_and_load"))
30 		return;
31 
32 	SYS(fail, "ip netns add %s", NS_TEST);
33 	SYS(fail, "ip -net %s -6 addr add %s/128 dev lo nodad", NS_TEST, IPV6_IFACE_ADDR);
34 	SYS(fail, "ip -net %s link set dev lo up", NS_TEST);
35 
36 	nstoken = open_netns(NS_TEST);
37 	if (!ASSERT_OK_PTR(nstoken, "open_netns"))
38 		goto fail;
39 
40 	qdisc_hook.ifindex = if_nametoindex("lo");
41 	if (!ASSERT_GT(qdisc_hook.ifindex, 0, "if_nametoindex lo"))
42 		goto fail;
43 
44 	err = bpf_tc_hook_create(&qdisc_hook);
45 	if (!ASSERT_OK(err, "create qdisc hook"))
46 		goto fail;
47 
48 	tc_attach.prog_fd = bpf_program__fd(skel->progs.decap_sanity);
49 	err = bpf_tc_attach(&qdisc_hook, &tc_attach);
50 	if (!ASSERT_OK(err, "attach filter"))
51 		goto fail;
52 
53 	addrlen = sizeof(addr);
54 	err = make_sockaddr(AF_INET6, IPV6_IFACE_ADDR, UDP_TEST_PORT,
55 			    (void *)&addr, &addrlen);
56 	if (!ASSERT_OK(err, "make_sockaddr"))
57 		goto fail;
58 	sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
59 	if (!ASSERT_NEQ(sockfd, -1, "socket"))
60 		goto fail;
61 	err = sendto(sockfd, buf, sizeof(buf), 0, (void *)&addr, addrlen);
62 	close(sockfd);
63 	if (!ASSERT_EQ(err, sizeof(buf), "send"))
64 		goto fail;
65 
66 	ASSERT_TRUE(skel->bss->init_csum_partial, "init_csum_partial");
67 	ASSERT_TRUE(skel->bss->final_csum_none, "final_csum_none");
68 	ASSERT_FALSE(skel->bss->broken_csum_start, "broken_csum_start");
69 
70 fail:
71 	if (nstoken) {
72 		bpf_tc_hook_destroy(&qdisc_hook);
73 		close_netns(nstoken);
74 	}
75 	SYS_NOFAIL("ip netns del " NS_TEST " &> /dev/null");
76 	decap_sanity__destroy(skel);
77 }
78