xref: /linux/tools/bpf/bpftool/net.c (revision 52990390f91c1c39ca742fc8f390b29891d95127)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 // Copyright (C) 2018 Facebook
3 
4 #ifndef _GNU_SOURCE
5 #define _GNU_SOURCE
6 #endif
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <time.h>
12 #include <unistd.h>
13 #include <bpf/bpf.h>
14 #include <bpf/libbpf.h>
15 #include <net/if.h>
16 #include <linux/rtnetlink.h>
17 #include <linux/socket.h>
18 #include <linux/tc_act/tc_bpf.h>
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 
23 #include "bpf/nlattr.h"
24 #include "main.h"
25 #include "netlink_dumper.h"
26 
27 #ifndef SOL_NETLINK
28 #define SOL_NETLINK 270
29 #endif
30 
31 struct ip_devname_ifindex {
32 	char	devname[64];
33 	int	ifindex;
34 };
35 
36 struct bpf_netdev_t {
37 	struct ip_devname_ifindex *devices;
38 	int	used_len;
39 	int	array_len;
40 	int	filter_idx;
41 };
42 
43 struct tc_kind_handle {
44 	char	kind[64];
45 	int	handle;
46 };
47 
48 struct bpf_tcinfo_t {
49 	struct tc_kind_handle	*handle_array;
50 	int			used_len;
51 	int			array_len;
52 	bool			is_qdisc;
53 };
54 
55 struct bpf_filter_t {
56 	const char	*kind;
57 	const char	*devname;
58 	int		ifindex;
59 };
60 
61 struct bpf_attach_info {
62 	__u32 flow_dissector_id;
63 };
64 
65 enum net_attach_type {
66 	NET_ATTACH_TYPE_XDP,
67 	NET_ATTACH_TYPE_XDP_GENERIC,
68 	NET_ATTACH_TYPE_XDP_DRIVER,
69 	NET_ATTACH_TYPE_XDP_OFFLOAD,
70 };
71 
72 static const char * const attach_type_strings[] = {
73 	[NET_ATTACH_TYPE_XDP]		= "xdp",
74 	[NET_ATTACH_TYPE_XDP_GENERIC]	= "xdpgeneric",
75 	[NET_ATTACH_TYPE_XDP_DRIVER]	= "xdpdrv",
76 	[NET_ATTACH_TYPE_XDP_OFFLOAD]	= "xdpoffload",
77 };
78 
79 const size_t net_attach_type_size = ARRAY_SIZE(attach_type_strings);
80 
81 static enum net_attach_type parse_attach_type(const char *str)
82 {
83 	enum net_attach_type type;
84 
85 	for (type = 0; type < net_attach_type_size; type++) {
86 		if (attach_type_strings[type] &&
87 		    is_prefix(str, attach_type_strings[type]))
88 			return type;
89 	}
90 
91 	return net_attach_type_size;
92 }
93 
94 typedef int (*dump_nlmsg_t)(void *cookie, void *msg, struct nlattr **tb);
95 
96 typedef int (*__dump_nlmsg_t)(struct nlmsghdr *nlmsg, dump_nlmsg_t, void *cookie);
97 
98 static int netlink_open(__u32 *nl_pid)
99 {
100 	struct sockaddr_nl sa;
101 	socklen_t addrlen;
102 	int one = 1, ret;
103 	int sock;
104 
105 	memset(&sa, 0, sizeof(sa));
106 	sa.nl_family = AF_NETLINK;
107 
108 	sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
109 	if (sock < 0)
110 		return -errno;
111 
112 	if (setsockopt(sock, SOL_NETLINK, NETLINK_EXT_ACK,
113 		       &one, sizeof(one)) < 0) {
114 		p_err("Netlink error reporting not supported");
115 	}
116 
117 	if (bind(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
118 		ret = -errno;
119 		goto cleanup;
120 	}
121 
122 	addrlen = sizeof(sa);
123 	if (getsockname(sock, (struct sockaddr *)&sa, &addrlen) < 0) {
124 		ret = -errno;
125 		goto cleanup;
126 	}
127 
128 	if (addrlen != sizeof(sa)) {
129 		ret = -LIBBPF_ERRNO__INTERNAL;
130 		goto cleanup;
131 	}
132 
133 	*nl_pid = sa.nl_pid;
134 	return sock;
135 
136 cleanup:
137 	close(sock);
138 	return ret;
139 }
140 
141 static int netlink_recv(int sock, __u32 nl_pid, __u32 seq,
142 			    __dump_nlmsg_t _fn, dump_nlmsg_t fn,
143 			    void *cookie)
144 {
145 	bool multipart = true;
146 	struct nlmsgerr *err;
147 	struct nlmsghdr *nh;
148 	char buf[4096];
149 	int len, ret;
150 
151 	while (multipart) {
152 		multipart = false;
153 		len = recv(sock, buf, sizeof(buf), 0);
154 		if (len < 0) {
155 			ret = -errno;
156 			goto done;
157 		}
158 
159 		if (len == 0)
160 			break;
161 
162 		for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, (unsigned int)len);
163 		     nh = NLMSG_NEXT(nh, len)) {
164 			if (nh->nlmsg_pid != nl_pid) {
165 				ret = -LIBBPF_ERRNO__WRNGPID;
166 				goto done;
167 			}
168 			if (nh->nlmsg_seq != seq) {
169 				ret = -LIBBPF_ERRNO__INVSEQ;
170 				goto done;
171 			}
172 			if (nh->nlmsg_flags & NLM_F_MULTI)
173 				multipart = true;
174 			switch (nh->nlmsg_type) {
175 			case NLMSG_ERROR:
176 				err = (struct nlmsgerr *)NLMSG_DATA(nh);
177 				if (!err->error)
178 					continue;
179 				ret = err->error;
180 				libbpf_nla_dump_errormsg(nh);
181 				goto done;
182 			case NLMSG_DONE:
183 				return 0;
184 			default:
185 				break;
186 			}
187 			if (_fn) {
188 				ret = _fn(nh, fn, cookie);
189 				if (ret)
190 					return ret;
191 			}
192 		}
193 	}
194 	ret = 0;
195 done:
196 	return ret;
197 }
198 
199 static int __dump_class_nlmsg(struct nlmsghdr *nlh,
200 			      dump_nlmsg_t dump_class_nlmsg,
201 			      void *cookie)
202 {
203 	struct nlattr *tb[TCA_MAX + 1], *attr;
204 	struct tcmsg *t = NLMSG_DATA(nlh);
205 	int len;
206 
207 	len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*t));
208 	attr = (struct nlattr *) ((void *) t + NLMSG_ALIGN(sizeof(*t)));
209 	if (libbpf_nla_parse(tb, TCA_MAX, attr, len, NULL) != 0)
210 		return -LIBBPF_ERRNO__NLPARSE;
211 
212 	return dump_class_nlmsg(cookie, t, tb);
213 }
214 
215 static int netlink_get_class(int sock, unsigned int nl_pid, int ifindex,
216 			     dump_nlmsg_t dump_class_nlmsg, void *cookie)
217 {
218 	struct {
219 		struct nlmsghdr nlh;
220 		struct tcmsg t;
221 	} req = {
222 		.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct tcmsg)),
223 		.nlh.nlmsg_type = RTM_GETTCLASS,
224 		.nlh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
225 		.t.tcm_family = AF_UNSPEC,
226 		.t.tcm_ifindex = ifindex,
227 	};
228 	int seq = time(NULL);
229 
230 	req.nlh.nlmsg_seq = seq;
231 	if (send(sock, &req, req.nlh.nlmsg_len, 0) < 0)
232 		return -errno;
233 
234 	return netlink_recv(sock, nl_pid, seq, __dump_class_nlmsg,
235 			    dump_class_nlmsg, cookie);
236 }
237 
238 static int __dump_qdisc_nlmsg(struct nlmsghdr *nlh,
239 			      dump_nlmsg_t dump_qdisc_nlmsg,
240 			      void *cookie)
241 {
242 	struct nlattr *tb[TCA_MAX + 1], *attr;
243 	struct tcmsg *t = NLMSG_DATA(nlh);
244 	int len;
245 
246 	len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*t));
247 	attr = (struct nlattr *) ((void *) t + NLMSG_ALIGN(sizeof(*t)));
248 	if (libbpf_nla_parse(tb, TCA_MAX, attr, len, NULL) != 0)
249 		return -LIBBPF_ERRNO__NLPARSE;
250 
251 	return dump_qdisc_nlmsg(cookie, t, tb);
252 }
253 
254 static int netlink_get_qdisc(int sock, unsigned int nl_pid, int ifindex,
255 			     dump_nlmsg_t dump_qdisc_nlmsg, void *cookie)
256 {
257 	struct {
258 		struct nlmsghdr nlh;
259 		struct tcmsg t;
260 	} req = {
261 		.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct tcmsg)),
262 		.nlh.nlmsg_type = RTM_GETQDISC,
263 		.nlh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
264 		.t.tcm_family = AF_UNSPEC,
265 		.t.tcm_ifindex = ifindex,
266 	};
267 	int seq = time(NULL);
268 
269 	req.nlh.nlmsg_seq = seq;
270 	if (send(sock, &req, req.nlh.nlmsg_len, 0) < 0)
271 		return -errno;
272 
273 	return netlink_recv(sock, nl_pid, seq, __dump_qdisc_nlmsg,
274 			    dump_qdisc_nlmsg, cookie);
275 }
276 
277 static int __dump_filter_nlmsg(struct nlmsghdr *nlh,
278 			       dump_nlmsg_t dump_filter_nlmsg,
279 			       void *cookie)
280 {
281 	struct nlattr *tb[TCA_MAX + 1], *attr;
282 	struct tcmsg *t = NLMSG_DATA(nlh);
283 	int len;
284 
285 	len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*t));
286 	attr = (struct nlattr *) ((void *) t + NLMSG_ALIGN(sizeof(*t)));
287 	if (libbpf_nla_parse(tb, TCA_MAX, attr, len, NULL) != 0)
288 		return -LIBBPF_ERRNO__NLPARSE;
289 
290 	return dump_filter_nlmsg(cookie, t, tb);
291 }
292 
293 static int netlink_get_filter(int sock, unsigned int nl_pid, int ifindex, int handle,
294 			      dump_nlmsg_t dump_filter_nlmsg, void *cookie)
295 {
296 	struct {
297 		struct nlmsghdr nlh;
298 		struct tcmsg t;
299 	} req = {
300 		.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct tcmsg)),
301 		.nlh.nlmsg_type = RTM_GETTFILTER,
302 		.nlh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
303 		.t.tcm_family = AF_UNSPEC,
304 		.t.tcm_ifindex = ifindex,
305 		.t.tcm_parent = handle,
306 	};
307 	int seq = time(NULL);
308 
309 	req.nlh.nlmsg_seq = seq;
310 	if (send(sock, &req, req.nlh.nlmsg_len, 0) < 0)
311 		return -errno;
312 
313 	return netlink_recv(sock, nl_pid, seq, __dump_filter_nlmsg,
314 			    dump_filter_nlmsg, cookie);
315 }
316 
317 static int __dump_link_nlmsg(struct nlmsghdr *nlh,
318 			     dump_nlmsg_t dump_link_nlmsg, void *cookie)
319 {
320 	struct nlattr *tb[IFLA_MAX + 1], *attr;
321 	struct ifinfomsg *ifi = NLMSG_DATA(nlh);
322 	int len;
323 
324 	len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*ifi));
325 	attr = (struct nlattr *) ((void *) ifi + NLMSG_ALIGN(sizeof(*ifi)));
326 	if (libbpf_nla_parse(tb, IFLA_MAX, attr, len, NULL) != 0)
327 		return -LIBBPF_ERRNO__NLPARSE;
328 
329 	return dump_link_nlmsg(cookie, ifi, tb);
330 }
331 
332 static int netlink_get_link(int sock, unsigned int nl_pid,
333 			    dump_nlmsg_t dump_link_nlmsg, void *cookie)
334 {
335 	struct {
336 		struct nlmsghdr nlh;
337 		struct ifinfomsg ifm;
338 	} req = {
339 		.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
340 		.nlh.nlmsg_type = RTM_GETLINK,
341 		.nlh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
342 		.ifm.ifi_family = AF_PACKET,
343 	};
344 	int seq = time(NULL);
345 
346 	req.nlh.nlmsg_seq = seq;
347 	if (send(sock, &req, req.nlh.nlmsg_len, 0) < 0)
348 		return -errno;
349 
350 	return netlink_recv(sock, nl_pid, seq, __dump_link_nlmsg,
351 			    dump_link_nlmsg, cookie);
352 }
353 
354 static int dump_link_nlmsg(void *cookie, void *msg, struct nlattr **tb)
355 {
356 	struct bpf_netdev_t *netinfo = cookie;
357 	struct ifinfomsg *ifinfo = msg;
358 
359 	if (netinfo->filter_idx > 0 && netinfo->filter_idx != ifinfo->ifi_index)
360 		return 0;
361 
362 	if (netinfo->used_len == netinfo->array_len) {
363 		netinfo->devices = realloc(netinfo->devices,
364 			(netinfo->array_len + 16) *
365 			sizeof(struct ip_devname_ifindex));
366 		if (!netinfo->devices)
367 			return -ENOMEM;
368 
369 		netinfo->array_len += 16;
370 	}
371 	netinfo->devices[netinfo->used_len].ifindex = ifinfo->ifi_index;
372 	snprintf(netinfo->devices[netinfo->used_len].devname,
373 		 sizeof(netinfo->devices[netinfo->used_len].devname),
374 		 "%s",
375 		 tb[IFLA_IFNAME]
376 			 ? libbpf_nla_getattr_str(tb[IFLA_IFNAME])
377 			 : "");
378 	netinfo->used_len++;
379 
380 	return do_xdp_dump(ifinfo, tb);
381 }
382 
383 static int dump_class_qdisc_nlmsg(void *cookie, void *msg, struct nlattr **tb)
384 {
385 	struct bpf_tcinfo_t *tcinfo = cookie;
386 	struct tcmsg *info = msg;
387 
388 	if (tcinfo->is_qdisc) {
389 		/* skip clsact qdisc */
390 		if (tb[TCA_KIND] &&
391 		    strcmp(libbpf_nla_data(tb[TCA_KIND]), "clsact") == 0)
392 			return 0;
393 		if (info->tcm_handle == 0)
394 			return 0;
395 	}
396 
397 	if (tcinfo->used_len == tcinfo->array_len) {
398 		tcinfo->handle_array = realloc(tcinfo->handle_array,
399 			(tcinfo->array_len + 16) * sizeof(struct tc_kind_handle));
400 		if (!tcinfo->handle_array)
401 			return -ENOMEM;
402 
403 		tcinfo->array_len += 16;
404 	}
405 	tcinfo->handle_array[tcinfo->used_len].handle = info->tcm_handle;
406 	snprintf(tcinfo->handle_array[tcinfo->used_len].kind,
407 		 sizeof(tcinfo->handle_array[tcinfo->used_len].kind),
408 		 "%s",
409 		 tb[TCA_KIND]
410 			 ? libbpf_nla_getattr_str(tb[TCA_KIND])
411 			 : "unknown");
412 	tcinfo->used_len++;
413 
414 	return 0;
415 }
416 
417 static int dump_filter_nlmsg(void *cookie, void *msg, struct nlattr **tb)
418 {
419 	const struct bpf_filter_t *filter_info = cookie;
420 
421 	return do_filter_dump((struct tcmsg *)msg, tb, filter_info->kind,
422 			      filter_info->devname, filter_info->ifindex);
423 }
424 
425 static int show_dev_tc_bpf(int sock, unsigned int nl_pid,
426 			   struct ip_devname_ifindex *dev)
427 {
428 	struct bpf_filter_t filter_info;
429 	struct bpf_tcinfo_t tcinfo;
430 	int i, handle, ret = 0;
431 
432 	tcinfo.handle_array = NULL;
433 	tcinfo.used_len = 0;
434 	tcinfo.array_len = 0;
435 
436 	tcinfo.is_qdisc = false;
437 	ret = netlink_get_class(sock, nl_pid, dev->ifindex,
438 				dump_class_qdisc_nlmsg, &tcinfo);
439 	if (ret)
440 		goto out;
441 
442 	tcinfo.is_qdisc = true;
443 	ret = netlink_get_qdisc(sock, nl_pid, dev->ifindex,
444 				dump_class_qdisc_nlmsg, &tcinfo);
445 	if (ret)
446 		goto out;
447 
448 	filter_info.devname = dev->devname;
449 	filter_info.ifindex = dev->ifindex;
450 	for (i = 0; i < tcinfo.used_len; i++) {
451 		filter_info.kind = tcinfo.handle_array[i].kind;
452 		ret = netlink_get_filter(sock, nl_pid, dev->ifindex,
453 					 tcinfo.handle_array[i].handle,
454 					 dump_filter_nlmsg, &filter_info);
455 		if (ret)
456 			goto out;
457 	}
458 
459 	/* root, ingress and egress handle */
460 	handle = TC_H_ROOT;
461 	filter_info.kind = "root";
462 	ret = netlink_get_filter(sock, nl_pid, dev->ifindex, handle,
463 				 dump_filter_nlmsg, &filter_info);
464 	if (ret)
465 		goto out;
466 
467 	handle = TC_H_MAKE(TC_H_CLSACT, TC_H_MIN_INGRESS);
468 	filter_info.kind = "clsact/ingress";
469 	ret = netlink_get_filter(sock, nl_pid, dev->ifindex, handle,
470 				 dump_filter_nlmsg, &filter_info);
471 	if (ret)
472 		goto out;
473 
474 	handle = TC_H_MAKE(TC_H_CLSACT, TC_H_MIN_EGRESS);
475 	filter_info.kind = "clsact/egress";
476 	ret = netlink_get_filter(sock, nl_pid, dev->ifindex, handle,
477 				 dump_filter_nlmsg, &filter_info);
478 	if (ret)
479 		goto out;
480 
481 out:
482 	free(tcinfo.handle_array);
483 	return 0;
484 }
485 
486 static int query_flow_dissector(struct bpf_attach_info *attach_info)
487 {
488 	__u32 attach_flags;
489 	__u32 prog_ids[1];
490 	__u32 prog_cnt;
491 	int err;
492 	int fd;
493 
494 	fd = open("/proc/self/ns/net", O_RDONLY);
495 	if (fd < 0) {
496 		p_err("can't open /proc/self/ns/net: %s",
497 		      strerror(errno));
498 		return -1;
499 	}
500 	prog_cnt = ARRAY_SIZE(prog_ids);
501 	err = bpf_prog_query(fd, BPF_FLOW_DISSECTOR, 0,
502 			     &attach_flags, prog_ids, &prog_cnt);
503 	close(fd);
504 	if (err) {
505 		if (errno == EINVAL) {
506 			/* Older kernel's don't support querying
507 			 * flow dissector programs.
508 			 */
509 			errno = 0;
510 			return 0;
511 		}
512 		p_err("can't query prog: %s", strerror(errno));
513 		return -1;
514 	}
515 
516 	if (prog_cnt == 1)
517 		attach_info->flow_dissector_id = prog_ids[0];
518 
519 	return 0;
520 }
521 
522 static int net_parse_dev(int *argc, char ***argv)
523 {
524 	int ifindex;
525 
526 	if (is_prefix(**argv, "dev")) {
527 		NEXT_ARGP();
528 
529 		ifindex = if_nametoindex(**argv);
530 		if (!ifindex)
531 			p_err("invalid devname %s", **argv);
532 
533 		NEXT_ARGP();
534 	} else {
535 		p_err("expected 'dev', got: '%s'?", **argv);
536 		return -1;
537 	}
538 
539 	return ifindex;
540 }
541 
542 static int do_attach_detach_xdp(int progfd, enum net_attach_type attach_type,
543 				int ifindex, bool overwrite)
544 {
545 	__u32 flags = 0;
546 
547 	if (!overwrite)
548 		flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
549 	if (attach_type == NET_ATTACH_TYPE_XDP_GENERIC)
550 		flags |= XDP_FLAGS_SKB_MODE;
551 	if (attach_type == NET_ATTACH_TYPE_XDP_DRIVER)
552 		flags |= XDP_FLAGS_DRV_MODE;
553 	if (attach_type == NET_ATTACH_TYPE_XDP_OFFLOAD)
554 		flags |= XDP_FLAGS_HW_MODE;
555 
556 	return bpf_xdp_attach(ifindex, progfd, flags, NULL);
557 }
558 
559 static int do_attach(int argc, char **argv)
560 {
561 	enum net_attach_type attach_type;
562 	int progfd, ifindex, err = 0;
563 	bool overwrite = false;
564 
565 	/* parse attach args */
566 	if (!REQ_ARGS(5))
567 		return -EINVAL;
568 
569 	attach_type = parse_attach_type(*argv);
570 	if (attach_type == net_attach_type_size) {
571 		p_err("invalid net attach/detach type: %s", *argv);
572 		return -EINVAL;
573 	}
574 	NEXT_ARG();
575 
576 	progfd = prog_parse_fd(&argc, &argv);
577 	if (progfd < 0)
578 		return -EINVAL;
579 
580 	ifindex = net_parse_dev(&argc, &argv);
581 	if (ifindex < 1) {
582 		err = -EINVAL;
583 		goto cleanup;
584 	}
585 
586 	if (argc) {
587 		if (is_prefix(*argv, "overwrite")) {
588 			overwrite = true;
589 		} else {
590 			p_err("expected 'overwrite', got: '%s'?", *argv);
591 			err = -EINVAL;
592 			goto cleanup;
593 		}
594 	}
595 
596 	/* attach xdp prog */
597 	if (is_prefix("xdp", attach_type_strings[attach_type]))
598 		err = do_attach_detach_xdp(progfd, attach_type, ifindex,
599 					   overwrite);
600 	if (err) {
601 		p_err("interface %s attach failed: %s",
602 		      attach_type_strings[attach_type], strerror(-err));
603 		goto cleanup;
604 	}
605 
606 	if (json_output)
607 		jsonw_null(json_wtr);
608 cleanup:
609 	close(progfd);
610 	return err;
611 }
612 
613 static int do_detach(int argc, char **argv)
614 {
615 	enum net_attach_type attach_type;
616 	int progfd, ifindex, err = 0;
617 
618 	/* parse detach args */
619 	if (!REQ_ARGS(3))
620 		return -EINVAL;
621 
622 	attach_type = parse_attach_type(*argv);
623 	if (attach_type == net_attach_type_size) {
624 		p_err("invalid net attach/detach type: %s", *argv);
625 		return -EINVAL;
626 	}
627 	NEXT_ARG();
628 
629 	ifindex = net_parse_dev(&argc, &argv);
630 	if (ifindex < 1)
631 		return -EINVAL;
632 
633 	/* detach xdp prog */
634 	progfd = -1;
635 	if (is_prefix("xdp", attach_type_strings[attach_type]))
636 		err = do_attach_detach_xdp(progfd, attach_type, ifindex, NULL);
637 
638 	if (err < 0) {
639 		p_err("interface %s detach failed: %s",
640 		      attach_type_strings[attach_type], strerror(-err));
641 		return err;
642 	}
643 
644 	if (json_output)
645 		jsonw_null(json_wtr);
646 
647 	return 0;
648 }
649 
650 static int netfilter_link_compar(const void *a, const void *b)
651 {
652 	const struct bpf_link_info *nfa = a;
653 	const struct bpf_link_info *nfb = b;
654 	int delta;
655 
656 	delta = nfa->netfilter.pf - nfb->netfilter.pf;
657 	if (delta)
658 		return delta;
659 
660 	delta = nfa->netfilter.hooknum - nfb->netfilter.hooknum;
661 	if (delta)
662 		return delta;
663 
664 	if (nfa->netfilter.priority < nfb->netfilter.priority)
665 		return -1;
666 	if (nfa->netfilter.priority > nfb->netfilter.priority)
667 		return 1;
668 
669 	return nfa->netfilter.flags - nfb->netfilter.flags;
670 }
671 
672 static void show_link_netfilter(void)
673 {
674 	unsigned int nf_link_len = 0, nf_link_count = 0;
675 	struct bpf_link_info *nf_link_info = NULL;
676 	__u32 id = 0;
677 
678 	while (true) {
679 		struct bpf_link_info info;
680 		int fd, err;
681 		__u32 len;
682 
683 		err = bpf_link_get_next_id(id, &id);
684 		if (err) {
685 			if (errno == ENOENT)
686 				break;
687 			p_err("can't get next link: %s (id %d)", strerror(errno), id);
688 			break;
689 		}
690 
691 		fd = bpf_link_get_fd_by_id(id);
692 		if (fd < 0) {
693 			p_err("can't get link by id (%u): %s", id, strerror(errno));
694 			continue;
695 		}
696 
697 		memset(&info, 0, sizeof(info));
698 		len = sizeof(info);
699 
700 		err = bpf_link_get_info_by_fd(fd, &info, &len);
701 
702 		close(fd);
703 
704 		if (err) {
705 			p_err("can't get link info for fd %d: %s", fd, strerror(errno));
706 			continue;
707 		}
708 
709 		if (info.type != BPF_LINK_TYPE_NETFILTER)
710 			continue;
711 
712 		if (nf_link_count >= nf_link_len) {
713 			static const unsigned int max_link_count = INT_MAX / sizeof(info);
714 			struct bpf_link_info *expand;
715 
716 			if (nf_link_count > max_link_count) {
717 				p_err("cannot handle more than %u links\n", max_link_count);
718 				break;
719 			}
720 
721 			nf_link_len += 16;
722 
723 			expand = realloc(nf_link_info, nf_link_len * sizeof(info));
724 			if (!expand) {
725 				p_err("realloc: %s",  strerror(errno));
726 				break;
727 			}
728 
729 			nf_link_info = expand;
730 		}
731 
732 		nf_link_info[nf_link_count] = info;
733 		nf_link_count++;
734 	}
735 
736 	qsort(nf_link_info, nf_link_count, sizeof(*nf_link_info), netfilter_link_compar);
737 
738 	for (id = 0; id < nf_link_count; id++) {
739 		NET_START_OBJECT;
740 		if (json_output)
741 			netfilter_dump_json(&nf_link_info[id], json_wtr);
742 		else
743 			netfilter_dump_plain(&nf_link_info[id]);
744 
745 		NET_DUMP_UINT("id", " prog_id %u", nf_link_info[id].prog_id);
746 		NET_END_OBJECT;
747 	}
748 
749 	free(nf_link_info);
750 }
751 
752 static int do_show(int argc, char **argv)
753 {
754 	struct bpf_attach_info attach_info = {};
755 	int i, sock, ret, filter_idx = -1;
756 	struct bpf_netdev_t dev_array;
757 	unsigned int nl_pid = 0;
758 	char err_buf[256];
759 
760 	if (argc == 2) {
761 		filter_idx = net_parse_dev(&argc, &argv);
762 		if (filter_idx < 1)
763 			return -1;
764 	} else if (argc != 0) {
765 		usage();
766 	}
767 
768 	ret = query_flow_dissector(&attach_info);
769 	if (ret)
770 		return -1;
771 
772 	sock = netlink_open(&nl_pid);
773 	if (sock < 0) {
774 		fprintf(stderr, "failed to open netlink sock\n");
775 		return -1;
776 	}
777 
778 	dev_array.devices = NULL;
779 	dev_array.used_len = 0;
780 	dev_array.array_len = 0;
781 	dev_array.filter_idx = filter_idx;
782 
783 	if (json_output)
784 		jsonw_start_array(json_wtr);
785 	NET_START_OBJECT;
786 	NET_START_ARRAY("xdp", "%s:\n");
787 	ret = netlink_get_link(sock, nl_pid, dump_link_nlmsg, &dev_array);
788 	NET_END_ARRAY("\n");
789 
790 	if (!ret) {
791 		NET_START_ARRAY("tc", "%s:\n");
792 		for (i = 0; i < dev_array.used_len; i++) {
793 			ret = show_dev_tc_bpf(sock, nl_pid,
794 					      &dev_array.devices[i]);
795 			if (ret)
796 				break;
797 		}
798 		NET_END_ARRAY("\n");
799 	}
800 
801 	NET_START_ARRAY("flow_dissector", "%s:\n");
802 	if (attach_info.flow_dissector_id > 0)
803 		NET_DUMP_UINT("id", "id %u", attach_info.flow_dissector_id);
804 	NET_END_ARRAY("\n");
805 
806 	NET_START_ARRAY("netfilter", "%s:\n");
807 	show_link_netfilter();
808 	NET_END_ARRAY("\n");
809 
810 	NET_END_OBJECT;
811 	if (json_output)
812 		jsonw_end_array(json_wtr);
813 
814 	if (ret) {
815 		if (json_output)
816 			jsonw_null(json_wtr);
817 		libbpf_strerror(ret, err_buf, sizeof(err_buf));
818 		fprintf(stderr, "Error: %s\n", err_buf);
819 	}
820 	free(dev_array.devices);
821 	close(sock);
822 	return ret;
823 }
824 
825 static int do_help(int argc, char **argv)
826 {
827 	if (json_output) {
828 		jsonw_null(json_wtr);
829 		return 0;
830 	}
831 
832 	fprintf(stderr,
833 		"Usage: %1$s %2$s { show | list } [dev <devname>]\n"
834 		"       %1$s %2$s attach ATTACH_TYPE PROG dev <devname> [ overwrite ]\n"
835 		"       %1$s %2$s detach ATTACH_TYPE dev <devname>\n"
836 		"       %1$s %2$s help\n"
837 		"\n"
838 		"       " HELP_SPEC_PROGRAM "\n"
839 		"       ATTACH_TYPE := { xdp | xdpgeneric | xdpdrv | xdpoffload }\n"
840 		"       " HELP_SPEC_OPTIONS " }\n"
841 		"\n"
842 		"Note: Only xdp and tc attachments are supported now.\n"
843 		"      For progs attached to cgroups, use \"bpftool cgroup\"\n"
844 		"      to dump program attachments. For program types\n"
845 		"      sk_{filter,skb,msg,reuseport} and lwt/seg6, please\n"
846 		"      consult iproute2.\n"
847 		"",
848 		bin_name, argv[-2]);
849 
850 	return 0;
851 }
852 
853 static const struct cmd cmds[] = {
854 	{ "show",	do_show },
855 	{ "list",	do_show },
856 	{ "attach",	do_attach },
857 	{ "detach",	do_detach },
858 	{ "help",	do_help },
859 	{ 0 }
860 };
861 
862 int do_net(int argc, char **argv)
863 {
864 	return cmd_select(cmds, argc, argv, do_help);
865 }
866