samples/bpf/tc_l2_redirect_kern.c

Source file repositories/reference/linux-study-clean/samples/bpf/tc_l2_redirect_kern.c

File Facts

System
Linux kernel
Corpus path
samples/bpf/tc_l2_redirect_kern.c
Extension
.c
Size
6052 bytes
Lines
232
Domain
Support Tooling And Documentation
Bucket
samples
Inferred role
Support Tooling And Documentation: implementation source
Status
source implementation candidate

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

struct bpf_elf_map {
	__u32 type;
	__u32 size_key;
	__u32 size_value;
	__u32 max_elem;
	__u32 flags;
	__u32 id;
	__u32 pinning;
};

/* copy of 'struct ethhdr' without __packed */
struct eth_hdr {
	unsigned char   h_dest[ETH_ALEN];
	unsigned char   h_source[ETH_ALEN];
	unsigned short  h_proto;
};

struct bpf_elf_map SEC("maps") tun_iface = {
	.type = BPF_MAP_TYPE_ARRAY,
	.size_key = sizeof(int),
	.size_value = sizeof(int),
	.pinning = PIN_GLOBAL_NS,
	.max_elem = 1,
};

static __always_inline bool is_vip_addr(__be16 eth_proto, __be32 daddr)
{
	if (eth_proto == htons(ETH_P_IP))
		return (_htonl(0xffffff00) & daddr) == _htonl(0x0a0a0100);
	else if (eth_proto == htons(ETH_P_IPV6))
		return (daddr == _htonl(0x2401face));

	return false;
}

SEC("l2_to_iptun_ingress_forward")
int _l2_to_iptun_ingress_forward(struct __sk_buff *skb)
{
	void *data = (void *)(long)skb->data;
	struct eth_hdr *eth = data;
	void *data_end = (void *)(long)skb->data_end;
	int key = 0, *ifindex;

	if (data + sizeof(*eth) > data_end)
		return TC_ACT_OK;

	ifindex = bpf_map_lookup_elem(&tun_iface, &key);
	if (!ifindex)
		return TC_ACT_OK;

	if (eth->h_proto == htons(ETH_P_IP)) {
		char fmt4[] = "ingress forward to ifindex:%d daddr4:%x\n";
		struct iphdr *iph = data + sizeof(*eth);

		if (data + sizeof(*eth) + sizeof(*iph) > data_end)
			return TC_ACT_OK;

		if (iph->protocol != IPPROTO_IPIP)
			return TC_ACT_OK;

		bpf_trace_printk(fmt4, sizeof(fmt4), *ifindex,
				 _htonl(iph->daddr));
		return bpf_redirect(*ifindex, BPF_F_INGRESS);
	} else if (eth->h_proto == htons(ETH_P_IPV6)) {
		char fmt6[] = "ingress forward to ifindex:%d daddr6:%x::%x\n";
		struct ipv6hdr *ip6h = data + sizeof(*eth);

		if (data + sizeof(*eth) + sizeof(*ip6h) > data_end)
			return TC_ACT_OK;

		if (ip6h->nexthdr != IPPROTO_IPIP &&
		    ip6h->nexthdr != IPPROTO_IPV6)
			return TC_ACT_OK;

		bpf_trace_printk(fmt6, sizeof(fmt6), *ifindex,
				 _htonl(ip6h->daddr.s6_addr32[0]),
				 _htonl(ip6h->daddr.s6_addr32[3]));
		return bpf_redirect(*ifindex, BPF_F_INGRESS);
	}

	return TC_ACT_OK;
}

SEC("l2_to_iptun_ingress_redirect")
int _l2_to_iptun_ingress_redirect(struct __sk_buff *skb)
{
	struct bpf_tunnel_key tkey = {};
	void *data = (void *)(long)skb->data;
	struct eth_hdr *eth = data;
	void *data_end = (void *)(long)skb->data_end;

Annotation

Implementation Notes