1 /* eBPF mini library */
4 #include <linux/unistd.h>
7 #include <linux/netlink.h>
10 #include <net/ethernet.h>
12 #include <linux/if_packet.h>
13 #include <arpa/inet.h>
16 static __u64
ptr_to_u64(void *ptr
)
18 return (__u64
) (unsigned long) ptr
;
21 int bpf_create_map(enum bpf_map_type map_type
, int key_size
, int value_size
,
24 union bpf_attr attr
= {
27 .value_size
= value_size
,
28 .max_entries
= max_entries
31 return syscall(__NR_bpf
, BPF_MAP_CREATE
, &attr
, sizeof(attr
));
34 int bpf_update_elem(int fd
, void *key
, void *value
, unsigned long long flags
)
36 union bpf_attr attr
= {
38 .key
= ptr_to_u64(key
),
39 .value
= ptr_to_u64(value
),
43 return syscall(__NR_bpf
, BPF_MAP_UPDATE_ELEM
, &attr
, sizeof(attr
));
46 int bpf_lookup_elem(int fd
, void *key
, void *value
)
48 union bpf_attr attr
= {
50 .key
= ptr_to_u64(key
),
51 .value
= ptr_to_u64(value
),
54 return syscall(__NR_bpf
, BPF_MAP_LOOKUP_ELEM
, &attr
, sizeof(attr
));
57 int bpf_delete_elem(int fd
, void *key
)
59 union bpf_attr attr
= {
61 .key
= ptr_to_u64(key
),
64 return syscall(__NR_bpf
, BPF_MAP_DELETE_ELEM
, &attr
, sizeof(attr
));
67 int bpf_get_next_key(int fd
, void *key
, void *next_key
)
69 union bpf_attr attr
= {
71 .key
= ptr_to_u64(key
),
72 .next_key
= ptr_to_u64(next_key
),
75 return syscall(__NR_bpf
, BPF_MAP_GET_NEXT_KEY
, &attr
, sizeof(attr
));
78 #define ROUND_UP(x, n) (((x) + (n) - 1u) & ~((n) - 1u))
80 char bpf_log_buf
[LOG_BUF_SIZE
];
82 int bpf_prog_load(enum bpf_prog_type prog_type
,
83 const struct bpf_insn
*insns
, int prog_len
,
86 union bpf_attr attr
= {
87 .prog_type
= prog_type
,
88 .insns
= ptr_to_u64((void *) insns
),
89 .insn_cnt
= prog_len
/ sizeof(struct bpf_insn
),
90 .license
= ptr_to_u64((void *) license
),
91 .log_buf
= ptr_to_u64(bpf_log_buf
),
92 .log_size
= LOG_BUF_SIZE
,
98 return syscall(__NR_bpf
, BPF_PROG_LOAD
, &attr
, sizeof(attr
));
101 int open_raw_sock(const char *name
)
103 struct sockaddr_ll sll
;
106 sock
= socket(PF_PACKET
, SOCK_RAW
| SOCK_NONBLOCK
| SOCK_CLOEXEC
, htons(ETH_P_ALL
));
108 printf("cannot create raw socket\n");
112 memset(&sll
, 0, sizeof(sll
));
113 sll
.sll_family
= AF_PACKET
;
114 sll
.sll_ifindex
= if_nametoindex(name
);
115 sll
.sll_protocol
= htons(ETH_P_ALL
);
116 if (bind(sock
, (struct sockaddr
*)&sll
, sizeof(sll
)) < 0) {
117 printf("bind to %s: %s\n", name
, strerror(errno
));