• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <linux/if.h>
18 #include <linux/ip.h>
19 #include <linux/ipv6.h>
20 #include <linux/pkt_cls.h>
21 #include <linux/tcp.h>
22 
23 // bionic kernel uapi linux/udp.h header is munged...
24 #define __kernel_udphdr udphdr
25 #include <linux/udp.h>
26 
27 #ifdef BTF
28 // BTF is incompatible with bpfloaders < v0.10, hence for S (v0.2) we must
29 // ship a different file than for later versions, but we need bpfloader v0.25+
30 // for obj@ver.o support
31 #define BPFLOADER_MIN_VER BPFLOADER_OBJ_AT_VER_VERSION
32 #else /* BTF */
33 // The resulting .o needs to load on the Android S bpfloader
34 #define BPFLOADER_MIN_VER BPFLOADER_S_VERSION
35 #define BPFLOADER_MAX_VER BPFLOADER_OBJ_AT_VER_VERSION
36 #endif /* BTF */
37 
38 // Warning: values other than AID_ROOT don't work for map uid on BpfLoader < v0.21
39 #define TETHERING_UID AID_ROOT
40 
41 #define TETHERING_GID AID_NETWORK_STACK
42 
43 #include "bpf_helpers.h"
44 #include "bpf_net_helpers.h"
45 #include "offload.h"
46 
47 // From kernel:include/net/ip.h
48 #define IP_DF 0x4000  // Flag: "Don't Fragment"
49 
50 // ----- Helper functions for offsets to fields -----
51 
52 // They all assume simple IP packets:
53 //   - no VLAN ethernet tags
54 //   - no IPv4 options (see IPV4_HLEN/TCP4_OFFSET/UDP4_OFFSET)
55 //   - no IPv6 extension headers
56 //   - no TCP options (see TCP_HLEN)
57 
58 //#define ETH_HLEN sizeof(struct ethhdr)
59 #define IP4_HLEN sizeof(struct iphdr)
60 #define IP6_HLEN sizeof(struct ipv6hdr)
61 #define TCP_HLEN sizeof(struct tcphdr)
62 #define UDP_HLEN sizeof(struct udphdr)
63 
64 // Offsets from beginning of L4 (TCP/UDP) header
65 #define TCP_OFFSET(field) offsetof(struct tcphdr, field)
66 #define UDP_OFFSET(field) offsetof(struct udphdr, field)
67 
68 // Offsets from beginning of L3 (IPv4) header
69 #define IP4_OFFSET(field) offsetof(struct iphdr, field)
70 #define IP4_TCP_OFFSET(field) (IP4_HLEN + TCP_OFFSET(field))
71 #define IP4_UDP_OFFSET(field) (IP4_HLEN + UDP_OFFSET(field))
72 
73 // Offsets from beginning of L3 (IPv6) header
74 #define IP6_OFFSET(field) offsetof(struct ipv6hdr, field)
75 #define IP6_TCP_OFFSET(field) (IP6_HLEN + TCP_OFFSET(field))
76 #define IP6_UDP_OFFSET(field) (IP6_HLEN + UDP_OFFSET(field))
77 
78 // Offsets from beginning of L2 (ie. Ethernet) header (which must be present)
79 #define ETH_IP4_OFFSET(field) (ETH_HLEN + IP4_OFFSET(field))
80 #define ETH_IP4_TCP_OFFSET(field) (ETH_HLEN + IP4_TCP_OFFSET(field))
81 #define ETH_IP4_UDP_OFFSET(field) (ETH_HLEN + IP4_UDP_OFFSET(field))
82 #define ETH_IP6_OFFSET(field) (ETH_HLEN + IP6_OFFSET(field))
83 #define ETH_IP6_TCP_OFFSET(field) (ETH_HLEN + IP6_TCP_OFFSET(field))
84 #define ETH_IP6_UDP_OFFSET(field) (ETH_HLEN + IP6_UDP_OFFSET(field))
85 
86 // ----- Tethering Error Counters -----
87 
88 // Note that pre-T devices with Mediatek chipsets may have a kernel bug (bad patch
89 // "[ALPS05162612] bpf: fix ubsan error") making it impossible to write to non-zero
90 // offset of bpf map ARRAYs.  This file (offload.o) loads on S+, but luckily this
91 // array is only written by bpf code, and only read by userspace.
DEFINE_BPF_MAP_RO(tether_error_map,ARRAY,uint32_t,uint32_t,BPF_TETHER_ERR__MAX,TETHERING_GID)92 DEFINE_BPF_MAP_RO(tether_error_map, ARRAY, uint32_t, uint32_t, BPF_TETHER_ERR__MAX, TETHERING_GID)
93 
94 #define COUNT_AND_RETURN(counter, ret) do {                     \
95     uint32_t code = BPF_TETHER_ERR_ ## counter;                 \
96     uint32_t *count = bpf_tether_error_map_lookup_elem(&code);  \
97     if (count) __sync_fetch_and_add(count, 1);                  \
98     return ret;                                                 \
99 } while(0)
100 
101 #define TC_DROP(counter) COUNT_AND_RETURN(counter, TC_ACT_SHOT)
102 #define TC_PUNT(counter) COUNT_AND_RETURN(counter, TC_ACT_PIPE)
103 
104 #define XDP_DROP(counter) COUNT_AND_RETURN(counter, XDP_DROP)
105 #define XDP_PUNT(counter) COUNT_AND_RETURN(counter, XDP_PASS)
106 
107 // ----- Tethering Data Stats and Limits -----
108 
109 // Tethering stats, indexed by upstream interface.
110 DEFINE_BPF_MAP_GRW(tether_stats_map, HASH, TetherStatsKey, TetherStatsValue, 16, TETHERING_GID)
111 
112 // Tethering data limit, indexed by upstream interface.
113 // (tethering allowed when stats[iif].rxBytes + stats[iif].txBytes < limit[iif])
114 DEFINE_BPF_MAP_GRW(tether_limit_map, HASH, TetherLimitKey, TetherLimitValue, 16, TETHERING_GID)
115 
116 // ----- IPv6 Support -----
117 
118 DEFINE_BPF_MAP_GRW(tether_downstream6_map, HASH, TetherDownstream6Key, Tether6Value, 64,
119                    TETHERING_GID)
120 
121 DEFINE_BPF_MAP_GRW(tether_downstream64_map, HASH, TetherDownstream64Key, TetherDownstream64Value,
122                    1024, TETHERING_GID)
123 
124 DEFINE_BPF_MAP_GRW(tether_upstream6_map, HASH, TetherUpstream6Key, Tether6Value, 64,
125                    TETHERING_GID)
126 
127 static inline __always_inline int do_forward6(struct __sk_buff* skb, const bool is_ethernet,
128         const bool downstream, const unsigned kver) {
129     // Must be meta-ethernet IPv6 frame
130     if (skb->protocol != htons(ETH_P_IPV6)) return TC_ACT_PIPE;
131 
132     // Require ethernet dst mac address to be our unicast address.
133     if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
134 
135     const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
136 
137     // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
138     // not trigger and thus we need to manually make sure we can read packet headers via DPA.
139     // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
140     // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
141     try_make_writable(skb, l2_header_size + IP6_HLEN + TCP_HLEN);
142 
143     void* data = (void*)(long)skb->data;
144     const void* data_end = (void*)(long)skb->data_end;
145     struct ethhdr* eth = is_ethernet ? data : NULL;  // used iff is_ethernet
146     struct ipv6hdr* ip6 = is_ethernet ? (void*)(eth + 1) : data;
147 
148     // Must have (ethernet and) ipv6 header
149     if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_PIPE;
150 
151     // Ethertype - if present - must be IPv6
152     if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_PIPE;
153 
154     // IP version must be 6
155     if (ip6->version != 6) TC_PUNT(INVALID_IPV6_VERSION);
156 
157     // Cannot decrement during forward if already zero or would be zero,
158     // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
159     if (ip6->hop_limit <= 1) TC_PUNT(LOW_TTL);
160 
161     // If hardware offload is running and programming flows based on conntrack entries,
162     // try not to interfere with it.
163     if (ip6->nexthdr == IPPROTO_TCP) {
164         struct tcphdr* tcph = (void*)(ip6 + 1);
165 
166         // Make sure we can get at the tcp header
167         if (data + l2_header_size + sizeof(*ip6) + sizeof(*tcph) > data_end)
168             TC_PUNT(INVALID_TCP_HEADER);
169 
170         // Do not offload TCP packets with any one of the SYN/FIN/RST flags
171         if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCPV6_CONTROL_PACKET);
172     }
173 
174     // Protect against forwarding packets sourced from ::1 or fe80::/64 or other weirdness.
175     __be32 src32 = ip6->saddr.s6_addr32[0];
176     if (src32 != htonl(0x0064ff9b) &&                        // 64:ff9b:/32 incl. XLAT464 WKP
177         (src32 & htonl(0xe0000000)) != htonl(0x20000000))    // 2000::/3 Global Unicast
178         TC_PUNT(NON_GLOBAL_SRC);
179 
180     // Protect against forwarding packets destined to ::1 or fe80::/64 or other weirdness.
181     __be32 dst32 = ip6->daddr.s6_addr32[0];
182     if (dst32 != htonl(0x0064ff9b) &&                        // 64:ff9b:/32 incl. XLAT464 WKP
183         (dst32 & htonl(0xe0000000)) != htonl(0x20000000))    // 2000::/3 Global Unicast
184         TC_PUNT(NON_GLOBAL_DST);
185 
186     // In the upstream direction do not forward traffic within the same /64 subnet.
187     if (!downstream && (src32 == dst32) && (ip6->saddr.s6_addr32[1] == ip6->daddr.s6_addr32[1]))
188         TC_PUNT(LOCAL_SRC_DST);
189 
190     TetherDownstream6Key kd = {
191             .iif = skb->ifindex,
192             .neigh6 = ip6->daddr,
193     };
194 
195     TetherUpstream6Key ku = {
196             .iif = skb->ifindex,
197     };
198     if (is_ethernet) __builtin_memcpy(downstream ? kd.dstMac : ku.dstMac, eth->h_dest, ETH_ALEN);
199 
200     Tether6Value* v = downstream ? bpf_tether_downstream6_map_lookup_elem(&kd)
201                                  : bpf_tether_upstream6_map_lookup_elem(&ku);
202 
203     // If we don't find any offload information then simply let the core stack handle it...
204     if (!v) return TC_ACT_PIPE;
205 
206     uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
207 
208     TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
209 
210     // If we don't have anywhere to put stats, then abort...
211     if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
212 
213     uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
214 
215     // If we don't have a limit, then abort...
216     if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
217 
218     // Required IPv6 minimum mtu is 1280, below that not clear what we should do, abort...
219     if (v->pmtu < IPV6_MIN_MTU) TC_PUNT(BELOW_IPV6_MTU);
220 
221     // Approximate handling of TCP/IPv6 overhead for incoming LRO/GRO packets: default
222     // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
223     // undercount, which is still better then not accounting for this overhead at all.
224     // Note: this really shouldn't be device/path mtu at all, but rather should be
225     // derived from this particular connection's mss (ie. from gro segment size).
226     // This would require a much newer kernel with newer ebpf accessors.
227     // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
228     uint64_t packets = 1;
229     uint64_t L3_bytes = skb->len - l2_header_size;
230     if (L3_bytes > v->pmtu) {
231         const int tcp6_overhead = sizeof(struct ipv6hdr) + sizeof(struct tcphdr) + 12;
232         const int mss = v->pmtu - tcp6_overhead;
233         const uint64_t payload = L3_bytes - tcp6_overhead;
234         packets = (payload + mss - 1) / mss;
235         L3_bytes = tcp6_overhead * packets + payload;
236     }
237 
238     // Are we past the limit?  If so, then abort...
239     // Note: will not overflow since u64 is 936 years even at 5Gbps.
240     // Do not drop here.  Offload is just that, whenever we fail to handle
241     // a packet we let the core stack deal with things.
242     // (The core stack needs to handle limits correctly anyway,
243     // since we don't offload all traffic in both directions)
244     if (stat_v->rxBytes + stat_v->txBytes + L3_bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
245 
246     if (!is_ethernet) {
247         // Try to inject an ethernet header, and simply return if we fail.
248         // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
249         // because this is easier and the kernel will strip extraneous ethernet header.
250         if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
251             __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
252             TC_PUNT(CHANGE_HEAD_FAILED);
253         }
254 
255         // bpf_skb_change_head() invalidates all pointers - reload them
256         data = (void*)(long)skb->data;
257         data_end = (void*)(long)skb->data_end;
258         eth = data;
259         ip6 = (void*)(eth + 1);
260 
261         // I do not believe this can ever happen, but keep the verifier happy...
262         if (data + sizeof(struct ethhdr) + sizeof(*ip6) > data_end) {
263             __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
264             TC_DROP(TOO_SHORT);
265         }
266     };
267 
268     // At this point we always have an ethernet header - which will get stripped by the
269     // kernel during transmit through a rawip interface.  ie. 'eth' pointer is valid.
270     // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
271 
272     // CHECKSUM_COMPLETE is a 16-bit one's complement sum,
273     // thus corrections for it need to be done in 16-byte chunks at even offsets.
274     // IPv6 nexthdr is at offset 6, while hop limit is at offset 7
275     uint8_t old_hl = ip6->hop_limit;
276     --ip6->hop_limit;
277     uint8_t new_hl = ip6->hop_limit;
278 
279     // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
280     // (-ENOTSUPP) if it isn't.
281     bpf_csum_update(skb, 0xFFFF - ntohs(old_hl) + ntohs(new_hl));
282 
283     __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
284     __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, L3_bytes);
285 
286     // Overwrite any mac header with the new one
287     // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
288     *eth = v->macHeader;
289 
290     // Redirect to forwarded interface.
291     //
292     // Note that bpf_redirect() cannot fail unless you pass invalid flags.
293     // The redirect actually happens after the ebpf program has already terminated,
294     // and can fail for example for mtu reasons at that point in time, but there's nothing
295     // we can do about it here.
296     return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
297 }
298 
299 DEFINE_BPF_PROG("schedcls/tether_downstream6_ether", TETHERING_UID, TETHERING_GID,
300                 sched_cls_tether_downstream6_ether)
301 (struct __sk_buff* skb) {
302     return do_forward6(skb, ETHER, DOWNSTREAM, KVER_NONE);
303 }
304 
305 DEFINE_BPF_PROG("schedcls/tether_upstream6_ether", TETHERING_UID, TETHERING_GID,
306                 sched_cls_tether_upstream6_ether)
307 (struct __sk_buff* skb) {
308     return do_forward6(skb, ETHER, UPSTREAM, KVER_NONE);
309 }
310 
311 // Note: section names must be unique to prevent programs from appending to each other,
312 // so instead the bpf loader will strip everything past the final $ symbol when actually
313 // pinning the program into the filesystem.
314 //
315 // bpf_skb_change_head() is only present on 4.14+ and 2 trivial kernel patches are needed:
316 //   ANDROID: net: bpf: Allow TC programs to call BPF_FUNC_skb_change_head
317 //   ANDROID: net: bpf: permit redirect from ingress L3 to egress L2 devices at near max mtu
318 // (the first of those has already been upstreamed)
319 //
320 // These were added to 4.14+ Android Common Kernel in R (including the original release of ACK 5.4)
321 // and there is a test in kernel/tests/net/test/bpf_test.py testSkbChangeHead()
322 // and in system/netd/tests/binder_test.cpp NetdBinderTest TetherOffloadForwarding.
323 //
324 // Hence, these mandatory (must load successfully) implementations for 4.14+ kernels:
325 DEFINE_BPF_PROG_KVER("schedcls/tether_downstream6_rawip$4_14", TETHERING_UID, TETHERING_GID,
326                      sched_cls_tether_downstream6_rawip_4_14, KVER(4, 14, 0))
327 (struct __sk_buff* skb) {
328     return do_forward6(skb, RAWIP, DOWNSTREAM, KVER(4, 14, 0));
329 }
330 
331 DEFINE_BPF_PROG_KVER("schedcls/tether_upstream6_rawip$4_14", TETHERING_UID, TETHERING_GID,
332                      sched_cls_tether_upstream6_rawip_4_14, KVER(4, 14, 0))
333 (struct __sk_buff* skb) {
334     return do_forward6(skb, RAWIP, UPSTREAM, KVER(4, 14, 0));
335 }
336 
337 // and define no-op stubs for pre-4.14 kernels.
338 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$stub", TETHERING_UID, TETHERING_GID,
339                            sched_cls_tether_downstream6_rawip_stub, KVER_NONE, KVER(4, 14, 0))
340 (struct __sk_buff* skb) {
341     return TC_ACT_PIPE;
342 }
343 
344 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$stub", TETHERING_UID, TETHERING_GID,
345                            sched_cls_tether_upstream6_rawip_stub, KVER_NONE, KVER(4, 14, 0))
346 (struct __sk_buff* skb) {
347     return TC_ACT_PIPE;
348 }
349 
350 // ----- IPv4 Support -----
351 
352 DEFINE_BPF_MAP_GRW(tether_downstream4_map, HASH, Tether4Key, Tether4Value, 1024, TETHERING_GID)
353 
354 DEFINE_BPF_MAP_GRW(tether_upstream4_map, HASH, Tether4Key, Tether4Value, 1024, TETHERING_GID)
355 
do_forward4_bottom(struct __sk_buff * skb,const int l2_header_size,void * data,const void * data_end,struct ethhdr * eth,struct iphdr * ip,const bool is_ethernet,const bool downstream,const bool updatetime,const bool is_tcp,const unsigned kver)356 static inline __always_inline int do_forward4_bottom(struct __sk_buff* skb,
357         const int l2_header_size, void* data, const void* data_end,
358         struct ethhdr* eth, struct iphdr* ip, const bool is_ethernet,
359         const bool downstream, const bool updatetime, const bool is_tcp,
360         const unsigned kver) {
361     struct tcphdr* tcph = is_tcp ? (void*)(ip + 1) : NULL;
362     struct udphdr* udph = is_tcp ? NULL : (void*)(ip + 1);
363 
364     if (is_tcp) {
365         // Make sure we can get at the tcp header
366         if (data + l2_header_size + sizeof(*ip) + sizeof(*tcph) > data_end)
367             TC_PUNT(SHORT_TCP_HEADER);
368 
369         // If hardware offload is running and programming flows based on conntrack entries, try not
370         // to interfere with it, so do not offload TCP packets with any one of the SYN/FIN/RST flags
371         if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCPV4_CONTROL_PACKET);
372     } else { // UDP
373         // Make sure we can get at the udp header
374         if (data + l2_header_size + sizeof(*ip) + sizeof(*udph) > data_end)
375             TC_PUNT(SHORT_UDP_HEADER);
376 
377         // Skip handling of CHECKSUM_COMPLETE packets with udp checksum zero due to need for
378         // additional updating of skb->csum (this could be fixed up manually with more effort).
379         //
380         // Note that the in-kernel implementation of 'int64_t bpf_csum_update(skb, u32 csum)' is:
381         //   if (skb->ip_summed == CHECKSUM_COMPLETE)
382         //     return (skb->csum = csum_add(skb->csum, csum));
383         //   else
384         //     return -ENOTSUPP;
385         //
386         // So this will punt any CHECKSUM_COMPLETE packet with a zero UDP checksum,
387         // and leave all other packets unaffected (since it just at most adds zero to skb->csum).
388         //
389         // In practice this should almost never trigger because most nics do not generate
390         // CHECKSUM_COMPLETE packets on receive - especially so for nics/drivers on a phone.
391         //
392         // Additionally since we're forwarding, in most cases the value of the skb->csum field
393         // shouldn't matter (it's not used by physical nic egress).
394         //
395         // It only matters if we're ingressing through a CHECKSUM_COMPLETE capable nic
396         // and egressing through a virtual interface looping back to the kernel itself
397         // (ie. something like veth) where the CHECKSUM_COMPLETE/skb->csum can get reused
398         // on ingress.
399         //
400         // If we were in the kernel we'd simply probably call
401         //   void skb_checksum_complete_unset(struct sk_buff *skb) {
402         //     if (skb->ip_summed == CHECKSUM_COMPLETE) skb->ip_summed = CHECKSUM_NONE;
403         //   }
404         // here instead.  Perhaps there should be a bpf helper for that?
405         if (!udph->check && (bpf_csum_update(skb, 0) >= 0)) TC_PUNT(UDP_CSUM_ZERO);
406     }
407 
408     Tether4Key k = {
409             .iif = skb->ifindex,
410             .l4Proto = ip->protocol,
411             .src4.s_addr = ip->saddr,
412             .dst4.s_addr = ip->daddr,
413             .srcPort = is_tcp ? tcph->source : udph->source,
414             .dstPort = is_tcp ? tcph->dest : udph->dest,
415     };
416     if (is_ethernet) __builtin_memcpy(k.dstMac, eth->h_dest, ETH_ALEN);
417 
418     Tether4Value* v = downstream ? bpf_tether_downstream4_map_lookup_elem(&k)
419                                  : bpf_tether_upstream4_map_lookup_elem(&k);
420 
421     // If we don't find any offload information then simply let the core stack handle it...
422     if (!v) return TC_ACT_PIPE;
423 
424     uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
425 
426     TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
427 
428     // If we don't have anywhere to put stats, then abort...
429     if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
430 
431     uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
432 
433     // If we don't have a limit, then abort...
434     if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
435 
436     // Required IPv4 minimum mtu is 68, below that not clear what we should do, abort...
437     if (v->pmtu < 68) TC_PUNT(BELOW_IPV4_MTU);
438 
439     // Approximate handling of TCP/IPv4 overhead for incoming LRO/GRO packets: default
440     // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
441     // undercount, which is still better then not accounting for this overhead at all.
442     // Note: this really shouldn't be device/path mtu at all, but rather should be
443     // derived from this particular connection's mss (ie. from gro segment size).
444     // This would require a much newer kernel with newer ebpf accessors.
445     // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
446     uint64_t packets = 1;
447     uint64_t L3_bytes = skb->len - l2_header_size;
448     if (L3_bytes > v->pmtu) {
449         const int tcp4_overhead = sizeof(struct iphdr) + sizeof(struct tcphdr) + 12;
450         const int mss = v->pmtu - tcp4_overhead;
451         const uint64_t payload = L3_bytes - tcp4_overhead;
452         packets = (payload + mss - 1) / mss;
453         L3_bytes = tcp4_overhead * packets + payload;
454     }
455 
456     // Are we past the limit?  If so, then abort...
457     // Note: will not overflow since u64 is 936 years even at 5Gbps.
458     // Do not drop here.  Offload is just that, whenever we fail to handle
459     // a packet we let the core stack deal with things.
460     // (The core stack needs to handle limits correctly anyway,
461     // since we don't offload all traffic in both directions)
462     if (stat_v->rxBytes + stat_v->txBytes + L3_bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
463 
464     if (!is_ethernet) {
465         // Try to inject an ethernet header, and simply return if we fail.
466         // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
467         // because this is easier and the kernel will strip extraneous ethernet header.
468         if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
469             __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
470             TC_PUNT(CHANGE_HEAD_FAILED);
471         }
472 
473         // bpf_skb_change_head() invalidates all pointers - reload them
474         data = (void*)(long)skb->data;
475         data_end = (void*)(long)skb->data_end;
476         eth = data;
477         ip = (void*)(eth + 1);
478         tcph = is_tcp ? (void*)(ip + 1) : NULL;
479         udph = is_tcp ? NULL : (void*)(ip + 1);
480 
481         // I do not believe this can ever happen, but keep the verifier happy...
482         if (data + sizeof(struct ethhdr) + sizeof(*ip) + (is_tcp ? sizeof(*tcph) : sizeof(*udph)) > data_end) {
483             __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
484             TC_DROP(TOO_SHORT);
485         }
486     };
487 
488     // At this point we always have an ethernet header - which will get stripped by the
489     // kernel during transmit through a rawip interface.  ie. 'eth' pointer is valid.
490     // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
491 
492     // Overwrite any mac header with the new one
493     // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
494     *eth = v->macHeader;
495 
496     // Decrement the IPv4 TTL, we already know it's greater than 1.
497     // u8 TTL field is followed by u8 protocol to make a u16 for ipv4 header checksum update.
498     // Since we're keeping the ipv4 checksum valid (which means the checksum of the entire
499     // ipv4 header remains 0), the overall checksum of the entire packet does not change.
500     const int sz2 = sizeof(__be16);
501     const __be16 old_ttl_proto = *(__be16 *)&ip->ttl;
502     const __be16 new_ttl_proto = old_ttl_proto - htons(0x0100);
503     bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_ttl_proto, new_ttl_proto, sz2);
504     bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(ttl), &new_ttl_proto, sz2, 0);
505 
506     const int l4_offs_csum = is_tcp ? ETH_IP4_TCP_OFFSET(check) : ETH_IP4_UDP_OFFSET(check);
507     const int sz4 = sizeof(__be32);
508     // UDP 0 is special and stored as FFFF (this flag also causes a csum of 0 to be unmodified)
509     const int l4_flags = is_tcp ? 0 : BPF_F_MARK_MANGLED_0;
510     const __be32 old_daddr = k.dst4.s_addr;
511     const __be32 old_saddr = k.src4.s_addr;
512     const __be32 new_daddr = v->dst46.s6_addr32[3];
513     const __be32 new_saddr = v->src46.s6_addr32[3];
514 
515     bpf_l4_csum_replace(skb, l4_offs_csum, old_daddr, new_daddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
516     bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_daddr, new_daddr, sz4);
517     bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(daddr), &new_daddr, sz4, 0);
518 
519     bpf_l4_csum_replace(skb, l4_offs_csum, old_saddr, new_saddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
520     bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_saddr, new_saddr, sz4);
521     bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(saddr), &new_saddr, sz4, 0);
522 
523     // The offsets for TCP and UDP ports: source (u16 @ L4 offset 0) & dest (u16 @ L4 offset 2) are
524     // actually the same, so the compiler should just optimize them both down to a constant.
525     bpf_l4_csum_replace(skb, l4_offs_csum, k.srcPort, v->srcPort, sz2 | l4_flags);
526     bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(source) : ETH_IP4_UDP_OFFSET(source),
527                         &v->srcPort, sz2, 0);
528 
529     bpf_l4_csum_replace(skb, l4_offs_csum, k.dstPort, v->dstPort, sz2 | l4_flags);
530     bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(dest) : ETH_IP4_UDP_OFFSET(dest),
531                         &v->dstPort, sz2, 0);
532 
533     // This requires the bpf_ktime_get_boot_ns() helper which was added in 5.8,
534     // and backported to all Android Common Kernel 4.14+ trees.
535     if (updatetime) v->last_used = bpf_ktime_get_boot_ns();
536 
537     __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
538     __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, L3_bytes);
539 
540     // Redirect to forwarded interface.
541     //
542     // Note that bpf_redirect() cannot fail unless you pass invalid flags.
543     // The redirect actually happens after the ebpf program has already terminated,
544     // and can fail for example for mtu reasons at that point in time, but there's nothing
545     // we can do about it here.
546     return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
547 }
548 
do_forward4(struct __sk_buff * skb,const bool is_ethernet,const bool downstream,const bool updatetime,const unsigned kver)549 static inline __always_inline int do_forward4(struct __sk_buff* skb, const bool is_ethernet,
550         const bool downstream, const bool updatetime, const unsigned kver) {
551     // Require ethernet dst mac address to be our unicast address.
552     if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
553 
554     // Must be meta-ethernet IPv4 frame
555     if (skb->protocol != htons(ETH_P_IP)) return TC_ACT_PIPE;
556 
557     const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
558 
559     // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
560     // not trigger and thus we need to manually make sure we can read packet headers via DPA.
561     // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
562     // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
563     try_make_writable(skb, l2_header_size + IP4_HLEN + TCP_HLEN);
564 
565     void* data = (void*)(long)skb->data;
566     const void* data_end = (void*)(long)skb->data_end;
567     struct ethhdr* eth = is_ethernet ? data : NULL;  // used iff is_ethernet
568     struct iphdr* ip = is_ethernet ? (void*)(eth + 1) : data;
569 
570     // Must have (ethernet and) ipv4 header
571     if (data + l2_header_size + sizeof(*ip) > data_end) return TC_ACT_PIPE;
572 
573     // Ethertype - if present - must be IPv4
574     if (is_ethernet && (eth->h_proto != htons(ETH_P_IP))) return TC_ACT_PIPE;
575 
576     // IP version must be 4
577     if (ip->version != 4) TC_PUNT(INVALID_IPV4_VERSION);
578 
579     // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
580     if (ip->ihl != 5) TC_PUNT(HAS_IP_OPTIONS);
581 
582     // Calculate the IPv4 one's complement checksum of the IPv4 header.
583     __wsum sum4 = 0;
584     for (int i = 0; i < sizeof(*ip) / sizeof(__u16); ++i) {
585         sum4 += ((__u16*)ip)[i];
586     }
587     // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4
588     sum4 = (sum4 & 0xFFFF) + (sum4 >> 16);  // collapse u32 into range 1 .. 0x1FFFE
589     sum4 = (sum4 & 0xFFFF) + (sum4 >> 16);  // collapse any potential carry into u16
590     // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
591     if (sum4 != 0xFFFF) TC_PUNT(CHECKSUM);
592 
593     // Minimum IPv4 total length is the size of the header
594     if (ntohs(ip->tot_len) < sizeof(*ip)) TC_PUNT(TRUNCATED_IPV4);
595 
596     // We are incapable of dealing with IPv4 fragments
597     if (ip->frag_off & ~htons(IP_DF)) TC_PUNT(IS_IP_FRAG);
598 
599     // Cannot decrement during forward if already zero or would be zero,
600     // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
601     if (ip->ttl <= 1) TC_PUNT(LOW_TTL);
602 
603     // If we cannot update the 'last_used' field due to lack of bpf_ktime_get_boot_ns() helper,
604     // then it is not safe to offload UDP due to the small conntrack timeouts, as such,
605     // in such a situation we can only support TCP.  This also has the added nice benefit of
606     // using a separate error counter, and thus making it obvious which version of the program
607     // is loaded.
608     if (!updatetime && ip->protocol != IPPROTO_TCP) TC_PUNT(NON_TCP);
609 
610     // We do not support offloading anything besides IPv4 TCP and UDP, due to need for NAT,
611     // but no need to check this if !updatetime due to check immediately above.
612     if (updatetime && (ip->protocol != IPPROTO_TCP) && (ip->protocol != IPPROTO_UDP))
613         TC_PUNT(NON_TCP_UDP);
614 
615     // We want to make sure that the compiler will, in the !updatetime case, entirely optimize
616     // out all the non-tcp logic.  Also note that at this point is_udp === !is_tcp.
617     const bool is_tcp = !updatetime || (ip->protocol == IPPROTO_TCP);
618 
619     // This is a bit of a hack to make things easier on the bpf verifier.
620     // (In particular I believe the Linux 4.14 kernel's verifier can get confused later on about
621     // what offsets into the packet are valid and can spuriously reject the program, this is
622     // because it fails to realize that is_tcp && !is_tcp is impossible)
623     //
624     // For both TCP & UDP we'll need to read and modify the src/dst ports, which so happen to
625     // always be in the first 4 bytes of the L4 header.  Additionally for UDP we'll need access
626     // to the checksum field which is in bytes 7 and 8.  While for TCP we'll need to read the
627     // TCP flags (at offset 13) and access to the checksum field (2 bytes at offset 16).
628     // As such we *always* need access to at least 8 bytes.
629     if (data + l2_header_size + sizeof(*ip) + 8 > data_end) TC_PUNT(SHORT_L4_HEADER);
630 
631     // We're forcing the compiler to emit two copies of the following code, optimized
632     // separately for is_tcp being true or false.  This simplifies the resulting bpf
633     // byte code sufficiently that the 4.14 bpf verifier is able to keep track of things.
634     // Without this (updatetime == true) case would fail to bpf verify on 4.14 even
635     // if the underlying requisite kernel support (bpf_ktime_get_boot_ns) was backported.
636     if (is_tcp) {
637       return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
638                                 is_ethernet, downstream, updatetime, /* is_tcp */ true, kver);
639     } else {
640       return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
641                                 is_ethernet, downstream, updatetime, /* is_tcp */ false, kver);
642     }
643 }
644 
645 // Full featured (required) implementations for 5.8+ kernels (these are S+ by definition)
646 
647 DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_rawip$5_8", TETHERING_UID, TETHERING_GID,
648                      sched_cls_tether_downstream4_rawip_5_8, KVER(5, 8, 0))
649 (struct __sk_buff* skb) {
650     return do_forward4(skb, RAWIP, DOWNSTREAM, UPDATETIME, KVER(5, 8, 0));
651 }
652 
653 DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_rawip$5_8", TETHERING_UID, TETHERING_GID,
654                      sched_cls_tether_upstream4_rawip_5_8, KVER(5, 8, 0))
655 (struct __sk_buff* skb) {
656     return do_forward4(skb, RAWIP, UPSTREAM, UPDATETIME, KVER(5, 8, 0));
657 }
658 
659 DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_ether$5_8", TETHERING_UID, TETHERING_GID,
660                      sched_cls_tether_downstream4_ether_5_8, KVER(5, 8, 0))
661 (struct __sk_buff* skb) {
662     return do_forward4(skb, ETHER, DOWNSTREAM, UPDATETIME, KVER(5, 8, 0));
663 }
664 
665 DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_ether$5_8", TETHERING_UID, TETHERING_GID,
666                      sched_cls_tether_upstream4_ether_5_8, KVER(5, 8, 0))
667 (struct __sk_buff* skb) {
668     return do_forward4(skb, ETHER, UPSTREAM, UPDATETIME, KVER(5, 8, 0));
669 }
670 
671 // Full featured (optional) implementations for 4.14-S, 4.19-S & 5.4-S kernels
672 // (optional, because we need to be able to fallback for 4.14/4.19/5.4 pre-S kernels)
673 
674 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$opt",
675                                     TETHERING_UID, TETHERING_GID,
676                                     sched_cls_tether_downstream4_rawip_opt,
677                                     KVER(4, 14, 0), KVER(5, 8, 0))
678 (struct __sk_buff* skb) {
679     return do_forward4(skb, RAWIP, DOWNSTREAM, UPDATETIME, KVER(4, 14, 0));
680 }
681 
682 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$opt",
683                                     TETHERING_UID, TETHERING_GID,
684                                     sched_cls_tether_upstream4_rawip_opt,
685                                     KVER(4, 14, 0), KVER(5, 8, 0))
686 (struct __sk_buff* skb) {
687     return do_forward4(skb, RAWIP, UPSTREAM, UPDATETIME, KVER(4, 14, 0));
688 }
689 
690 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$opt",
691                                     TETHERING_UID, TETHERING_GID,
692                                     sched_cls_tether_downstream4_ether_opt,
693                                     KVER(4, 14, 0), KVER(5, 8, 0))
694 (struct __sk_buff* skb) {
695     return do_forward4(skb, ETHER, DOWNSTREAM, UPDATETIME, KVER(4, 14, 0));
696 }
697 
698 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$opt",
699                                     TETHERING_UID, TETHERING_GID,
700                                     sched_cls_tether_upstream4_ether_opt,
701                                     KVER(4, 14, 0), KVER(5, 8, 0))
702 (struct __sk_buff* skb) {
703     return do_forward4(skb, ETHER, UPSTREAM, UPDATETIME, KVER(4, 14, 0));
704 }
705 
706 // Partial (TCP-only: will not update 'last_used' field) implementations for 4.14+ kernels.
707 // These will be loaded only if the above optional ones failed (loading of *these* must succeed
708 // for 5.4+, since that is always an R patched kernel).
709 //
710 // [Note: as a result TCP connections will not have their conntrack timeout refreshed, however,
711 // since /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established defaults to 432000 (seconds),
712 // this in practice means they'll break only after 5 days.  This seems an acceptable trade-off.
713 //
714 // Additionally kernel/tests change "net-test: add bpf_ktime_get_ns / bpf_ktime_get_boot_ns tests"
715 // which enforces and documents the required kernel cherrypicks will make it pretty unlikely that
716 // many devices upgrading to S will end up relying on these fallback programs.
717 
718 // RAWIP: Required for 5.4-R kernels -- which always support bpf_skb_change_head().
719 
720 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$5_4", TETHERING_UID, TETHERING_GID,
721                            sched_cls_tether_downstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
722 (struct __sk_buff* skb) {
723     return do_forward4(skb, RAWIP, DOWNSTREAM, NO_UPDATETIME, KVER(5, 4, 0));
724 }
725 
726 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$5_4", TETHERING_UID, TETHERING_GID,
727                            sched_cls_tether_upstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
728 (struct __sk_buff* skb) {
729     return do_forward4(skb, RAWIP, UPSTREAM, NO_UPDATETIME, KVER(5, 4, 0));
730 }
731 
732 // RAWIP: Optional for 4.14/4.19 (R) kernels -- which support bpf_skb_change_head().
733 // [Note: fallback for 4.14/4.19 (P/Q) kernels is below in stub section]
734 
735 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$4_14",
736                                     TETHERING_UID, TETHERING_GID,
737                                     sched_cls_tether_downstream4_rawip_4_14,
738                                     KVER(4, 14, 0), KVER(5, 4, 0))
739 (struct __sk_buff* skb) {
740     return do_forward4(skb, RAWIP, DOWNSTREAM, NO_UPDATETIME, KVER(4, 14, 0));
741 }
742 
743 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$4_14",
744                                     TETHERING_UID, TETHERING_GID,
745                                     sched_cls_tether_upstream4_rawip_4_14,
746                                     KVER(4, 14, 0), KVER(5, 4, 0))
747 (struct __sk_buff* skb) {
748     return do_forward4(skb, RAWIP, UPSTREAM, NO_UPDATETIME, KVER(4, 14, 0));
749 }
750 
751 // ETHER: Required for 4.14-Q/R, 4.19-Q/R & 5.4-R kernels.
752 
753 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$4_14", TETHERING_UID, TETHERING_GID,
754                            sched_cls_tether_downstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
755 (struct __sk_buff* skb) {
756     return do_forward4(skb, ETHER, DOWNSTREAM, NO_UPDATETIME, KVER(4, 14, 0));
757 }
758 
759 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$4_14", TETHERING_UID, TETHERING_GID,
760                            sched_cls_tether_upstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
761 (struct __sk_buff* skb) {
762     return do_forward4(skb, ETHER, UPSTREAM, NO_UPDATETIME, KVER(4, 14, 0));
763 }
764 
765 // Placeholder (no-op) implementations for older Q kernels
766 
767 // RAWIP: 4.9-P/Q, 4.14-P/Q & 4.19-Q kernels -- without bpf_skb_change_head() for tc programs
768 
769 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$stub", TETHERING_UID, TETHERING_GID,
770                            sched_cls_tether_downstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
771 (struct __sk_buff* skb) {
772     return TC_ACT_PIPE;
773 }
774 
775 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$stub", TETHERING_UID, TETHERING_GID,
776                            sched_cls_tether_upstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
777 (struct __sk_buff* skb) {
778     return TC_ACT_PIPE;
779 }
780 
781 // ETHER: 4.9-P/Q kernel
782 
783 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$stub", TETHERING_UID, TETHERING_GID,
784                            sched_cls_tether_downstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
785 (struct __sk_buff* skb) {
786     return TC_ACT_PIPE;
787 }
788 
789 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$stub", TETHERING_UID, TETHERING_GID,
790                            sched_cls_tether_upstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
791 (struct __sk_buff* skb) {
792     return TC_ACT_PIPE;
793 }
794 
795 // ----- XDP Support -----
796 
797 DEFINE_BPF_MAP_GRW(tether_dev_map, DEVMAP_HASH, uint32_t, uint32_t, 64, TETHERING_GID)
798 
do_xdp_forward6(struct xdp_md * ctx,const bool is_ethernet,const bool downstream)799 static inline __always_inline int do_xdp_forward6(struct xdp_md *ctx, const bool is_ethernet,
800         const bool downstream) {
801     return XDP_PASS;
802 }
803 
do_xdp_forward4(struct xdp_md * ctx,const bool is_ethernet,const bool downstream)804 static inline __always_inline int do_xdp_forward4(struct xdp_md *ctx, const bool is_ethernet,
805         const bool downstream) {
806     return XDP_PASS;
807 }
808 
do_xdp_forward_ether(struct xdp_md * ctx,const bool downstream)809 static inline __always_inline int do_xdp_forward_ether(struct xdp_md *ctx, const bool downstream) {
810     const void* data = (void*)(long)ctx->data;
811     const void* data_end = (void*)(long)ctx->data_end;
812     const struct ethhdr* eth = data;
813 
814     // Make sure we actually have an ethernet header
815     if ((void*)(eth + 1) > data_end) return XDP_PASS;
816 
817     if (eth->h_proto == htons(ETH_P_IPV6))
818         return do_xdp_forward6(ctx, ETHER, downstream);
819     if (eth->h_proto == htons(ETH_P_IP))
820         return do_xdp_forward4(ctx, ETHER, downstream);
821 
822     // Anything else we don't know how to handle...
823     return XDP_PASS;
824 }
825 
do_xdp_forward_rawip(struct xdp_md * ctx,const bool downstream)826 static inline __always_inline int do_xdp_forward_rawip(struct xdp_md *ctx, const bool downstream) {
827     const void* data = (void*)(long)ctx->data;
828     const void* data_end = (void*)(long)ctx->data_end;
829 
830     // The top nibble of both IPv4 and IPv6 headers is the IP version.
831     if (data_end - data < 1) return XDP_PASS;
832     const uint8_t v = (*(uint8_t*)data) >> 4;
833 
834     if (v == 6) return do_xdp_forward6(ctx, RAWIP, downstream);
835     if (v == 4) return do_xdp_forward4(ctx, RAWIP, downstream);
836 
837     // Anything else we don't know how to handle...
838     return XDP_PASS;
839 }
840 
841 #define DEFINE_XDP_PROG(str, func) \
842     DEFINE_BPF_PROG_KVER(str, TETHERING_UID, TETHERING_GID, func, KVER(5, 9, 0))(struct xdp_md *ctx)
843 
844 DEFINE_XDP_PROG("xdp/tether_downstream_ether",
845                  xdp_tether_downstream_ether) {
846     return do_xdp_forward_ether(ctx, DOWNSTREAM);
847 }
848 
849 DEFINE_XDP_PROG("xdp/tether_downstream_rawip",
850                  xdp_tether_downstream_rawip) {
851     return do_xdp_forward_rawip(ctx, DOWNSTREAM);
852 }
853 
854 DEFINE_XDP_PROG("xdp/tether_upstream_ether",
855                  xdp_tether_upstream_ether) {
856     return do_xdp_forward_ether(ctx, UPSTREAM);
857 }
858 
859 DEFINE_XDP_PROG("xdp/tether_upstream_rawip",
860                  xdp_tether_upstream_rawip) {
861     return do_xdp_forward_rawip(ctx, UPSTREAM);
862 }
863 
864 LICENSE("Apache 2.0");
865 CRITICAL("Connectivity (Tethering)");
866