xref: /aosp_15_r20/external/bcc/libbpf-tools/tcptop.c (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 /*
4  * tcptop Trace sending and received operation over IP.
5  * Copyright (c) 2022 Francis Laniel <[email protected]>
6  *
7  * Based on tcptop(8) from BCC by Brendan Gregg.
8  * 03-Mar-2022   Francis Laniel   Created this.
9  */
10 #include <argp.h>
11 #include <arpa/inet.h>
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <signal.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <time.h>
21 #include <unistd.h>
22 
23 #include <bpf/libbpf.h>
24 #include <bpf/bpf.h>
25 #include "tcptop.h"
26 #include "tcptop.skel.h"
27 #include "trace_helpers.h"
28 
29 #define warn(...) fprintf(stderr, __VA_ARGS__)
30 #define OUTPUT_ROWS_LIMIT 10240
31 
32 #define IPV4 0
33 #define PORT_LENGTH 5
34 
35 enum SORT {
36 	ALL,
37 	SENT,
38 	RECEIVED,
39 };
40 
41 static volatile sig_atomic_t exiting = 0;
42 
43 static pid_t target_pid = -1;
44 static char *cgroup_path;
45 static bool cgroup_filtering = false;
46 static bool clear_screen = true;
47 static bool no_summary = false;
48 static bool ipv4_only = false;
49 static bool ipv6_only = false;
50 static int output_rows = 20;
51 static int sort_by = ALL;
52 static int interval = 1;
53 static int count = 99999999;
54 static bool verbose = false;
55 
56 const char *argp_program_version = "tcptop 0.1";
57 const char *argp_program_bug_address =
58 	"https://github.com/iovisor/bcc/tree/master/libbpf-tools";
59 const char argp_program_doc[] =
60 "Trace sending and received operation over IP.\n"
61 "\n"
62 "USAGE: tcptop [-h] [-p PID] [interval] [count]\n"
63 "\n"
64 "EXAMPLES:\n"
65 "    tcptop            # TCP top, refresh every 1s\n"
66 "    tcptop -p 1216    # only trace PID 1216\n"
67 "    tcptop -c path    # only trace the given cgroup path\n"
68 "    tcptop 5 10       # 5s summaries, 10 times\n";
69 
70 static const struct argp_option opts[] = {
71 	{ "pid", 'p', "PID", 0, "Process ID to trace" },
72 	{ "cgroup", 'c', "/sys/fs/cgroup/unified", 0, "Trace process in cgroup path" },
73 	{ "ipv4", '4', NULL, 0, "trace IPv4 family only" },
74 	{ "ipv6", '6', NULL, 0, "trace IPv6 family only" },
75 	{ "nosummary", 'S', NULL, 0, "Skip system summary line"},
76 	{ "noclear", 'C', NULL, 0, "Don't clear the screen" },
77 	{ "sort", 's', "SORT", 0, "Sort columns, default all [all, sent, received]" },
78 	{ "rows", 'r', "ROWS", 0, "Maximum rows to print, default 20" },
79 	{ "verbose", 'v', NULL, 0, "Verbose debug output" },
80 	{ NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
81 	{},
82 };
83 
84 struct info_t {
85 	struct ip_key_t key;
86 	struct traffic_t value;
87 };
88 
parse_arg(int key,char * arg,struct argp_state * state)89 static error_t parse_arg(int key, char *arg, struct argp_state *state)
90 {
91 	long pid, rows;
92 	static int pos_args;
93 
94 	switch (key) {
95 	case 'p':
96 		errno = 0;
97 		pid = strtol(arg, NULL, 10);
98 		if (errno || pid <= 0) {
99 			warn("invalid PID: %s\n", arg);
100 			argp_usage(state);
101 		}
102 		target_pid = pid;
103 		break;
104 	case 'c':
105 		cgroup_path = arg;
106 		cgroup_filtering = true;
107 		break;
108 	case 'C':
109 		clear_screen = false;
110 		break;
111 	case 'S':
112 		no_summary = true;
113 		break;
114 	case '4':
115 		ipv4_only = true;
116 		if (ipv6_only) {
117 			warn("Only one --ipvX option should be used\n");
118 			argp_usage(state);
119 		}
120 		break;
121 	case '6':
122 		ipv6_only = true;
123 		if (ipv4_only) {
124 			warn("Only one --ipvX option should be used\n");
125 			argp_usage(state);
126 		}
127 		break;
128 	case 's':
129 		if (!strcmp(arg, "all")) {
130 			sort_by = ALL;
131 		} else if (!strcmp(arg, "sent")) {
132 			sort_by = SENT;
133 		} else if (!strcmp(arg, "received")) {
134 			sort_by = RECEIVED;
135 		} else {
136 			warn("invalid sort method: %s\n", arg);
137 			argp_usage(state);
138 		}
139 		break;
140 	case 'r':
141 		errno = 0;
142 		rows = strtol(arg, NULL, 10);
143 		if (errno || rows <= 0) {
144 			warn("invalid rows: %s\n", arg);
145 			argp_usage(state);
146 		}
147 		output_rows = rows;
148 		if (output_rows > OUTPUT_ROWS_LIMIT)
149 			output_rows = OUTPUT_ROWS_LIMIT;
150 		break;
151 	case 'v':
152 		verbose = true;
153 		break;
154 	case 'h':
155 		argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
156 		break;
157 	case ARGP_KEY_ARG:
158 		errno = 0;
159 		if (pos_args == 0) {
160 			interval = strtol(arg, NULL, 10);
161 			if (errno || interval <= 0) {
162 				warn("invalid interval\n");
163 				argp_usage(state);
164 			}
165 		} else if (pos_args == 1) {
166 			count = strtol(arg, NULL, 10);
167 			if (errno || count <= 0) {
168 				warn("invalid count\n");
169 				argp_usage(state);
170 			}
171 		} else {
172 			warn("unrecognized positional argument: %s\n", arg);
173 			argp_usage(state);
174 		}
175 		pos_args++;
176 		break;
177 	default:
178 		return ARGP_ERR_UNKNOWN;
179 	}
180 	return 0;
181 }
182 
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)183 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
184 {
185 	if (level == LIBBPF_DEBUG && !verbose)
186 		return 0;
187 	return vfprintf(stderr, format, args);
188 }
189 
sig_int(int signo)190 static void sig_int(int signo)
191 {
192 	exiting = 1;
193 }
194 
sort_column(const void * obj1,const void * obj2)195 static int sort_column(const void *obj1, const void *obj2)
196 {
197 	struct info_t *i1 = (struct info_t *)obj1;
198 	struct info_t *i2 = (struct info_t *)obj2;
199 
200 	if (i1->key.family != i2->key.family)
201 		/*
202 		 * i1 - i2 because we want to sort by increasing order (first AF_INET then
203 		 * AF_INET6).
204 		 */
205 		return i1->key.family - i2->key.family;
206 
207 	if (sort_by == SENT)
208 		return i2->value.sent - i1->value.sent;
209 	else if (sort_by == RECEIVED)
210 		return i2->value.received - i1->value.received;
211 	else
212 		return (i2->value.sent + i2->value.received) - (i1->value.sent + i1->value.received);
213 }
214 
print_stat(struct tcptop_bpf * obj)215 static int print_stat(struct tcptop_bpf *obj)
216 {
217 	FILE *f;
218 	time_t t;
219 	struct tm *tm;
220 	char ts[16], buf[256];
221 	struct ip_key_t key, *prev_key = NULL;
222 	static struct info_t infos[OUTPUT_ROWS_LIMIT];
223 	int n, i, err = 0;
224 	int fd = bpf_map__fd(obj->maps.ip_map);
225 	int rows = 0;
226 	bool ipv6_header_printed = false;
227 
228 	if (!no_summary) {
229 		f = fopen("/proc/loadavg", "r");
230 		if (f) {
231 			time(&t);
232 			tm = localtime(&t);
233 			strftime(ts, sizeof(ts), "%H:%M:%S", tm);
234 			memset(buf, 0, sizeof(buf));
235 			n = fread(buf, 1, sizeof(buf), f);
236 			if (n)
237 				printf("%8s loadavg: %s\n", ts, buf);
238 			fclose(f);
239 		}
240 	}
241 
242 	while (1) {
243 		err = bpf_map_get_next_key(fd, prev_key, &infos[rows].key);
244 		if (err) {
245 			if (errno == ENOENT) {
246 				err = 0;
247 				break;
248 			}
249 			warn("bpf_map_get_next_key failed: %s\n", strerror(errno));
250 			return err;
251 		}
252 		err = bpf_map_lookup_elem(fd, &infos[rows].key, &infos[rows].value);
253 		if (err) {
254 			warn("bpf_map_lookup_elem failed: %s\n", strerror(errno));
255 			return err;
256 		}
257 		prev_key = &infos[rows].key;
258 		rows++;
259 	}
260 
261 	printf("%-6s %-12s %-21s %-21s %6s %6s", "PID", "COMM", "LADDR", "RADDR",
262 				 "RX_KB", "TX_KB\n");
263 
264 	qsort(infos, rows, sizeof(struct info_t), sort_column);
265 	rows = rows < output_rows ? rows : output_rows;
266 	for (i = 0; i < rows; i++) {
267 		/* Default width to fit IPv4 plus port. */
268 		int column_width = 21;
269 		struct ip_key_t *key = &infos[i].key;
270 		struct traffic_t *value = &infos[i].value;
271 
272 		if (key->family == AF_INET6) {
273 			/* Width to fit IPv6 plus port. */
274 			column_width = 51;
275 			if (!ipv6_header_printed) {
276 				printf("\n%-6s %-12s %-51s %-51s %6s %6s", "PID", "COMM", "LADDR6",
277 							"RADDR6", "RX_KB", "TX_KB\n");
278 				ipv6_header_printed = true;
279 			}
280 		}
281 
282 		char saddr[INET6_ADDRSTRLEN];
283 		char daddr[INET6_ADDRSTRLEN];
284 
285 		inet_ntop(key->family, &key->saddr, saddr, INET6_ADDRSTRLEN);
286 		inet_ntop(key->family, &key->daddr, daddr, INET6_ADDRSTRLEN);
287 
288 		/*
289 		 * A port is stored in u16, so highest value is 65535, which is 5
290 		 * characters long.
291 		 * We need one character more for ':'.
292 		 */
293 		size_t size = INET6_ADDRSTRLEN + PORT_LENGTH + 1;
294 
295 		char saddr_port[size];
296 		char daddr_port[size];
297 
298 		snprintf(saddr_port, size, "%s:%d", saddr, key->lport);
299 		snprintf(daddr_port, size, "%s:%d", daddr, key->dport);
300 
301 		printf("%-6d %-12.12s %-*s %-*s %6ld %6ld\n",
302 					 key->pid, key->name,
303 					 column_width, saddr_port,
304 					 column_width, daddr_port,
305 					 value->received / 1024, value->sent / 1024);
306 	}
307 
308 	printf("\n");
309 
310 	prev_key = NULL;
311 	while (1) {
312 		err = bpf_map_get_next_key(fd, prev_key, &key);
313 		if (err) {
314 			if (errno == ENOENT) {
315 				err = 0;
316 				break;
317 			}
318 			warn("bpf_map_get_next_key failed: %s\n", strerror(errno));
319 			return err;
320 		}
321 		err = bpf_map_delete_elem(fd, &key);
322 		if (err) {
323 			warn("bpf_map_delete_elem failed: %s\n", strerror(errno));
324 			return err;
325 		}
326 		prev_key = &key;
327 	}
328 
329 	return err;
330 }
331 
main(int argc,char ** argv)332 int main(int argc, char **argv)
333 {
334 	static const struct argp argp = {
335 		.options = opts,
336 		.parser = parse_arg,
337 		.doc = argp_program_doc,
338 	};
339 	struct tcptop_bpf *obj;
340 	int family;
341 	int cgfd = -1;
342 	int err;
343 
344 	err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
345 	if (err)
346 		return err;
347 
348 	libbpf_set_print(libbpf_print_fn);
349 
350 	family = -1;
351 	if (ipv4_only)
352 		family = AF_INET;
353 	if (ipv6_only)
354 		family = AF_INET6;
355 
356 	obj = tcptop_bpf__open();
357 	if (!obj) {
358 		warn("failed to open BPF object\n");
359 		return 1;
360 	}
361 
362 	obj->rodata->target_pid = target_pid;
363 	obj->rodata->target_family = family;
364 	obj->rodata->filter_cg = cgroup_filtering;
365 
366 	err = tcptop_bpf__load(obj);
367 	if (err) {
368 		warn("failed to load BPF object: %d\n", err);
369 		goto cleanup;
370 	}
371 
372 	if (cgroup_filtering) {
373 		int zero = 0;
374 		int cg_map_fd = bpf_map__fd(obj->maps.cgroup_map);
375 
376 		cgfd = open(cgroup_path, O_RDONLY);
377 		if (cgfd < 0) {
378 			warn("Failed opening Cgroup path: %s\n", cgroup_path);
379 			goto cleanup;
380 		}
381 
382 		warn("bpf_map__fd: %d\n", cg_map_fd);
383 
384 		if (bpf_map_update_elem(cg_map_fd, &zero, &cgfd, BPF_ANY)) {
385 			warn("Failed adding target cgroup to map\n");
386 			goto cleanup;
387 		}
388 	}
389 
390 	err = tcptop_bpf__attach(obj);
391 	if (err) {
392 		warn("failed to attach BPF programs: %d\n", err);
393 		goto cleanup;
394 	}
395 
396 	if (signal(SIGINT, sig_int) == SIG_ERR) {
397 		warn("can't set signal handler: %s\n", strerror(errno));
398 		err = 1;
399 		goto cleanup;
400 	}
401 
402 	while (1) {
403 		sleep(interval);
404 
405 		if (clear_screen) {
406 			err = system("clear");
407 			if (err)
408 				goto cleanup;
409 		}
410 
411 		err = print_stat(obj);
412 		if (err)
413 			goto cleanup;
414 
415 		count--;
416 		if (exiting || !count)
417 			goto cleanup;
418 	}
419 
420 cleanup:
421 	if (cgroup_filtering && cgfd != -1)
422 		close(cgfd);
423 	tcptop_bpf__destroy(obj);
424 
425 	return err != 0;
426 }
427