1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
3 
4 #define _GNU_SOURCE
5 #include <ctype.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <ftw.h>
9 #include <libgen.h>
10 #include <mntent.h>
11 #include <stdbool.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <net/if.h>
17 #include <sys/mount.h>
18 #include <sys/resource.h>
19 #include <sys/stat.h>
20 #include <sys/vfs.h>
21 
22 #include <linux/filter.h>
23 #include <linux/limits.h>
24 #include <linux/magic.h>
25 #include <linux/unistd.h>
26 
27 #include <bpf/bpf.h>
28 #include <bpf/hashmap.h>
29 #include <bpf/libbpf.h> /* libbpf_num_possible_cpus */
30 #include <bpf/btf.h>
31 
32 #include "main.h"
33 
34 #ifndef BPF_FS_MAGIC
35 #define BPF_FS_MAGIC		0xcafe4a11
36 #endif
37 
p_err(const char * fmt,...)38 void p_err(const char *fmt, ...)
39 {
40 	va_list ap;
41 
42 	va_start(ap, fmt);
43 	if (json_output) {
44 		jsonw_start_object(json_wtr);
45 		jsonw_name(json_wtr, "error");
46 		jsonw_vprintf_enquote(json_wtr, fmt, ap);
47 		jsonw_end_object(json_wtr);
48 	} else {
49 		fprintf(stderr, "Error: ");
50 		vfprintf(stderr, fmt, ap);
51 		fprintf(stderr, "\n");
52 	}
53 	va_end(ap);
54 }
55 
p_info(const char * fmt,...)56 void p_info(const char *fmt, ...)
57 {
58 	va_list ap;
59 
60 	if (json_output)
61 		return;
62 
63 	va_start(ap, fmt);
64 	vfprintf(stderr, fmt, ap);
65 	fprintf(stderr, "\n");
66 	va_end(ap);
67 }
68 
is_bpffs(char * path)69 static bool is_bpffs(char *path)
70 {
71 	struct statfs st_fs;
72 
73 	if (statfs(path, &st_fs) < 0)
74 		return false;
75 
76 	return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
77 }
78 
79 /* Probe whether kernel switched from memlock-based (RLIMIT_MEMLOCK) to
80  * memcg-based memory accounting for BPF maps and programs. This was done in
81  * commit 97306be45fbe ("Merge branch 'switch to memcg-based memory
82  * accounting'"), in Linux 5.11.
83  *
84  * Libbpf also offers to probe for memcg-based accounting vs rlimit, but does
85  * so by checking for the availability of a given BPF helper and this has
86  * failed on some kernels with backports in the past, see commit 6b4384ff1088
87  * ("Revert "bpftool: Use libbpf 1.0 API mode instead of RLIMIT_MEMLOCK"").
88  * Instead, we can probe by lowering the process-based rlimit to 0, trying to
89  * load a BPF object, and resetting the rlimit. If the load succeeds then
90  * memcg-based accounting is supported.
91  *
92  * This would be too dangerous to do in the library, because multithreaded
93  * applications might attempt to load items while the rlimit is at 0. Given
94  * that bpftool is single-threaded, this is fine to do here.
95  */
known_to_need_rlimit(void)96 static bool known_to_need_rlimit(void)
97 {
98 	struct rlimit rlim_init, rlim_cur_zero = {};
99 	struct bpf_insn insns[] = {
100 		BPF_MOV64_IMM(BPF_REG_0, 0),
101 		BPF_EXIT_INSN(),
102 	};
103 	size_t insn_cnt = ARRAY_SIZE(insns);
104 	union bpf_attr attr;
105 	int prog_fd, err;
106 
107 	memset(&attr, 0, sizeof(attr));
108 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
109 	attr.insns = ptr_to_u64(insns);
110 	attr.insn_cnt = insn_cnt;
111 	attr.license = ptr_to_u64("GPL");
112 
113 	if (getrlimit(RLIMIT_MEMLOCK, &rlim_init))
114 		return false;
115 
116 	/* Drop the soft limit to zero. We maintain the hard limit to its
117 	 * current value, because lowering it would be a permanent operation
118 	 * for unprivileged users.
119 	 */
120 	rlim_cur_zero.rlim_max = rlim_init.rlim_max;
121 	if (setrlimit(RLIMIT_MEMLOCK, &rlim_cur_zero))
122 		return false;
123 
124 	/* Do not use bpf_prog_load() from libbpf here, because it calls
125 	 * bump_rlimit_memlock(), interfering with the current probe.
126 	 */
127 	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
128 	err = errno;
129 
130 	/* reset soft rlimit to its initial value */
131 	setrlimit(RLIMIT_MEMLOCK, &rlim_init);
132 
133 	if (prog_fd < 0)
134 		return err == EPERM;
135 
136 	close(prog_fd);
137 	return false;
138 }
139 
set_max_rlimit(void)140 void set_max_rlimit(void)
141 {
142 	struct rlimit rinf = { RLIM_INFINITY, RLIM_INFINITY };
143 
144 	if (known_to_need_rlimit())
145 		setrlimit(RLIMIT_MEMLOCK, &rinf);
146 }
147 
148 static int
mnt_fs(const char * target,const char * type,char * buff,size_t bufflen)149 mnt_fs(const char *target, const char *type, char *buff, size_t bufflen)
150 {
151 	bool bind_done = false;
152 
153 	while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
154 		if (errno != EINVAL || bind_done) {
155 			snprintf(buff, bufflen,
156 				 "mount --make-private %s failed: %s",
157 				 target, strerror(errno));
158 			return -1;
159 		}
160 
161 		if (mount(target, target, "none", MS_BIND, NULL)) {
162 			snprintf(buff, bufflen,
163 				 "mount --bind %s %s failed: %s",
164 				 target, target, strerror(errno));
165 			return -1;
166 		}
167 
168 		bind_done = true;
169 	}
170 
171 	if (mount(type, target, type, 0, "mode=0700")) {
172 		snprintf(buff, bufflen, "mount -t %s %s %s failed: %s",
173 			 type, type, target, strerror(errno));
174 		return -1;
175 	}
176 
177 	return 0;
178 }
179 
mount_tracefs(const char * target)180 int mount_tracefs(const char *target)
181 {
182 	char err_str[ERR_MAX_LEN];
183 	int err;
184 
185 	err = mnt_fs(target, "tracefs", err_str, ERR_MAX_LEN);
186 	if (err) {
187 		err_str[ERR_MAX_LEN - 1] = '\0';
188 		p_err("can't mount tracefs: %s", err_str);
189 	}
190 
191 	return err;
192 }
193 
open_obj_pinned(const char * path,bool quiet)194 int open_obj_pinned(const char *path, bool quiet)
195 {
196 	char *pname;
197 	int fd = -1;
198 
199 	pname = strdup(path);
200 	if (!pname) {
201 		if (!quiet)
202 			p_err("mem alloc failed");
203 		goto out_ret;
204 	}
205 
206 	fd = bpf_obj_get(pname);
207 	if (fd < 0) {
208 		if (!quiet)
209 			p_err("bpf obj get (%s): %s", pname,
210 			      errno == EACCES && !is_bpffs(dirname(pname)) ?
211 			    "directory not in bpf file system (bpffs)" :
212 			    strerror(errno));
213 		goto out_free;
214 	}
215 
216 out_free:
217 	free(pname);
218 out_ret:
219 	return fd;
220 }
221 
open_obj_pinned_any(const char * path,enum bpf_obj_type exp_type)222 int open_obj_pinned_any(const char *path, enum bpf_obj_type exp_type)
223 {
224 	enum bpf_obj_type type;
225 	int fd;
226 
227 	fd = open_obj_pinned(path, false);
228 	if (fd < 0)
229 		return -1;
230 
231 	type = get_fd_type(fd);
232 	if (type < 0) {
233 		close(fd);
234 		return type;
235 	}
236 	if (type != exp_type) {
237 		p_err("incorrect object type: %s", get_fd_type_name(type));
238 		close(fd);
239 		return -1;
240 	}
241 
242 	return fd;
243 }
244 
mount_bpffs_for_pin(const char * name)245 int mount_bpffs_for_pin(const char *name)
246 {
247 	char err_str[ERR_MAX_LEN];
248 	char *file;
249 	char *dir;
250 	int err = 0;
251 
252 	file = malloc(strlen(name) + 1);
253 	if (!file) {
254 		p_err("mem alloc failed");
255 		return -1;
256 	}
257 
258 	strcpy(file, name);
259 	dir = dirname(file);
260 
261 	if (is_bpffs(dir))
262 		/* nothing to do if already mounted */
263 		goto out_free;
264 
265 	if (block_mount) {
266 		p_err("no BPF file system found, not mounting it due to --nomount option");
267 		err = -1;
268 		goto out_free;
269 	}
270 
271 	err = mnt_fs(dir, "bpf", err_str, ERR_MAX_LEN);
272 	if (err) {
273 		err_str[ERR_MAX_LEN - 1] = '\0';
274 		p_err("can't mount BPF file system to pin the object (%s): %s",
275 		      name, err_str);
276 	}
277 
278 out_free:
279 	free(file);
280 	return err;
281 }
282 
do_pin_fd(int fd,const char * name)283 int do_pin_fd(int fd, const char *name)
284 {
285 	int err;
286 
287 	err = mount_bpffs_for_pin(name);
288 	if (err)
289 		return err;
290 
291 	err = bpf_obj_pin(fd, name);
292 	if (err)
293 		p_err("can't pin the object (%s): %s", name, strerror(errno));
294 
295 	return err;
296 }
297 
do_pin_any(int argc,char ** argv,int (* get_fd)(int *,char ***))298 int do_pin_any(int argc, char **argv, int (*get_fd)(int *, char ***))
299 {
300 	int err;
301 	int fd;
302 
303 	if (!REQ_ARGS(3))
304 		return -EINVAL;
305 
306 	fd = get_fd(&argc, &argv);
307 	if (fd < 0)
308 		return fd;
309 
310 	err = do_pin_fd(fd, *argv);
311 
312 	close(fd);
313 	return err;
314 }
315 
get_fd_type_name(enum bpf_obj_type type)316 const char *get_fd_type_name(enum bpf_obj_type type)
317 {
318 	static const char * const names[] = {
319 		[BPF_OBJ_UNKNOWN]	= "unknown",
320 		[BPF_OBJ_PROG]		= "prog",
321 		[BPF_OBJ_MAP]		= "map",
322 		[BPF_OBJ_LINK]		= "link",
323 	};
324 
325 	if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
326 		return names[BPF_OBJ_UNKNOWN];
327 
328 	return names[type];
329 }
330 
get_prog_full_name(const struct bpf_prog_info * prog_info,int prog_fd,char * name_buff,size_t buff_len)331 void get_prog_full_name(const struct bpf_prog_info *prog_info, int prog_fd,
332 			char *name_buff, size_t buff_len)
333 {
334 	const char *prog_name = prog_info->name;
335 	const struct btf_type *func_type;
336 	const struct bpf_func_info finfo = {};
337 	struct bpf_prog_info info = {};
338 	__u32 info_len = sizeof(info);
339 	struct btf *prog_btf = NULL;
340 
341 	if (buff_len <= BPF_OBJ_NAME_LEN ||
342 	    strlen(prog_info->name) < BPF_OBJ_NAME_LEN - 1)
343 		goto copy_name;
344 
345 	if (!prog_info->btf_id || prog_info->nr_func_info == 0)
346 		goto copy_name;
347 
348 	info.nr_func_info = 1;
349 	info.func_info_rec_size = prog_info->func_info_rec_size;
350 	if (info.func_info_rec_size > sizeof(finfo))
351 		info.func_info_rec_size = sizeof(finfo);
352 	info.func_info = ptr_to_u64(&finfo);
353 
354 	if (bpf_obj_get_info_by_fd(prog_fd, &info, &info_len))
355 		goto copy_name;
356 
357 	prog_btf = btf__load_from_kernel_by_id(info.btf_id);
358 	if (!prog_btf)
359 		goto copy_name;
360 
361 	func_type = btf__type_by_id(prog_btf, finfo.type_id);
362 	if (!func_type || !btf_is_func(func_type))
363 		goto copy_name;
364 
365 	prog_name = btf__name_by_offset(prog_btf, func_type->name_off);
366 
367 copy_name:
368 	snprintf(name_buff, buff_len, "%s", prog_name);
369 
370 	if (prog_btf)
371 		btf__free(prog_btf);
372 }
373 
get_fd_type(int fd)374 int get_fd_type(int fd)
375 {
376 	char path[PATH_MAX];
377 	char buf[512];
378 	ssize_t n;
379 
380 	snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
381 
382 	n = readlink(path, buf, sizeof(buf));
383 	if (n < 0) {
384 		p_err("can't read link type: %s", strerror(errno));
385 		return -1;
386 	}
387 	if (n == sizeof(path)) {
388 		p_err("can't read link type: path too long!");
389 		return -1;
390 	}
391 
392 	if (strstr(buf, "bpf-map"))
393 		return BPF_OBJ_MAP;
394 	else if (strstr(buf, "bpf-prog"))
395 		return BPF_OBJ_PROG;
396 	else if (strstr(buf, "bpf-link"))
397 		return BPF_OBJ_LINK;
398 
399 	return BPF_OBJ_UNKNOWN;
400 }
401 
get_fdinfo(int fd,const char * key)402 char *get_fdinfo(int fd, const char *key)
403 {
404 	char path[PATH_MAX];
405 	char *line = NULL;
406 	size_t line_n = 0;
407 	ssize_t n;
408 	FILE *fdi;
409 
410 	snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
411 
412 	fdi = fopen(path, "r");
413 	if (!fdi)
414 		return NULL;
415 
416 	while ((n = getline(&line, &line_n, fdi)) > 0) {
417 		char *value;
418 		int len;
419 
420 		if (!strstr(line, key))
421 			continue;
422 
423 		fclose(fdi);
424 
425 		value = strchr(line, '\t');
426 		if (!value || !value[1]) {
427 			free(line);
428 			return NULL;
429 		}
430 		value++;
431 
432 		len = strlen(value);
433 		memmove(line, value, len);
434 		line[len - 1] = '\0';
435 
436 		return line;
437 	}
438 
439 	free(line);
440 	fclose(fdi);
441 	return NULL;
442 }
443 
print_data_json(uint8_t * data,size_t len)444 void print_data_json(uint8_t *data, size_t len)
445 {
446 	unsigned int i;
447 
448 	jsonw_start_array(json_wtr);
449 	for (i = 0; i < len; i++)
450 		jsonw_printf(json_wtr, "%d", data[i]);
451 	jsonw_end_array(json_wtr);
452 }
453 
print_hex_data_json(uint8_t * data,size_t len)454 void print_hex_data_json(uint8_t *data, size_t len)
455 {
456 	unsigned int i;
457 
458 	jsonw_start_array(json_wtr);
459 	for (i = 0; i < len; i++)
460 		jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
461 	jsonw_end_array(json_wtr);
462 }
463 
464 /* extra params for nftw cb */
465 static struct hashmap *build_fn_table;
466 static enum bpf_obj_type build_fn_type;
467 
do_build_table_cb(const char * fpath,const struct stat * sb,int typeflag,struct FTW * ftwbuf)468 static int do_build_table_cb(const char *fpath, const struct stat *sb,
469 			     int typeflag, struct FTW *ftwbuf)
470 {
471 	struct bpf_prog_info pinned_info;
472 	__u32 len = sizeof(pinned_info);
473 	enum bpf_obj_type objtype;
474 	int fd, err = 0;
475 	char *path;
476 
477 	if (typeflag != FTW_F)
478 		goto out_ret;
479 
480 	fd = open_obj_pinned(fpath, true);
481 	if (fd < 0)
482 		goto out_ret;
483 
484 	objtype = get_fd_type(fd);
485 	if (objtype != build_fn_type)
486 		goto out_close;
487 
488 	memset(&pinned_info, 0, sizeof(pinned_info));
489 	if (bpf_obj_get_info_by_fd(fd, &pinned_info, &len))
490 		goto out_close;
491 
492 	path = strdup(fpath);
493 	if (!path) {
494 		err = -1;
495 		goto out_close;
496 	}
497 
498 	err = hashmap__append(build_fn_table, u32_as_hash_field(pinned_info.id), path);
499 	if (err) {
500 		p_err("failed to append entry to hashmap for ID %u, path '%s': %s",
501 		      pinned_info.id, path, strerror(errno));
502 		free(path);
503 		goto out_close;
504 	}
505 
506 out_close:
507 	close(fd);
508 out_ret:
509 	return err;
510 }
511 
build_pinned_obj_table(struct hashmap * tab,enum bpf_obj_type type)512 int build_pinned_obj_table(struct hashmap *tab,
513 			   enum bpf_obj_type type)
514 {
515 	struct mntent *mntent = NULL;
516 	FILE *mntfile = NULL;
517 	int flags = FTW_PHYS;
518 	int nopenfd = 16;
519 	int err = 0;
520 
521 	mntfile = setmntent("/proc/mounts", "r");
522 	if (!mntfile)
523 		return -1;
524 
525 	build_fn_table = tab;
526 	build_fn_type = type;
527 
528 	while ((mntent = getmntent(mntfile))) {
529 		char *path = mntent->mnt_dir;
530 
531 		if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
532 			continue;
533 		err = nftw(path, do_build_table_cb, nopenfd, flags);
534 		if (err)
535 			break;
536 	}
537 	fclose(mntfile);
538 	return err;
539 }
540 
delete_pinned_obj_table(struct hashmap * map)541 void delete_pinned_obj_table(struct hashmap *map)
542 {
543 	struct hashmap_entry *entry;
544 	size_t bkt;
545 
546 	if (!map)
547 		return;
548 
549 	hashmap__for_each_entry(map, entry, bkt)
550 		free(entry->value);
551 
552 	hashmap__free(map);
553 }
554 
get_page_size(void)555 unsigned int get_page_size(void)
556 {
557 	static int result;
558 
559 	if (!result)
560 		result = getpagesize();
561 	return result;
562 }
563 
get_possible_cpus(void)564 unsigned int get_possible_cpus(void)
565 {
566 	int cpus = libbpf_num_possible_cpus();
567 
568 	if (cpus < 0) {
569 		p_err("Can't get # of possible cpus: %s", strerror(-cpus));
570 		exit(-1);
571 	}
572 	return cpus;
573 }
574 
575 static char *
ifindex_to_name_ns(__u32 ifindex,__u32 ns_dev,__u32 ns_ino,char * buf)576 ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf)
577 {
578 	struct stat st;
579 	int err;
580 
581 	err = stat("/proc/self/ns/net", &st);
582 	if (err) {
583 		p_err("Can't stat /proc/self: %s", strerror(errno));
584 		return NULL;
585 	}
586 
587 	if (st.st_dev != ns_dev || st.st_ino != ns_ino)
588 		return NULL;
589 
590 	return if_indextoname(ifindex, buf);
591 }
592 
read_sysfs_hex_int(char * path)593 static int read_sysfs_hex_int(char *path)
594 {
595 	char vendor_id_buf[8];
596 	int len;
597 	int fd;
598 
599 	fd = open(path, O_RDONLY);
600 	if (fd < 0) {
601 		p_err("Can't open %s: %s", path, strerror(errno));
602 		return -1;
603 	}
604 
605 	len = read(fd, vendor_id_buf, sizeof(vendor_id_buf));
606 	close(fd);
607 	if (len < 0) {
608 		p_err("Can't read %s: %s", path, strerror(errno));
609 		return -1;
610 	}
611 	if (len >= (int)sizeof(vendor_id_buf)) {
612 		p_err("Value in %s too long", path);
613 		return -1;
614 	}
615 
616 	vendor_id_buf[len] = 0;
617 
618 	return strtol(vendor_id_buf, NULL, 0);
619 }
620 
read_sysfs_netdev_hex_int(char * devname,const char * entry_name)621 static int read_sysfs_netdev_hex_int(char *devname, const char *entry_name)
622 {
623 	char full_path[64];
624 
625 	snprintf(full_path, sizeof(full_path), "/sys/class/net/%s/device/%s",
626 		 devname, entry_name);
627 
628 	return read_sysfs_hex_int(full_path);
629 }
630 
631 const char *
ifindex_to_bfd_params(__u32 ifindex,__u64 ns_dev,__u64 ns_ino,const char ** opt)632 ifindex_to_bfd_params(__u32 ifindex, __u64 ns_dev, __u64 ns_ino,
633 		      const char **opt)
634 {
635 	char devname[IF_NAMESIZE];
636 	int vendor_id;
637 	int device_id;
638 
639 	if (!ifindex_to_name_ns(ifindex, ns_dev, ns_ino, devname)) {
640 		p_err("Can't get net device name for ifindex %d: %s", ifindex,
641 		      strerror(errno));
642 		return NULL;
643 	}
644 
645 	vendor_id = read_sysfs_netdev_hex_int(devname, "vendor");
646 	if (vendor_id < 0) {
647 		p_err("Can't get device vendor id for %s", devname);
648 		return NULL;
649 	}
650 
651 	switch (vendor_id) {
652 	case 0x19ee:
653 		device_id = read_sysfs_netdev_hex_int(devname, "device");
654 		if (device_id != 0x4000 &&
655 		    device_id != 0x6000 &&
656 		    device_id != 0x6003)
657 			p_info("Unknown NFP device ID, assuming it is NFP-6xxx arch");
658 		*opt = "ctx4";
659 		return "NFP-6xxx";
660 	default:
661 		p_err("Can't get bfd arch name for device vendor id 0x%04x",
662 		      vendor_id);
663 		return NULL;
664 	}
665 }
666 
print_dev_plain(__u32 ifindex,__u64 ns_dev,__u64 ns_inode)667 void print_dev_plain(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
668 {
669 	char name[IF_NAMESIZE];
670 
671 	if (!ifindex)
672 		return;
673 
674 	printf("  offloaded_to ");
675 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
676 		printf("%s", name);
677 	else
678 		printf("ifindex %u ns_dev %llu ns_ino %llu",
679 		       ifindex, ns_dev, ns_inode);
680 }
681 
print_dev_json(__u32 ifindex,__u64 ns_dev,__u64 ns_inode)682 void print_dev_json(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
683 {
684 	char name[IF_NAMESIZE];
685 
686 	if (!ifindex)
687 		return;
688 
689 	jsonw_name(json_wtr, "dev");
690 	jsonw_start_object(json_wtr);
691 	jsonw_uint_field(json_wtr, "ifindex", ifindex);
692 	jsonw_uint_field(json_wtr, "ns_dev", ns_dev);
693 	jsonw_uint_field(json_wtr, "ns_inode", ns_inode);
694 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
695 		jsonw_string_field(json_wtr, "ifname", name);
696 	jsonw_end_object(json_wtr);
697 }
698 
parse_u32_arg(int * argc,char *** argv,__u32 * val,const char * what)699 int parse_u32_arg(int *argc, char ***argv, __u32 *val, const char *what)
700 {
701 	char *endptr;
702 
703 	NEXT_ARGP();
704 
705 	if (*val) {
706 		p_err("%s already specified", what);
707 		return -1;
708 	}
709 
710 	*val = strtoul(**argv, &endptr, 0);
711 	if (*endptr) {
712 		p_err("can't parse %s as %s", **argv, what);
713 		return -1;
714 	}
715 	NEXT_ARGP();
716 
717 	return 0;
718 }
719 
720 int __printf(2, 0)
print_all_levels(__maybe_unused enum libbpf_print_level level,const char * format,va_list args)721 print_all_levels(__maybe_unused enum libbpf_print_level level,
722 		 const char *format, va_list args)
723 {
724 	return vfprintf(stderr, format, args);
725 }
726 
prog_fd_by_nametag(void * nametag,int ** fds,bool tag)727 static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)
728 {
729 	char prog_name[MAX_PROG_FULL_NAME];
730 	unsigned int id = 0;
731 	int fd, nb_fds = 0;
732 	void *tmp;
733 	int err;
734 
735 	while (true) {
736 		struct bpf_prog_info info = {};
737 		__u32 len = sizeof(info);
738 
739 		err = bpf_prog_get_next_id(id, &id);
740 		if (err) {
741 			if (errno != ENOENT) {
742 				p_err("%s", strerror(errno));
743 				goto err_close_fds;
744 			}
745 			return nb_fds;
746 		}
747 
748 		fd = bpf_prog_get_fd_by_id(id);
749 		if (fd < 0) {
750 			p_err("can't get prog by id (%u): %s",
751 			      id, strerror(errno));
752 			goto err_close_fds;
753 		}
754 
755 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
756 		if (err) {
757 			p_err("can't get prog info (%u): %s",
758 			      id, strerror(errno));
759 			goto err_close_fd;
760 		}
761 
762 		if (tag && memcmp(nametag, info.tag, BPF_TAG_SIZE)) {
763 			close(fd);
764 			continue;
765 		}
766 
767 		if (!tag) {
768 			get_prog_full_name(&info, fd, prog_name,
769 					   sizeof(prog_name));
770 			if (strncmp(nametag, prog_name, sizeof(prog_name))) {
771 				close(fd);
772 				continue;
773 			}
774 		}
775 
776 		if (nb_fds > 0) {
777 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
778 			if (!tmp) {
779 				p_err("failed to realloc");
780 				goto err_close_fd;
781 			}
782 			*fds = tmp;
783 		}
784 		(*fds)[nb_fds++] = fd;
785 	}
786 
787 err_close_fd:
788 	close(fd);
789 err_close_fds:
790 	while (--nb_fds >= 0)
791 		close((*fds)[nb_fds]);
792 	return -1;
793 }
794 
prog_parse_fds(int * argc,char *** argv,int ** fds)795 int prog_parse_fds(int *argc, char ***argv, int **fds)
796 {
797 	if (is_prefix(**argv, "id")) {
798 		unsigned int id;
799 		char *endptr;
800 
801 		NEXT_ARGP();
802 
803 		id = strtoul(**argv, &endptr, 0);
804 		if (*endptr) {
805 			p_err("can't parse %s as ID", **argv);
806 			return -1;
807 		}
808 		NEXT_ARGP();
809 
810 		(*fds)[0] = bpf_prog_get_fd_by_id(id);
811 		if ((*fds)[0] < 0) {
812 			p_err("get by id (%u): %s", id, strerror(errno));
813 			return -1;
814 		}
815 		return 1;
816 	} else if (is_prefix(**argv, "tag")) {
817 		unsigned char tag[BPF_TAG_SIZE];
818 
819 		NEXT_ARGP();
820 
821 		if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
822 			   tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
823 		    != BPF_TAG_SIZE) {
824 			p_err("can't parse tag");
825 			return -1;
826 		}
827 		NEXT_ARGP();
828 
829 		return prog_fd_by_nametag(tag, fds, true);
830 	} else if (is_prefix(**argv, "name")) {
831 		char *name;
832 
833 		NEXT_ARGP();
834 
835 		name = **argv;
836 		if (strlen(name) > MAX_PROG_FULL_NAME - 1) {
837 			p_err("can't parse name");
838 			return -1;
839 		}
840 		NEXT_ARGP();
841 
842 		return prog_fd_by_nametag(name, fds, false);
843 	} else if (is_prefix(**argv, "pinned")) {
844 		char *path;
845 
846 		NEXT_ARGP();
847 
848 		path = **argv;
849 		NEXT_ARGP();
850 
851 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_PROG);
852 		if ((*fds)[0] < 0)
853 			return -1;
854 		return 1;
855 	}
856 
857 	p_err("expected 'id', 'tag', 'name' or 'pinned', got: '%s'?", **argv);
858 	return -1;
859 }
860 
prog_parse_fd(int * argc,char *** argv)861 int prog_parse_fd(int *argc, char ***argv)
862 {
863 	int *fds = NULL;
864 	int nb_fds, fd;
865 
866 	fds = malloc(sizeof(int));
867 	if (!fds) {
868 		p_err("mem alloc failed");
869 		return -1;
870 	}
871 	nb_fds = prog_parse_fds(argc, argv, &fds);
872 	if (nb_fds != 1) {
873 		if (nb_fds > 1) {
874 			p_err("several programs match this handle");
875 			while (nb_fds--)
876 				close(fds[nb_fds]);
877 		}
878 		fd = -1;
879 		goto exit_free;
880 	}
881 
882 	fd = fds[0];
883 exit_free:
884 	free(fds);
885 	return fd;
886 }
887 
map_fd_by_name(char * name,int ** fds)888 static int map_fd_by_name(char *name, int **fds)
889 {
890 	unsigned int id = 0;
891 	int fd, nb_fds = 0;
892 	void *tmp;
893 	int err;
894 
895 	while (true) {
896 		struct bpf_map_info info = {};
897 		__u32 len = sizeof(info);
898 
899 		err = bpf_map_get_next_id(id, &id);
900 		if (err) {
901 			if (errno != ENOENT) {
902 				p_err("%s", strerror(errno));
903 				goto err_close_fds;
904 			}
905 			return nb_fds;
906 		}
907 
908 		fd = bpf_map_get_fd_by_id(id);
909 		if (fd < 0) {
910 			p_err("can't get map by id (%u): %s",
911 			      id, strerror(errno));
912 			goto err_close_fds;
913 		}
914 
915 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
916 		if (err) {
917 			p_err("can't get map info (%u): %s",
918 			      id, strerror(errno));
919 			goto err_close_fd;
920 		}
921 
922 		if (strncmp(name, info.name, BPF_OBJ_NAME_LEN)) {
923 			close(fd);
924 			continue;
925 		}
926 
927 		if (nb_fds > 0) {
928 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
929 			if (!tmp) {
930 				p_err("failed to realloc");
931 				goto err_close_fd;
932 			}
933 			*fds = tmp;
934 		}
935 		(*fds)[nb_fds++] = fd;
936 	}
937 
938 err_close_fd:
939 	close(fd);
940 err_close_fds:
941 	while (--nb_fds >= 0)
942 		close((*fds)[nb_fds]);
943 	return -1;
944 }
945 
map_parse_fds(int * argc,char *** argv,int ** fds)946 int map_parse_fds(int *argc, char ***argv, int **fds)
947 {
948 	if (is_prefix(**argv, "id")) {
949 		unsigned int id;
950 		char *endptr;
951 
952 		NEXT_ARGP();
953 
954 		id = strtoul(**argv, &endptr, 0);
955 		if (*endptr) {
956 			p_err("can't parse %s as ID", **argv);
957 			return -1;
958 		}
959 		NEXT_ARGP();
960 
961 		(*fds)[0] = bpf_map_get_fd_by_id(id);
962 		if ((*fds)[0] < 0) {
963 			p_err("get map by id (%u): %s", id, strerror(errno));
964 			return -1;
965 		}
966 		return 1;
967 	} else if (is_prefix(**argv, "name")) {
968 		char *name;
969 
970 		NEXT_ARGP();
971 
972 		name = **argv;
973 		if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
974 			p_err("can't parse name");
975 			return -1;
976 		}
977 		NEXT_ARGP();
978 
979 		return map_fd_by_name(name, fds);
980 	} else if (is_prefix(**argv, "pinned")) {
981 		char *path;
982 
983 		NEXT_ARGP();
984 
985 		path = **argv;
986 		NEXT_ARGP();
987 
988 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_MAP);
989 		if ((*fds)[0] < 0)
990 			return -1;
991 		return 1;
992 	}
993 
994 	p_err("expected 'id', 'name' or 'pinned', got: '%s'?", **argv);
995 	return -1;
996 }
997 
map_parse_fd(int * argc,char *** argv)998 int map_parse_fd(int *argc, char ***argv)
999 {
1000 	int *fds = NULL;
1001 	int nb_fds, fd;
1002 
1003 	fds = malloc(sizeof(int));
1004 	if (!fds) {
1005 		p_err("mem alloc failed");
1006 		return -1;
1007 	}
1008 	nb_fds = map_parse_fds(argc, argv, &fds);
1009 	if (nb_fds != 1) {
1010 		if (nb_fds > 1) {
1011 			p_err("several maps match this handle");
1012 			while (nb_fds--)
1013 				close(fds[nb_fds]);
1014 		}
1015 		fd = -1;
1016 		goto exit_free;
1017 	}
1018 
1019 	fd = fds[0];
1020 exit_free:
1021 	free(fds);
1022 	return fd;
1023 }
1024 
map_parse_fd_and_info(int * argc,char *** argv,void * info,__u32 * info_len)1025 int map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
1026 {
1027 	int err;
1028 	int fd;
1029 
1030 	fd = map_parse_fd(argc, argv);
1031 	if (fd < 0)
1032 		return -1;
1033 
1034 	err = bpf_obj_get_info_by_fd(fd, info, info_len);
1035 	if (err) {
1036 		p_err("can't get map info: %s", strerror(errno));
1037 		close(fd);
1038 		return err;
1039 	}
1040 
1041 	return fd;
1042 }
1043 
hash_fn_for_key_as_id(const void * key,void * ctx)1044 size_t hash_fn_for_key_as_id(const void *key, void *ctx)
1045 {
1046 	return (size_t)key;
1047 }
1048 
equal_fn_for_key_as_id(const void * k1,const void * k2,void * ctx)1049 bool equal_fn_for_key_as_id(const void *k1, const void *k2, void *ctx)
1050 {
1051 	return k1 == k2;
1052 }
1053 
bpf_attach_type_input_str(enum bpf_attach_type t)1054 const char *bpf_attach_type_input_str(enum bpf_attach_type t)
1055 {
1056 	switch (t) {
1057 	case BPF_CGROUP_INET_INGRESS:		return "ingress";
1058 	case BPF_CGROUP_INET_EGRESS:		return "egress";
1059 	case BPF_CGROUP_INET_SOCK_CREATE:	return "sock_create";
1060 	case BPF_CGROUP_INET_SOCK_RELEASE:	return "sock_release";
1061 	case BPF_CGROUP_SOCK_OPS:		return "sock_ops";
1062 	case BPF_CGROUP_DEVICE:			return "device";
1063 	case BPF_CGROUP_INET4_BIND:		return "bind4";
1064 	case BPF_CGROUP_INET6_BIND:		return "bind6";
1065 	case BPF_CGROUP_INET4_CONNECT:		return "connect4";
1066 	case BPF_CGROUP_INET6_CONNECT:		return "connect6";
1067 	case BPF_CGROUP_INET4_POST_BIND:	return "post_bind4";
1068 	case BPF_CGROUP_INET6_POST_BIND:	return "post_bind6";
1069 	case BPF_CGROUP_INET4_GETPEERNAME:	return "getpeername4";
1070 	case BPF_CGROUP_INET6_GETPEERNAME:	return "getpeername6";
1071 	case BPF_CGROUP_INET4_GETSOCKNAME:	return "getsockname4";
1072 	case BPF_CGROUP_INET6_GETSOCKNAME:	return "getsockname6";
1073 	case BPF_CGROUP_UDP4_SENDMSG:		return "sendmsg4";
1074 	case BPF_CGROUP_UDP6_SENDMSG:		return "sendmsg6";
1075 	case BPF_CGROUP_SYSCTL:			return "sysctl";
1076 	case BPF_CGROUP_UDP4_RECVMSG:		return "recvmsg4";
1077 	case BPF_CGROUP_UDP6_RECVMSG:		return "recvmsg6";
1078 	case BPF_CGROUP_GETSOCKOPT:		return "getsockopt";
1079 	case BPF_CGROUP_SETSOCKOPT:		return "setsockopt";
1080 	case BPF_TRACE_RAW_TP:			return "raw_tp";
1081 	case BPF_TRACE_FENTRY:			return "fentry";
1082 	case BPF_TRACE_FEXIT:			return "fexit";
1083 	case BPF_MODIFY_RETURN:			return "mod_ret";
1084 	case BPF_SK_REUSEPORT_SELECT:		return "sk_skb_reuseport_select";
1085 	case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:	return "sk_skb_reuseport_select_or_migrate";
1086 	default:	return libbpf_bpf_attach_type_str(t);
1087 	}
1088 }
1089