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