xref: /openbmc/linux/tools/bpf/bpftool/common.c (revision 0a73d21e)
1 /*
2  * Copyright (C) 2017 Netronome Systems, Inc.
3  *
4  * This software is dual licensed under the GNU General License Version 2,
5  * June 1991 as shown in the file COPYING in the top-level directory of this
6  * source tree or the BSD 2-Clause License provided below.  You have the
7  * option to license this software under the complete terms of either license.
8  *
9  * The BSD 2-Clause License:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      1. Redistributions of source code must retain the above
16  *         copyright notice, this list of conditions and the following
17  *         disclaimer.
18  *
19  *      2. Redistributions in binary form must reproduce the above
20  *         copyright notice, this list of conditions and the following
21  *         disclaimer in the documentation and/or other materials
22  *         provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33 
34 /* Author: Jakub Kicinski <kubakici@wp.pl> */
35 
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <fts.h>
39 #include <libgen.h>
40 #include <mntent.h>
41 #include <stdbool.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <linux/limits.h>
47 #include <linux/magic.h>
48 #include <net/if.h>
49 #include <sys/mount.h>
50 #include <sys/stat.h>
51 #include <sys/types.h>
52 #include <sys/vfs.h>
53 
54 #include <bpf.h>
55 
56 #include "main.h"
57 
58 void p_err(const char *fmt, ...)
59 {
60 	va_list ap;
61 
62 	va_start(ap, fmt);
63 	if (json_output) {
64 		jsonw_start_object(json_wtr);
65 		jsonw_name(json_wtr, "error");
66 		jsonw_vprintf_enquote(json_wtr, fmt, ap);
67 		jsonw_end_object(json_wtr);
68 	} else {
69 		fprintf(stderr, "Error: ");
70 		vfprintf(stderr, fmt, ap);
71 		fprintf(stderr, "\n");
72 	}
73 	va_end(ap);
74 }
75 
76 void p_info(const char *fmt, ...)
77 {
78 	va_list ap;
79 
80 	if (json_output)
81 		return;
82 
83 	va_start(ap, fmt);
84 	vfprintf(stderr, fmt, ap);
85 	fprintf(stderr, "\n");
86 	va_end(ap);
87 }
88 
89 static bool is_bpffs(char *path)
90 {
91 	struct statfs st_fs;
92 
93 	if (statfs(path, &st_fs) < 0)
94 		return false;
95 
96 	return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
97 }
98 
99 static int mnt_bpffs(const char *target, char *buff, size_t bufflen)
100 {
101 	bool bind_done = false;
102 
103 	while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
104 		if (errno != EINVAL || bind_done) {
105 			snprintf(buff, bufflen,
106 				 "mount --make-private %s failed: %s",
107 				 target, strerror(errno));
108 			return -1;
109 		}
110 
111 		if (mount(target, target, "none", MS_BIND, NULL)) {
112 			snprintf(buff, bufflen,
113 				 "mount --bind %s %s failed: %s",
114 				 target, target, strerror(errno));
115 			return -1;
116 		}
117 
118 		bind_done = true;
119 	}
120 
121 	if (mount("bpf", target, "bpf", 0, "mode=0700")) {
122 		snprintf(buff, bufflen, "mount -t bpf bpf %s failed: %s",
123 			 target, strerror(errno));
124 		return -1;
125 	}
126 
127 	return 0;
128 }
129 
130 int open_obj_pinned(char *path)
131 {
132 	int fd;
133 
134 	fd = bpf_obj_get(path);
135 	if (fd < 0) {
136 		p_err("bpf obj get (%s): %s", path,
137 		      errno == EACCES && !is_bpffs(dirname(path)) ?
138 		    "directory not in bpf file system (bpffs)" :
139 		    strerror(errno));
140 		return -1;
141 	}
142 
143 	return fd;
144 }
145 
146 int open_obj_pinned_any(char *path, enum bpf_obj_type exp_type)
147 {
148 	enum bpf_obj_type type;
149 	int fd;
150 
151 	fd = open_obj_pinned(path);
152 	if (fd < 0)
153 		return -1;
154 
155 	type = get_fd_type(fd);
156 	if (type < 0) {
157 		close(fd);
158 		return type;
159 	}
160 	if (type != exp_type) {
161 		p_err("incorrect object type: %s", get_fd_type_name(type));
162 		close(fd);
163 		return -1;
164 	}
165 
166 	return fd;
167 }
168 
169 int do_pin_fd(int fd, const char *name)
170 {
171 	char err_str[ERR_MAX_LEN];
172 	char *file;
173 	char *dir;
174 	int err = 0;
175 
176 	err = bpf_obj_pin(fd, name);
177 	if (!err)
178 		goto out;
179 
180 	file = malloc(strlen(name) + 1);
181 	strcpy(file, name);
182 	dir = dirname(file);
183 
184 	if (errno != EPERM || is_bpffs(dir)) {
185 		p_err("can't pin the object (%s): %s", name, strerror(errno));
186 		goto out_free;
187 	}
188 
189 	/* Attempt to mount bpffs, then retry pinning. */
190 	err = mnt_bpffs(dir, err_str, ERR_MAX_LEN);
191 	if (!err) {
192 		err = bpf_obj_pin(fd, name);
193 		if (err)
194 			p_err("can't pin the object (%s): %s", name,
195 			      strerror(errno));
196 	} else {
197 		err_str[ERR_MAX_LEN - 1] = '\0';
198 		p_err("can't mount BPF file system to pin the object (%s): %s",
199 		      name, err_str);
200 	}
201 
202 out_free:
203 	free(file);
204 out:
205 	return err;
206 }
207 
208 int do_pin_any(int argc, char **argv, int (*get_fd_by_id)(__u32))
209 {
210 	unsigned int id;
211 	char *endptr;
212 	int err;
213 	int fd;
214 
215 	if (!is_prefix(*argv, "id")) {
216 		p_err("expected 'id' got %s", *argv);
217 		return -1;
218 	}
219 	NEXT_ARG();
220 
221 	id = strtoul(*argv, &endptr, 0);
222 	if (*endptr) {
223 		p_err("can't parse %s as ID", *argv);
224 		return -1;
225 	}
226 	NEXT_ARG();
227 
228 	if (argc != 1)
229 		usage();
230 
231 	fd = get_fd_by_id(id);
232 	if (fd < 0) {
233 		p_err("can't get prog by id (%u): %s", id, strerror(errno));
234 		return -1;
235 	}
236 
237 	err = do_pin_fd(fd, *argv);
238 
239 	close(fd);
240 	return err;
241 }
242 
243 const char *get_fd_type_name(enum bpf_obj_type type)
244 {
245 	static const char * const names[] = {
246 		[BPF_OBJ_UNKNOWN]	= "unknown",
247 		[BPF_OBJ_PROG]		= "prog",
248 		[BPF_OBJ_MAP]		= "map",
249 	};
250 
251 	if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
252 		return names[BPF_OBJ_UNKNOWN];
253 
254 	return names[type];
255 }
256 
257 int get_fd_type(int fd)
258 {
259 	char path[PATH_MAX];
260 	char buf[512];
261 	ssize_t n;
262 
263 	snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), fd);
264 
265 	n = readlink(path, buf, sizeof(buf));
266 	if (n < 0) {
267 		p_err("can't read link type: %s", strerror(errno));
268 		return -1;
269 	}
270 	if (n == sizeof(path)) {
271 		p_err("can't read link type: path too long!");
272 		return -1;
273 	}
274 
275 	if (strstr(buf, "bpf-map"))
276 		return BPF_OBJ_MAP;
277 	else if (strstr(buf, "bpf-prog"))
278 		return BPF_OBJ_PROG;
279 
280 	return BPF_OBJ_UNKNOWN;
281 }
282 
283 char *get_fdinfo(int fd, const char *key)
284 {
285 	char path[PATH_MAX];
286 	char *line = NULL;
287 	size_t line_n = 0;
288 	ssize_t n;
289 	FILE *fdi;
290 
291 	snprintf(path, sizeof(path), "/proc/%d/fdinfo/%d", getpid(), fd);
292 
293 	fdi = fopen(path, "r");
294 	if (!fdi) {
295 		p_err("can't open fdinfo: %s", strerror(errno));
296 		return NULL;
297 	}
298 
299 	while ((n = getline(&line, &line_n, fdi))) {
300 		char *value;
301 		int len;
302 
303 		if (!strstr(line, key))
304 			continue;
305 
306 		fclose(fdi);
307 
308 		value = strchr(line, '\t');
309 		if (!value || !value[1]) {
310 			p_err("malformed fdinfo!?");
311 			free(line);
312 			return NULL;
313 		}
314 		value++;
315 
316 		len = strlen(value);
317 		memmove(line, value, len);
318 		line[len - 1] = '\0';
319 
320 		return line;
321 	}
322 
323 	p_err("key '%s' not found in fdinfo", key);
324 	free(line);
325 	fclose(fdi);
326 	return NULL;
327 }
328 
329 void print_hex_data_json(uint8_t *data, size_t len)
330 {
331 	unsigned int i;
332 
333 	jsonw_start_array(json_wtr);
334 	for (i = 0; i < len; i++)
335 		jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
336 	jsonw_end_array(json_wtr);
337 }
338 
339 int build_pinned_obj_table(struct pinned_obj_table *tab,
340 			   enum bpf_obj_type type)
341 {
342 	struct bpf_prog_info pinned_info = {};
343 	struct pinned_obj *obj_node = NULL;
344 	__u32 len = sizeof(pinned_info);
345 	struct mntent *mntent = NULL;
346 	enum bpf_obj_type objtype;
347 	FILE *mntfile = NULL;
348 	FTSENT *ftse = NULL;
349 	FTS *fts = NULL;
350 	int fd, err;
351 
352 	mntfile = setmntent("/proc/mounts", "r");
353 	if (!mntfile)
354 		return -1;
355 
356 	while ((mntent = getmntent(mntfile))) {
357 		char *path[] = { mntent->mnt_dir, NULL };
358 
359 		if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
360 			continue;
361 
362 		fts = fts_open(path, 0, NULL);
363 		if (!fts)
364 			continue;
365 
366 		while ((ftse = fts_read(fts))) {
367 			if (!(ftse->fts_info & FTS_F))
368 				continue;
369 			fd = open_obj_pinned(ftse->fts_path);
370 			if (fd < 0)
371 				continue;
372 
373 			objtype = get_fd_type(fd);
374 			if (objtype != type) {
375 				close(fd);
376 				continue;
377 			}
378 			memset(&pinned_info, 0, sizeof(pinned_info));
379 			err = bpf_obj_get_info_by_fd(fd, &pinned_info, &len);
380 			if (err) {
381 				close(fd);
382 				continue;
383 			}
384 
385 			obj_node = malloc(sizeof(*obj_node));
386 			if (!obj_node) {
387 				close(fd);
388 				fts_close(fts);
389 				fclose(mntfile);
390 				return -1;
391 			}
392 
393 			memset(obj_node, 0, sizeof(*obj_node));
394 			obj_node->id = pinned_info.id;
395 			obj_node->path = strdup(ftse->fts_path);
396 			hash_add(tab->table, &obj_node->hash, obj_node->id);
397 
398 			close(fd);
399 		}
400 		fts_close(fts);
401 	}
402 	fclose(mntfile);
403 	return 0;
404 }
405 
406 void delete_pinned_obj_table(struct pinned_obj_table *tab)
407 {
408 	struct pinned_obj *obj;
409 	struct hlist_node *tmp;
410 	unsigned int bkt;
411 
412 	hash_for_each_safe(tab->table, bkt, tmp, obj, hash) {
413 		hash_del(&obj->hash);
414 		free(obj->path);
415 		free(obj);
416 	}
417 }
418 
419 static char *
420 ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf)
421 {
422 	struct stat st;
423 	int err;
424 
425 	err = stat("/proc/self/ns/net", &st);
426 	if (err) {
427 		p_err("Can't stat /proc/self: %s", strerror(errno));
428 		return NULL;
429 	}
430 
431 	if (st.st_dev != ns_dev || st.st_ino != ns_ino)
432 		return NULL;
433 
434 	return if_indextoname(ifindex, buf);
435 }
436 
437 static int read_sysfs_hex_int(char *path)
438 {
439 	char vendor_id_buf[8];
440 	int len;
441 	int fd;
442 
443 	fd = open(path, O_RDONLY);
444 	if (fd < 0) {
445 		p_err("Can't open %s: %s", path, strerror(errno));
446 		return -1;
447 	}
448 
449 	len = read(fd, vendor_id_buf, sizeof(vendor_id_buf));
450 	close(fd);
451 	if (len < 0) {
452 		p_err("Can't read %s: %s", path, strerror(errno));
453 		return -1;
454 	}
455 	if (len >= (int)sizeof(vendor_id_buf)) {
456 		p_err("Value in %s too long", path);
457 		return -1;
458 	}
459 
460 	vendor_id_buf[len] = 0;
461 
462 	return strtol(vendor_id_buf, NULL, 0);
463 }
464 
465 static int read_sysfs_netdev_hex_int(char *devname, const char *entry_name)
466 {
467 	char full_path[64];
468 
469 	snprintf(full_path, sizeof(full_path), "/sys/class/net/%s/device/%s",
470 		 devname, entry_name);
471 
472 	return read_sysfs_hex_int(full_path);
473 }
474 
475 const char *ifindex_to_bfd_name_ns(__u32 ifindex, __u64 ns_dev, __u64 ns_ino)
476 {
477 	char devname[IF_NAMESIZE];
478 	int vendor_id;
479 	int device_id;
480 
481 	if (!ifindex_to_name_ns(ifindex, ns_dev, ns_ino, devname)) {
482 		p_err("Can't get net device name for ifindex %d: %s", ifindex,
483 		      strerror(errno));
484 		return NULL;
485 	}
486 
487 	vendor_id = read_sysfs_netdev_hex_int(devname, "vendor");
488 	if (vendor_id < 0) {
489 		p_err("Can't get device vendor id for %s", devname);
490 		return NULL;
491 	}
492 
493 	switch (vendor_id) {
494 	case 0x19ee:
495 		device_id = read_sysfs_netdev_hex_int(devname, "device");
496 		if (device_id != 0x4000 &&
497 		    device_id != 0x6000 &&
498 		    device_id != 0x6003)
499 			p_info("Unknown NFP device ID, assuming it is NFP-6xxx arch");
500 		return "NFP-6xxx";
501 	default:
502 		p_err("Can't get bfd arch name for device vendor id 0x%04x",
503 		      vendor_id);
504 		return NULL;
505 	}
506 }
507 
508 void print_dev_plain(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
509 {
510 	char name[IF_NAMESIZE];
511 
512 	if (!ifindex)
513 		return;
514 
515 	printf(" dev ");
516 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
517 		printf("%s", name);
518 	else
519 		printf("ifindex %u ns_dev %llu ns_ino %llu",
520 		       ifindex, ns_dev, ns_inode);
521 }
522 
523 void print_dev_json(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
524 {
525 	char name[IF_NAMESIZE];
526 
527 	if (!ifindex)
528 		return;
529 
530 	jsonw_name(json_wtr, "dev");
531 	jsonw_start_object(json_wtr);
532 	jsonw_uint_field(json_wtr, "ifindex", ifindex);
533 	jsonw_uint_field(json_wtr, "ns_dev", ns_dev);
534 	jsonw_uint_field(json_wtr, "ns_inode", ns_inode);
535 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
536 		jsonw_string_field(json_wtr, "ifname", name);
537 	jsonw_end_object(json_wtr);
538 }
539