xref: /aosp_15_r20/external/bcc/libbpf-tools/tcptracer.c (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2022 Microsoft Corporation
3 //
4 // Based on tcptracer(8) from BCC by Kinvolk GmbH and
5 // tcpconnect(8) by Anton Protopopov
6 #include <sys/resource.h>
7 #include <arpa/inet.h>
8 #include <argp.h>
9 #include <signal.h>
10 #include <limits.h>
11 #include <unistd.h>
12 #include <time.h>
13 #include <bpf/bpf.h>
14 #include "tcptracer.h"
15 #include "tcptracer.skel.h"
16 #include "btf_helpers.h"
17 #include "trace_helpers.h"
18 #include "map_helpers.h"
19 
20 #define warn(...) fprintf(stderr, __VA_ARGS__)
21 
22 static volatile sig_atomic_t exiting = 0;
23 
24 const char *argp_program_version = "tcptracer 0.1";
25 const char *argp_program_bug_address =
26 	"https://github.com/iovisor/bcc/tree/master/libbpf-tools";
27 static const char argp_program_doc[] =
28 	"\ntcptracer: Trace TCP connections\n"
29 	"\n"
30 	"EXAMPLES:\n"
31 	"    tcptracer             # trace all TCP connections\n"
32 	"    tcptracer -t          # include timestamps\n"
33 	"    tcptracer -p 181      # only trace PID 181\n"
34 	"    tcptracer -U          # include UID\n"
35 	"    tcptracer -u 1000     # only trace UID 1000\n"
36 	"    tcptracer --C mappath # only trace cgroups in the map\n"
37 	"    tcptracer --M mappath # only trace mount namespaces in the map\n"
38 	;
39 
get_int(const char * arg,int * ret,int min,int max)40 static int get_int(const char *arg, int *ret, int min, int max)
41 {
42 	char *end;
43 	long val;
44 
45 	errno = 0;
46 	val = strtol(arg, &end, 10);
47 	if (errno) {
48 		warn("strtol: %s: %s\n", arg, strerror(errno));
49 		return -1;
50 	} else if (end == arg || val < min || val > max) {
51 		return -1;
52 	}
53 	if (ret)
54 		*ret = val;
55 	return 0;
56 }
57 
get_uint(const char * arg,unsigned int * ret,unsigned int min,unsigned int max)58 static int get_uint(const char *arg, unsigned int *ret,
59 		    unsigned int min, unsigned int max)
60 {
61 	char *end;
62 	long val;
63 
64 	errno = 0;
65 	val = strtoul(arg, &end, 10);
66 	if (errno) {
67 		warn("strtoul: %s: %s\n", arg, strerror(errno));
68 		return -1;
69 	} else if (end == arg || val < min || val > max) {
70 		return -1;
71 	}
72 	if (ret)
73 		*ret = val;
74 	return 0;
75 }
76 
77 static const struct argp_option opts[] = {
78 	{ "verbose", 'v', NULL, 0, "Verbose debug output" },
79 	{ "timestamp", 't', NULL, 0, "Include timestamp on output" },
80 	{ "print-uid", 'U', NULL, 0, "Include UID on output" },
81 	{ "pid", 'p', "PID", 0, "Process PID to trace" },
82 	{ "uid", 'u', "UID", 0, "Process UID to trace" },
83 	{ "cgroupmap", 'C', "PATH", 0, "trace cgroups in this map" },
84 	{ "mntnsmap", 'M', "PATH", 0, "trace mount namespaces in this map" },
85 	{ NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
86 	{},
87 };
88 
89 static struct env {
90 	bool verbose;
91 	bool count;
92 	bool print_timestamp;
93 	bool print_uid;
94 	pid_t pid;
95 	uid_t uid;
96 } env = {
97 	.uid = (uid_t) -1,
98 };
99 
parse_arg(int key,char * arg,struct argp_state * state)100 static error_t parse_arg(int key, char *arg, struct argp_state *state)
101 {
102 	int err;
103 
104 	switch (key) {
105 	case 'h':
106 		argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
107 		break;
108 	case 'v':
109 		env.verbose = true;
110 		break;
111 	case 'c':
112 		env.count = true;
113 		break;
114 	case 't':
115 		env.print_timestamp = true;
116 		break;
117 	case 'U':
118 		env.print_uid = true;
119 		break;
120 	case 'p':
121 		err = get_int(arg, &env.pid, 1, INT_MAX);
122 		if (err) {
123 			warn("invalid PID: %s\n", arg);
124 			argp_usage(state);
125 		}
126 		break;
127 	case 'u':
128 		err = get_uint(arg, &env.uid, 0, (uid_t) -2);
129 		if (err) {
130 			warn("invalid UID: %s\n", arg);
131 			argp_usage(state);
132 		}
133 		break;
134 	case 'C':
135 		warn("not implemented: --cgroupmap");
136 		break;
137 	case 'M':
138 		warn("not implemented: --mntnsmap");
139 		break;
140 	default:
141 		return ARGP_ERR_UNKNOWN;
142 	}
143 	return 0;
144 }
145 
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)146 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
147 {
148 	if (level == LIBBPF_DEBUG && !env.verbose)
149 		return 0;
150 	return vfprintf(stderr, format, args);
151 }
152 
sig_int(int signo)153 static void sig_int(int signo)
154 {
155 	exiting = 1;
156 }
157 
print_events_header()158 static void print_events_header()
159 {
160 	if (env.print_timestamp)
161 		printf("%-9s", "TIME(s)");
162 	if (env.print_uid)
163 		printf("%-6s", "UID");
164 	printf("%s %-6s %-12s %-2s %-16s %-16s %-4s %-4s\n",
165 	       "T", "PID", "COMM", "IP", "SADDR", "DADDR", "SPORT", "DPORT");
166 }
167 
handle_event(void * ctx,int cpu,void * data,__u32 data_sz)168 static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
169 {
170 	const struct event *event = data;
171 	char src[INET6_ADDRSTRLEN];
172 	char dst[INET6_ADDRSTRLEN];
173 	union {
174 		struct in_addr  x4;
175 		struct in6_addr x6;
176 	} s, d;
177 	static __u64 start_ts;
178 
179 	if (event->af == AF_INET) {
180 		s.x4.s_addr = event->saddr_v4;
181 		d.x4.s_addr = event->daddr_v4;
182 	} else if (event->af == AF_INET6) {
183 		memcpy(&s.x6.s6_addr, &event->saddr_v6, sizeof(s.x6.s6_addr));
184 		memcpy(&d.x6.s6_addr, &event->daddr_v6, sizeof(d.x6.s6_addr));
185 	} else {
186 		warn("broken event: event->af=%d", event->af);
187 		return;
188 	}
189 
190 	if (env.print_timestamp) {
191 		if (start_ts == 0)
192 			start_ts = event->ts_us;
193 		printf("%-9.3f", (event->ts_us - start_ts) / 1000000.0);
194 	}
195 
196 	if (env.print_uid)
197 		printf("%-6d", event->uid);
198 
199 	char type = '-';
200 	switch (event->type) {
201 	case TCP_EVENT_TYPE_CONNECT:
202 		type = 'C';
203 		break;
204 	case TCP_EVENT_TYPE_ACCEPT:
205 		type = 'A';
206 		break;
207 	case TCP_EVENT_TYPE_CLOSE:
208 		type = 'X';
209 		break;
210 	}
211 
212 	printf("%c %-6d %-12.12s %-2d %-16s %-16s %-4d %-4d\n",
213 	       type, event->pid, event->task,
214 	       event->af == AF_INET ? 4 : 6,
215 	       inet_ntop(event->af, &s, src, sizeof(src)),
216 	       inet_ntop(event->af, &d, dst, sizeof(dst)),
217 	       ntohs(event->sport), ntohs(event->dport));
218 }
219 
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)220 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
221 {
222 	warn("Lost %llu events on CPU #%d!\n", lost_cnt, cpu);
223 }
224 
print_events(int perf_map_fd)225 static void print_events(int perf_map_fd)
226 {
227 	struct perf_buffer *pb;
228 	int err;
229 
230 	pb = perf_buffer__new(perf_map_fd, 128,
231 			      handle_event, handle_lost_events, NULL, NULL);
232 	if (!pb) {
233 		err = -errno;
234 		warn("failed to open perf buffer: %d\n", err);
235 		goto cleanup;
236 	}
237 
238 	print_events_header();
239 	while (!exiting) {
240 		err = perf_buffer__poll(pb, 100);
241 		if (err < 0 && err != -EINTR) {
242 			warn("error polling perf buffer: %s\n", strerror(-err));
243 			goto cleanup;
244 		}
245 		/* reset err to return 0 if exiting */
246 		err = 0;
247 	}
248 
249 cleanup:
250 	perf_buffer__free(pb);
251 }
252 
main(int argc,char ** argv)253 int main(int argc, char **argv)
254 {
255 	LIBBPF_OPTS(bpf_object_open_opts, open_opts);
256 	static const struct argp argp = {
257 		.options = opts,
258 		.parser = parse_arg,
259 		.doc = argp_program_doc,
260 		.args_doc = NULL,
261 	};
262 	struct tcptracer_bpf *obj;
263 	int err;
264 
265 	err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
266 	if (err)
267 		return err;
268 
269 	libbpf_set_print(libbpf_print_fn);
270 
271 	err = ensure_core_btf(&open_opts);
272 	if (err) {
273 		fprintf(stderr, "failed to fetch necessary BTF for CO-RE: %s\n", strerror(-err));
274 		return 1;
275 	}
276 
277 	obj = tcptracer_bpf__open_opts(&open_opts);
278 	if (!obj) {
279 		warn("failed to open BPF object\n");
280 		return 1;
281 	}
282 
283 	if (env.pid)
284 		obj->rodata->filter_pid = env.pid;
285 	if (env.uid != (uid_t) -1)
286 		obj->rodata->filter_uid = env.uid;
287 
288 	err = tcptracer_bpf__load(obj);
289 	if (err) {
290 		warn("failed to load BPF object: %d\n", err);
291 		goto cleanup;
292 	}
293 
294 	err = tcptracer_bpf__attach(obj);
295 	if (err) {
296 		warn("failed to attach BPF programs: %s\n", strerror(-err));
297 		goto cleanup;
298 	}
299 
300 	if (signal(SIGINT, sig_int) == SIG_ERR) {
301 		warn("can't set signal handler: %s\n", strerror(errno));
302 		err = 1;
303 		goto cleanup;
304 	}
305 
306 
307 	print_events(bpf_map__fd(obj->maps.events));
308 
309 cleanup:
310 	tcptracer_bpf__destroy(obj);
311 	cleanup_core_btf(&open_opts);
312 
313 	return err != 0;
314 }
315