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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
#include <signal.h>
#include <unistd.h>
#include "tc.skel.h"
// 环回设备的接口索引
#define LO_IFINDEX 1
// 标记程序是否收到退出信号
static volatile sig_atomic_t exiting = 0;
// 信号处理回调函数
static void sig_int(int signo)
{
exiting = 1;
}
// libbp日志打印回调函数
static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
{
return vfprintf(stderr, format, args);
}
int main(int argc, char **argv)
{
// 描述定义了名为tc_hook的TC挂载点,其网络接口索引为LO_IFINDEX,挂载点为入方向
DECLARE_LIBBPF_OPTS(bpf_tc_hook, tc_hook, .ifindex = LO_IFINDEX, .attach_point = BPF_TC_INGRESS);
// 描述定义了名为tc_opts的附加选项,设置了TC过滤器的句柄标识符为1、优先级为1
DECLARE_LIBBPF_OPTS(bpf_tc_opts, tc_opts, .handle = 1, .priority = 1);
bool hook_created = false;
struct tc_bpf *skel;
int err;
// 设置libbp日志打印的回调函数
libbpf_set_print(libbpf_print_fn);
// 打开并加载eBPF程序
skel = tc_bpf__open_and_load();
if (!skel) {
fprintf(stderr, "Failed to open BPF skeleton\n");
return 1;
}
// 创建TC钩子,即创建qdisc
err = bpf_tc_hook_create(&tc_hook);
if (!err)
hook_created = true;
if (err && err != -EEXIST) {
fprintf(stderr, "Failed to create TC hook: %d\n", err);
goto cleanup;
}
// 获取eBPF程序tc_ingress的文件描述符,并赋值到tc_opts结构体中
tc_opts.prog_fd = bpf_program__fd(skel->progs.tc_ingress);
// 根据tc_opts,将eBPF程序tc_ingress附加到名为tc_hook的TC钩子上
err = bpf_tc_attach(&tc_hook, &tc_opts);
if (err) {
fprintf(stderr, "Failed to attach TC: %d\n", err);
goto cleanup;
}
// 设置SIGINT信号处理
if (signal(SIGINT, sig_int) == SIG_ERR) {
err = errno;
fprintf(stderr, "Can't set signal handler: %s\n", strerror(errno));
goto cleanup;
}
printf("Successfully started! Please run `sudo cat /sys/kernel/debug/tracing/trace_pipe` "
"to see output of the BPF program.\n");
// 主循环
while (!exiting) {
fprintf(stderr, ".");
sleep(1);
}
// 清空tc_opts中的字段
tc_opts.flags = tc_opts.prog_fd = tc_opts.prog_id = 0;
// 将eBPF程序从TC钩子上卸载掉
err = bpf_tc_detach(&tc_hook, &tc_opts);
if (err) {
fprintf(stderr, "Failed to detach TC: %d\n", err);
goto cleanup;
}
cleanup:
// 清楚之前创建的TC钩子
if (hook_created)
bpf_tc_hook_destroy(&tc_hook);
// 清理eBPF环境
tc_bpf__destroy(skel);
return -err;
}
|