1 // SPDX-License-Identifier: GPL-2.0
3 /* This logic is lifted from a real-world use case of packet parsing, used in
4 * the open source library katran, a layer 4 load balancer.
6 * This test demonstrates how to parse packet contents using dynptrs. The
7 * original code (parsing without dynptrs) can be found in test_parse_tcp_hdr_opt.c
10 #include <linux/bpf.h>
11 #include <bpf/bpf_helpers.h>
12 #include <linux/tcp.h>
14 #include <linux/ipv6.h>
15 #include <linux/if_ether.h>
16 #include "test_tcp_hdr_options.h"
17 #include "bpf_kfuncs.h"
19 char _license[] SEC("license") = "GPL";
21 /* Kind number used for experiments */
22 const __u32 tcp_hdr_opt_kind_tpr = 0xFD;
23 /* Length of the tcp header option */
24 const __u32 tcp_hdr_opt_len_tpr = 6;
25 /* maximum number of header options to check to lookup server_id */
26 const __u32 tcp_hdr_opt_max_opt_checks = 15;
30 static int parse_hdr_opt(struct bpf_dynptr *ptr, __u32 *off, __u8 *hdr_bytes_remaining,
34 __u8 buffer[sizeof(kind) + sizeof(hdr_len) + sizeof(*server_id)];
37 __builtin_memset(buffer, 0, sizeof(buffer));
39 data = bpf_dynptr_slice(ptr, *off, buffer, sizeof(buffer));
45 if (kind == TCPOPT_EOL)
48 if (kind == TCPOPT_NOP) {
50 *hdr_bytes_remaining -= 1;
54 if (*hdr_bytes_remaining < 2)
58 if (hdr_len > *hdr_bytes_remaining)
61 if (kind == tcp_hdr_opt_kind_tpr) {
62 if (hdr_len != tcp_hdr_opt_len_tpr)
65 __builtin_memcpy(server_id, (__u32 *)(data + 2), sizeof(*server_id));
70 *hdr_bytes_remaining -= hdr_len;
75 int xdp_ingress_v6(struct xdp_md *xdp)
77 __u8 buffer[sizeof(struct tcphdr)] = {};
78 __u8 hdr_bytes_remaining;
79 struct tcphdr *tcp_hdr;
84 struct bpf_dynptr ptr;
86 bpf_dynptr_from_xdp(xdp, 0, &ptr);
88 off = sizeof(struct ethhdr) + sizeof(struct ipv6hdr);
90 tcp_hdr = bpf_dynptr_slice(&ptr, off, buffer, sizeof(buffer));
94 tcp_hdr_opt_len = (tcp_hdr->doff * 4) - sizeof(struct tcphdr);
95 if (tcp_hdr_opt_len < tcp_hdr_opt_len_tpr)
98 hdr_bytes_remaining = tcp_hdr_opt_len;
100 off += sizeof(struct tcphdr);
102 /* max number of bytes of options in tcp header is 40 bytes */
103 for (int i = 0; i < tcp_hdr_opt_max_opt_checks; i++) {
104 err = parse_hdr_opt(&ptr, &off, &hdr_bytes_remaining, &server_id);
106 if (err || !hdr_bytes_remaining)