-
Notifications
You must be signed in to change notification settings - Fork 54
/
xdp_lb_kern.c
56 lines (42 loc) · 1.25 KB
/
xdp_lb_kern.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "xdp_lb_kern.h"
#define IP_ADDRESS(x) (unsigned int)(172 + (17 << 8) + (0 << 16) + (x << 24))
#define BACKEND_A 2
#define BACKEND_B 3
#define CLIENT 4
#define LB 5
SEC("xdp_lb")
int xdp_load_balancer(struct xdp_md *ctx)
{
void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;
bpf_printk("got something");
struct ethhdr *eth = data;
if (data + sizeof(struct ethhdr) > data_end)
return XDP_ABORTED;
if (bpf_ntohs(eth->h_proto) != ETH_P_IP)
return XDP_PASS;
struct iphdr *iph = data + sizeof(struct ethhdr);
if (data + sizeof(struct ethhdr) + sizeof(struct iphdr) > data_end)
return XDP_ABORTED;
if (iph->protocol != IPPROTO_TCP)
return XDP_PASS;
bpf_printk("Got TCP packet from %x", iph->saddr);
if (iph->saddr == IP_ADDRESS(CLIENT))
{
char be = BACKEND_A;
if (bpf_ktime_get_ns() % 2)
be = BACKEND_B;
iph->daddr = IP_ADDRESS(be);
eth->h_dest[5] = be;
}
else
{
iph->daddr = IP_ADDRESS(CLIENT);
eth->h_dest[5] = CLIENT;
}
iph->saddr = IP_ADDRESS(LB);
eth->h_source[5] = LB;
iph->check = iph_csum(iph);
return XDP_TX;
}
char _license[] SEC("license") = "GPL";