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