1 // SPDX-License-Identifier: GPL-2.0
2 #include <error.h>
3 #include <errno.h>
4 #include <getopt.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <bpf/bpf.h>
12 #include <bpf/libbpf.h>
13 
14 #include "bpf_rlimit.h"
15 #include "flow_dissector_load.h"
16 
17 const char *cfg_pin_path = "/sys/fs/bpf/flow_dissector";
18 const char *cfg_map_name = "jmp_table";
19 bool cfg_attach = true;
20 char *cfg_prog_name;
21 char *cfg_path_name;
22 
23 static void load_and_attach_program(void)
24 {
25 	int prog_fd, ret;
26 	struct bpf_object *obj;
27 
28 	ret = libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
29 	if (ret)
30 		error(1, 0, "failed to enable libbpf strict mode: %d", ret);
31 
32 	ret = bpf_flow_load(&obj, cfg_path_name, cfg_prog_name,
33 			    cfg_map_name, NULL, &prog_fd, NULL);
34 	if (ret)
35 		error(1, 0, "bpf_flow_load %s", cfg_path_name);
36 
37 	ret = bpf_prog_attach(prog_fd, 0 /* Ignore */, BPF_FLOW_DISSECTOR, 0);
38 	if (ret)
39 		error(1, 0, "bpf_prog_attach %s", cfg_path_name);
40 
41 	ret = bpf_object__pin(obj, cfg_pin_path);
42 	if (ret)
43 		error(1, 0, "bpf_object__pin %s", cfg_pin_path);
44 }
45 
46 static void detach_program(void)
47 {
48 	char command[64];
49 	int ret;
50 
51 	ret = bpf_prog_detach(0, BPF_FLOW_DISSECTOR);
52 	if (ret)
53 		error(1, 0, "bpf_prog_detach");
54 
55 	/* To unpin, it is necessary and sufficient to just remove this dir */
56 	sprintf(command, "rm -r %s", cfg_pin_path);
57 	ret = system(command);
58 	if (ret)
59 		error(1, errno, "%s", command);
60 }
61 
62 static void parse_opts(int argc, char **argv)
63 {
64 	bool attach = false;
65 	bool detach = false;
66 	int c;
67 
68 	while ((c = getopt(argc, argv, "adp:s:")) != -1) {
69 		switch (c) {
70 		case 'a':
71 			if (detach)
72 				error(1, 0, "attach/detach are exclusive");
73 			attach = true;
74 			break;
75 		case 'd':
76 			if (attach)
77 				error(1, 0, "attach/detach are exclusive");
78 			detach = true;
79 			break;
80 		case 'p':
81 			if (cfg_path_name)
82 				error(1, 0, "only one path can be given");
83 
84 			cfg_path_name = optarg;
85 			break;
86 		case 's':
87 			if (cfg_prog_name)
88 				error(1, 0, "only one prog can be given");
89 
90 			cfg_prog_name = optarg;
91 			break;
92 		}
93 	}
94 
95 	if (detach)
96 		cfg_attach = false;
97 
98 	if (cfg_attach && !cfg_path_name)
99 		error(1, 0, "must provide a path to the BPF program");
100 
101 	if (cfg_attach && !cfg_prog_name)
102 		error(1, 0, "must provide a section name");
103 }
104 
105 int main(int argc, char **argv)
106 {
107 	parse_opts(argc, argv);
108 	if (cfg_attach)
109 		load_and_attach_program();
110 	else
111 		detach_program();
112 	return 0;
113 }
114