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