1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2023 Isovalent */
5 #include <linux/if_ether.h>
8 #include <linux/ipv6.h>
10 #include <linux/udp.h>
11 #include <bpf/bpf_endian.h>
12 #include <bpf/bpf_helpers.h>
13 #include <linux/pkt_cls.h>
15 char LICENSE[] SEC("license") = "GPL";
18 __u64 reuseport_executed;
24 const volatile __u16 dest_port;
27 __uint(type, BPF_MAP_TYPE_SOCKMAP);
28 __uint(max_entries, 1);
31 } sk_map SEC(".maps");
34 int reuse_accept(struct sk_reuseport_md *ctx)
38 if (ctx->ip_protocol == IPPROTO_TCP) {
39 if (ctx->data + sizeof(headers.tcp) > ctx->data_end)
42 if (__builtin_memcmp(&headers.tcp, ctx->data, sizeof(headers.tcp)) != 0)
44 } else if (ctx->ip_protocol == IPPROTO_UDP) {
45 if (ctx->data + sizeof(headers.udp) > ctx->data_end)
48 if (__builtin_memcmp(&headers.udp, ctx->data, sizeof(headers.udp)) != 0)
54 sk_cookie_seen = bpf_get_socket_cookie(ctx->sk);
59 int reuse_drop(struct sk_reuseport_md *ctx)
67 assign_sk(struct __sk_buff *skb)
69 int zero = 0, ret = 0;
72 sk = bpf_map_lookup_elem(&sk_map, &zero);
75 ret = bpf_sk_assign(skb, sk, 0);
77 return ret ? TC_ACT_SHOT : TC_ACT_OK;
81 maybe_assign_tcp(struct __sk_buff *skb, struct tcphdr *th)
83 if (th + 1 > (void *)(long)(skb->data_end))
86 if (!th->syn || th->ack || th->dest != bpf_htons(dest_port))
89 __builtin_memcpy(&headers.tcp, th, sizeof(headers.tcp));
90 return assign_sk(skb);
94 maybe_assign_udp(struct __sk_buff *skb, struct udphdr *uh)
96 if (uh + 1 > (void *)(long)(skb->data_end))
99 if (uh->dest != bpf_htons(dest_port))
102 __builtin_memcpy(&headers.udp, uh, sizeof(headers.udp));
103 return assign_sk(skb);
107 int tc_main(struct __sk_buff *skb)
109 void *data_end = (void *)(long)skb->data_end;
110 void *data = (void *)(long)skb->data;
113 eth = (struct ethhdr *)(data);
114 if (eth + 1 > data_end)
117 if (eth->h_proto == bpf_htons(ETH_P_IP)) {
118 struct iphdr *iph = (struct iphdr *)(data + sizeof(*eth));
120 if (iph + 1 > data_end)
123 if (iph->protocol == IPPROTO_TCP)
124 return maybe_assign_tcp(skb, (struct tcphdr *)(iph + 1));
125 else if (iph->protocol == IPPROTO_UDP)
126 return maybe_assign_udp(skb, (struct udphdr *)(iph + 1));
130 struct ipv6hdr *ip6h = (struct ipv6hdr *)(data + sizeof(*eth));
132 if (ip6h + 1 > data_end)
135 if (ip6h->nexthdr == IPPROTO_TCP)
136 return maybe_assign_tcp(skb, (struct tcphdr *)(ip6h + 1));
137 else if (ip6h->nexthdr == IPPROTO_UDP)
138 return maybe_assign_udp(skb, (struct udphdr *)(ip6h + 1));