• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 /*
4  * solisten  Trace IPv4 and IPv6 listen syscalls
5  *
6  * Copyright (c) 2021 Hengqi Chen
7  *
8  * Based on solisten(8) from BCC by Jean-Tiare Le Bigot
9  * 31-May-2021   Hengqi Chen   Created this.
10  */
11 #include <argp.h>
12 #include <arpa/inet.h>
13 #include <errno.h>
14 #include <signal.h>
15 #include <sys/socket.h>
16 #include <time.h>
17 
18 #include <bpf/libbpf.h>
19 #include <bpf/bpf.h>
20 #include "solisten.h"
21 #include "solisten.skel.h"
22 #include "trace_helpers.h"
23 
24 #define PERF_BUFFER_PAGES       16
25 #define PERF_POLL_TIMEOUT_MS    100
26 #define warn(...) fprintf(stderr, __VA_ARGS__)
27 
28 static volatile sig_atomic_t exiting = 0;
29 
30 static pid_t target_pid = 0;
31 static bool emit_timestamp = false;
32 static bool verbose = false;
33 
34 const char *argp_program_version = "solisten 0.1";
35 const char *argp_program_bug_address =
36 	"https://github.com/iovisor/bcc/tree/master/libbpf-tools";
37 const char argp_program_doc[] =
38 "Trace IPv4 and IPv6 listen syscalls.\n"
39 "\n"
40 "USAGE: solisten [-h] [-t] [-p PID]\n"
41 "\n"
42 "EXAMPLES:\n"
43 "    solisten           # trace listen syscalls\n"
44 "    solisten -t        # output with timestamp\n"
45 "    solisten -p 1216   # only trace PID 1216\n";
46 
47 static const struct argp_option opts[] = {
48 	{ "pid", 'p', "PID", 0, "Process ID to trace" },
49 	{ "timestamp", 't', NULL, 0, "Include timestamp on output" },
50 	{ "verbose", 'v', NULL, 0, "Verbose debug output" },
51 	{ NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
52 	{},
53 };
54 
parse_arg(int key,char * arg,struct argp_state * state)55 static error_t parse_arg(int key, char *arg, struct argp_state *state)
56 {
57 	long pid;
58 
59 	switch (key) {
60 	case 'p':
61 		errno = 0;
62 		pid = strtol(arg, NULL, 10);
63 		if (errno || pid <= 0) {
64 			warn("Invalid PID: %s\n", arg);
65 			argp_usage(state);
66 		}
67 		target_pid = pid;
68 		break;
69 	case 't':
70 		emit_timestamp = true;
71 		break;
72 	case 'v':
73 		verbose = true;
74 		break;
75 	case 'h':
76 		argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
77 		break;
78 	default:
79 		return ARGP_ERR_UNKNOWN;
80 	}
81 	return 0;
82 }
83 
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)84 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
85 {
86 	if (level == LIBBPF_DEBUG && !verbose)
87 		return 0;
88 	return vfprintf(stderr, format, args);
89 }
90 
sig_int(int signo)91 static void sig_int(int signo)
92 {
93 	exiting = 1;
94 }
95 
handle_event(void * ctx,int cpu,void * data,__u32 data_sz)96 static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
97 {
98 	const struct event *e = data;
99 	time_t t;
100 	struct tm *tm;
101 	char ts[32], proto[16], addr[48] = {};
102 	__u16 family = e->proto >> 16;
103 	__u16 type = (__u16)e->proto;
104 	const char *prot;
105 
106 	if (emit_timestamp) {
107 		time(&t);
108 		tm = localtime(&t);
109 		strftime(ts, sizeof(ts), "%H:%M:%S", tm);
110 		printf("%8s ", ts);
111 	}
112 
113 	if (type == SOCK_STREAM)
114 		prot = "TCP";
115 	else if (type == SOCK_DGRAM)
116 		prot = "UDP";
117 	else
118 		prot = "UNK";
119 	if (family == AF_INET)
120 		snprintf(proto, sizeof(proto), "%sv4", prot);
121 	else /* family == AF_INET6 */
122 		snprintf(proto, sizeof(proto), "%sv6", prot);
123 	inet_ntop(family, e->addr, addr, sizeof(addr));
124 	printf("%-7d %-16s %-3d %-7d %-5s %-5d %-32s\n",
125 	       e->pid, e->task, e->ret, e->backlog, proto, e->port, addr);
126 }
127 
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)128 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
129 {
130 	warn("lost %llu events on CPU #%d\n", lost_cnt, cpu);
131 }
132 
main(int argc,char ** argv)133 int main(int argc, char **argv)
134 {
135 	static const struct argp argp = {
136 		.options = opts,
137 		.parser = parse_arg,
138 		.doc = argp_program_doc,
139 	};
140 	struct perf_buffer *pb = NULL;
141 	struct solisten_bpf *obj;
142 	int err;
143 
144 	err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
145 	if (err)
146 		return err;
147 
148 	libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
149 	libbpf_set_print(libbpf_print_fn);
150 
151 	obj = solisten_bpf__open();
152 	if (!obj) {
153 		warn("failed to open BPF object\n");
154 		return 1;
155 	}
156 
157 	obj->rodata->target_pid = target_pid;
158 
159 	if (fentry_can_attach("inet_listen", NULL)) {
160 		bpf_program__set_autoload(obj->progs.inet_listen_entry, false);
161 		bpf_program__set_autoload(obj->progs.inet_listen_exit, false);
162 	} else {
163 		bpf_program__set_autoload(obj->progs.inet_listen_fexit, false);
164 	}
165 
166 	err = solisten_bpf__load(obj);
167 	if (err) {
168 		warn("failed to load BPF object: %d\n", err);
169 		goto cleanup;
170 	}
171 
172 	err = solisten_bpf__attach(obj);
173 	if (err) {
174 		warn("failed to attach BPF programs: %d\n", err);
175 		goto cleanup;
176 	}
177 
178 	pb = perf_buffer__new(bpf_map__fd(obj->maps.events), PERF_BUFFER_PAGES,
179 			      handle_event, handle_lost_events, NULL, NULL);
180 	if (!pb) {
181 		err = -errno;
182 		warn("failed to open perf buffer: %d\n", err);
183 		goto cleanup;
184 	}
185 
186 	if (signal(SIGINT, sig_int) == SIG_ERR) {
187 		warn("can't set signal handler: %s\n", strerror(errno));
188 		err = 1;
189 		goto cleanup;
190 	}
191 
192 	if (emit_timestamp)
193 		printf("%-8s ", "TIME(s)");
194 	printf("%-7s %-16s %-3s %-7s %-5s %-5s %-32s\n",
195 	       "PID", "COMM", "RET", "BACKLOG", "PROTO", "PORT", "ADDR");
196 
197 	while (!exiting) {
198 		err = perf_buffer__poll(pb, PERF_POLL_TIMEOUT_MS);
199 		if (err < 0 && err != -EINTR) {
200 			warn("error polling perf buffer: %s\n", strerror(-err));
201 			goto cleanup;
202 		}
203 		/* reset err to return 0 if exiting */
204 		err = 0;
205 	}
206 
207 cleanup:
208 	perf_buffer__free(pb);
209 	solisten_bpf__destroy(obj);
210 
211 	return err != 0;
212 }
213