1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2
3 /*
4 * Copyright (c) 2021 Hengqi Chen
5 *
6 * Based on bindsnoop(8) from BCC by Pavel Dubovitsky.
7 * 11-May-2021 Hengqi Chen Created this.
8 */
9 #include <argp.h>
10 #include <arpa/inet.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include <string.h>
14 #include <sys/socket.h>
15 #include <time.h>
16
17 #include <bpf/libbpf.h>
18 #include <bpf/bpf.h>
19 #include "bindsnoop.h"
20 #include "bindsnoop.skel.h"
21 #include "trace_helpers.h"
22
23 #define PERF_BUFFER_PAGES 16
24 #define PERF_POLL_TIMEOUT_MS 100
25 #define warn(...) fprintf(stderr, __VA_ARGS__)
26
27 static volatile sig_atomic_t exiting = 0;
28
29 static bool emit_timestamp = false;
30 static pid_t target_pid = 0;
31 static bool ignore_errors = true;
32 static char *target_ports = NULL;
33 static bool verbose = false;
34
35 const char *argp_program_version = "bindsnoop 0.1";
36 const char *argp_program_bug_address =
37 "https://github.com/iovisor/bcc/tree/master/libbpf-tools";
38 const char argp_program_doc[] =
39 "Trace bind syscalls.\n"
40 "\n"
41 "USAGE: bindsnoop [-h] [-t] [-x] [-p PID] [-P ports]\n"
42 "\n"
43 "EXAMPLES:\n"
44 " bindsnoop # trace all bind syscall\n"
45 " bindsnoop -t # include timestamps\n"
46 " bindsnoop -x # include errors on output\n"
47 " bindsnoop -p 1216 # only trace PID 1216\n"
48 " bindsnoop -P 80,81 # only trace port 80 and 81\n"
49 "\n"
50 "Socket options are reported as:\n"
51 " SOL_IP IP_FREEBIND F....\n"
52 " SOL_IP IP_TRANSPARENT .T...\n"
53 " SOL_IP IP_BIND_ADDRESS_NO_PORT ..N..\n"
54 " SOL_SOCKET SO_REUSEADDR ...R.\n"
55 " SOL_SOCKET SO_REUSEPORT ....r\n";
56
57 static const struct argp_option opts[] = {
58 { "timestamp", 't', NULL, 0, "Include timestamp on output" },
59 { "failed", 'x', NULL, 0, "Include errors on output." },
60 { "pid", 'p', "PID", 0, "Process ID to trace" },
61 { "ports", 'P', "PORTS", 0, "Comma-separated list of ports to trace." },
62 { "verbose", 'v', NULL, 0, "Verbose debug output" },
63 { NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
64 {},
65 };
66
parse_arg(int key,char * arg,struct argp_state * state)67 static error_t parse_arg(int key, char *arg, struct argp_state *state)
68 {
69 long pid, port_num;
70 char *port;
71
72 switch (key) {
73 case 'p':
74 errno = 0;
75 pid = strtol(arg, NULL, 10);
76 if (errno || pid <= 0) {
77 warn("Invalid PID: %s\n", arg);
78 argp_usage(state);
79 }
80 target_pid = pid;
81 break;
82 case 'P':
83 if (!arg) {
84 warn("No ports specified\n");
85 argp_usage(state);
86 }
87 target_ports = strdup(arg);
88 port = strtok(arg, ",");
89 while (port) {
90 port_num = strtol(port, NULL, 10);
91 if (errno || port_num <= 0 || port_num > 65536) {
92 warn("Invalid ports: %s\n", arg);
93 argp_usage(state);
94 }
95 port = strtok(NULL, ",");
96 }
97 break;
98 case 'x':
99 ignore_errors = false;
100 break;
101 case 't':
102 emit_timestamp = true;
103 break;
104 case 'v':
105 verbose = true;
106 break;
107 case 'h':
108 argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
109 break;
110 default:
111 return ARGP_ERR_UNKNOWN;
112 }
113 return 0;
114 }
115
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)116 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
117 {
118 if (level == LIBBPF_DEBUG && !verbose)
119 return 0;
120 return vfprintf(stderr, format, args);
121 }
122
sig_int(int signo)123 static void sig_int(int signo)
124 {
125 exiting = 1;
126 }
127
handle_event(void * ctx,int cpu,void * data,__u32 data_sz)128 static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
129 {
130 struct bind_event *e = data;
131 time_t t;
132 struct tm *tm;
133 char ts[32], addr[48];
134 char opts[] = {'F', 'T', 'N', 'R', 'r', '\0'};
135 const char *proto;
136 int i = 0;
137
138 if (emit_timestamp) {
139 time(&t);
140 tm = localtime(&t);
141 strftime(ts, sizeof(ts), "%H:%M:%S", tm);
142 printf("%8s ", ts);
143 }
144 if (e->proto == IPPROTO_TCP)
145 proto = "TCP";
146 else if (e->proto == IPPROTO_UDP)
147 proto = "UDP";
148 else
149 proto = "UNK";
150 while (opts[i]) {
151 if (!((1 << i) & e->opts)) {
152 opts[i] = '.';
153 }
154 i++;
155 }
156 if (e->ver == 4) {
157 inet_ntop(AF_INET, &e->addr, addr, sizeof(addr));
158 } else {
159 inet_ntop(AF_INET6, &e->addr, addr, sizeof(addr));
160 }
161 printf("%-7d %-16s %-3d %-5s %-5s %-4d %-5d %-48s\n",
162 e->pid, e->task, e->ret, proto, opts, e->bound_dev_if, e->port, addr);
163 }
164
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)165 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
166 {
167 warn("lost %llu events on CPU #%d\n", lost_cnt, cpu);
168 }
169
main(int argc,char ** argv)170 int main(int argc, char **argv)
171 {
172 static const struct argp argp = {
173 .options = opts,
174 .parser = parse_arg,
175 .doc = argp_program_doc,
176 };
177 struct perf_buffer *pb = NULL;
178 struct bindsnoop_bpf *obj;
179 int err, port_map_fd;
180 char *port;
181 short port_num;
182
183 err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
184 if (err)
185 return err;
186
187 libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
188 libbpf_set_print(libbpf_print_fn);
189
190 obj = bindsnoop_bpf__open();
191 if (!obj) {
192 warn("failed to open BPF object\n");
193 return 1;
194 }
195
196 obj->rodata->target_pid = target_pid;
197 obj->rodata->ignore_errors = ignore_errors;
198 obj->rodata->filter_by_port = target_ports != NULL;
199
200 err = bindsnoop_bpf__load(obj);
201 if (err) {
202 warn("failed to load BPF object: %d\n", err);
203 goto cleanup;
204 }
205
206 if (target_ports) {
207 port_map_fd = bpf_map__fd(obj->maps.ports);
208 port = strtok(target_ports, ",");
209 while (port) {
210 port_num = strtol(port, NULL, 10);
211 bpf_map_update_elem(port_map_fd, &port_num, &port_num, BPF_ANY);
212 port = strtok(NULL, ",");
213 }
214 }
215
216 err = bindsnoop_bpf__attach(obj);
217 if (err) {
218 warn("failed to attach BPF programs: %d\n", err);
219 goto cleanup;
220 }
221
222 pb = perf_buffer__new(bpf_map__fd(obj->maps.events), PERF_BUFFER_PAGES,
223 handle_event, handle_lost_events, NULL, NULL);
224 if (!pb) {
225 err = -errno;
226 warn("failed to open perf buffer: %d\n", err);
227 goto cleanup;
228 }
229
230 if (signal(SIGINT, sig_int) == SIG_ERR) {
231 warn("can't set signal handler: %s\n", strerror(errno));
232 err = 1;
233 goto cleanup;
234 }
235
236 if (emit_timestamp)
237 printf("%-8s ", "TIME(s)");
238 printf("%-7s %-16s %-3s %-5s %-5s %-4s %-5s %-48s\n",
239 "PID", "COMM", "RET", "PROTO", "OPTS", "IF", "PORT", "ADDR");
240
241 while (!exiting) {
242 err = perf_buffer__poll(pb, PERF_POLL_TIMEOUT_MS);
243 if (err < 0 && err != -EINTR) {
244 warn("error polling perf buffer: %s\n", strerror(-err));
245 goto cleanup;
246 }
247 /* reset err to return 0 if exiting */
248 err = 0;
249 }
250
251 cleanup:
252 perf_buffer__free(pb);
253 bindsnoop_bpf__destroy(obj);
254
255 return err != 0;
256 }
257