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 SYS(fmt, ...)						\
14 	({							\
15 		char cmd[1024];					\
16 		snprintf(cmd, sizeof(cmd), fmt, ##__VA_ARGS__);	\
17 		if (!ASSERT_OK(system(cmd), cmd))		\
18 			goto fail;				\
19 	})
20 
21 #define NS_TEST "decap_sanity_ns"
22 #define IPV6_IFACE_ADDR "face::1"
23 #define UDP_TEST_PORT 7777
24 
25 void test_decap_sanity(void)
26 {
27 	LIBBPF_OPTS(bpf_tc_hook, qdisc_hook, .attach_point = BPF_TC_EGRESS);
28 	LIBBPF_OPTS(bpf_tc_opts, tc_attach);
29 	struct nstoken *nstoken = NULL;
30 	struct decap_sanity *skel;
31 	struct sockaddr_in6 addr;
32 	socklen_t addrlen;
33 	char buf[128] = {};
34 	int sockfd, err;
35 
36 	skel = decap_sanity__open_and_load();
37 	if (!ASSERT_OK_PTR(skel, "skel open_and_load"))
38 		return;
39 
40 	SYS("ip netns add %s", NS_TEST);
41 	SYS("ip -net %s -6 addr add %s/128 dev lo nodad", NS_TEST, IPV6_IFACE_ADDR);
42 	SYS("ip -net %s link set dev lo up", NS_TEST);
43 
44 	nstoken = open_netns(NS_TEST);
45 	if (!ASSERT_OK_PTR(nstoken, "open_netns"))
46 		goto fail;
47 
48 	qdisc_hook.ifindex = if_nametoindex("lo");
49 	if (!ASSERT_GT(qdisc_hook.ifindex, 0, "if_nametoindex lo"))
50 		goto fail;
51 
52 	err = bpf_tc_hook_create(&qdisc_hook);
53 	if (!ASSERT_OK(err, "create qdisc hook"))
54 		goto fail;
55 
56 	tc_attach.prog_fd = bpf_program__fd(skel->progs.decap_sanity);
57 	err = bpf_tc_attach(&qdisc_hook, &tc_attach);
58 	if (!ASSERT_OK(err, "attach filter"))
59 		goto fail;
60 
61 	addrlen = sizeof(addr);
62 	err = make_sockaddr(AF_INET6, IPV6_IFACE_ADDR, UDP_TEST_PORT,
63 			    (void *)&addr, &addrlen);
64 	if (!ASSERT_OK(err, "make_sockaddr"))
65 		goto fail;
66 	sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
67 	if (!ASSERT_NEQ(sockfd, -1, "socket"))
68 		goto fail;
69 	err = sendto(sockfd, buf, sizeof(buf), 0, (void *)&addr, addrlen);
70 	close(sockfd);
71 	if (!ASSERT_EQ(err, sizeof(buf), "send"))
72 		goto fail;
73 
74 	ASSERT_TRUE(skel->bss->init_csum_partial, "init_csum_partial");
75 	ASSERT_TRUE(skel->bss->final_csum_none, "final_csum_none");
76 	ASSERT_FALSE(skel->bss->broken_csum_start, "broken_csum_start");
77 
78 fail:
79 	if (nstoken) {
80 		bpf_tc_hook_destroy(&qdisc_hook);
81 		close_netns(nstoken);
82 	}
83 	system("ip netns del " NS_TEST " >& /dev/null");
84 	decap_sanity__destroy(skel);
85 }
86