-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsample_kern.c
77 lines (70 loc) · 2.06 KB
/
sample_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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
struct {
__uint(type, BPF_MAP_TYPE_XSKMAP);
__uint(max_entries, 128);
__type(key, int);
__type(value, int);
} xsks_map SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 4096);
__type(key, char[6]);
__type(value, int);
} mac_map SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 4096);
__type(key, char[6]);
__type(value, int);
} in_mac_map SEC(".maps");
inline int redirect_pkt_count_check(struct xdp_md *ctx) {
unsigned char* data_end = (unsigned char*) ((long) ctx->data_end);
unsigned char* data = (unsigned char*) ((long) ctx->data);
unsigned char* pos = data;
pos += 12;
if (pos > data_end) {
return 0;
}
int* cnt_ptr = bpf_map_lookup_elem(&in_mac_map, data + 6);
int cnt;
if (cnt_ptr == NULL) {
cnt = 1;
bpf_map_update_elem(&in_mac_map, data + 6, &cnt, 0);
return 0;
}
cnt = *cnt_ptr;
*cnt_ptr += 1;
if (cnt % 65536 == 0) {
return 0;
}
return 1;
}
inline int redirect_pkt_by_mac(struct xdp_md *ctx) {
unsigned char* data_end = (unsigned char*) ((long) ctx->data_end);
unsigned char* data = (unsigned char*) ((long) ctx->data);
unsigned char* pos = data;
pos += 6;
if (pos > data_end) {
return XDP_DROP;
}
int* output_iface_ptr = bpf_map_lookup_elem(&mac_map, data);
if (output_iface_ptr != NULL) {
int output_iface = *output_iface_ptr;
if (ctx->ingress_ifindex == output_iface) {
return XDP_DROP;
}
if (redirect_pkt_count_check(ctx)) {
return bpf_redirect(output_iface, 0);
}
}
return XDP_DROP;
}
SEC("xdp") int xdp_sock(struct xdp_md *ctx)
{
int redirect_result = redirect_pkt_by_mac(ctx);
if (redirect_result != XDP_DROP) {
return redirect_result;
}
return bpf_redirect_map(&xsks_map, ctx->rx_queue_index, XDP_DROP);
}