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