xref: /openbmc/linux/tools/bpf/bpftool/common.c (revision bbecb07f)
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 <fts.h>
38 #include <libgen.h>
39 #include <mntent.h>
40 #include <stdbool.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <linux/limits.h>
46 #include <linux/magic.h>
47 #include <sys/mount.h>
48 #include <sys/types.h>
49 #include <sys/vfs.h>
50 
51 #include <bpf.h>
52 
53 #include "main.h"
54 
55 void p_err(const char *fmt, ...)
56 {
57 	va_list ap;
58 
59 	va_start(ap, fmt);
60 	if (json_output) {
61 		jsonw_start_object(json_wtr);
62 		jsonw_name(json_wtr, "error");
63 		jsonw_vprintf_enquote(json_wtr, fmt, ap);
64 		jsonw_end_object(json_wtr);
65 	} else {
66 		fprintf(stderr, "Error: ");
67 		vfprintf(stderr, fmt, ap);
68 		fprintf(stderr, "\n");
69 	}
70 	va_end(ap);
71 }
72 
73 void p_info(const char *fmt, ...)
74 {
75 	va_list ap;
76 
77 	if (json_output)
78 		return;
79 
80 	va_start(ap, fmt);
81 	vfprintf(stderr, fmt, ap);
82 	fprintf(stderr, "\n");
83 	va_end(ap);
84 }
85 
86 static bool is_bpffs(char *path)
87 {
88 	struct statfs st_fs;
89 
90 	if (statfs(path, &st_fs) < 0)
91 		return false;
92 
93 	return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
94 }
95 
96 static int mnt_bpffs(const char *target, char *buff, size_t bufflen)
97 {
98 	bool bind_done = false;
99 
100 	while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
101 		if (errno != EINVAL || bind_done) {
102 			snprintf(buff, bufflen,
103 				 "mount --make-private %s failed: %s",
104 				 target, strerror(errno));
105 			return -1;
106 		}
107 
108 		if (mount(target, target, "none", MS_BIND, NULL)) {
109 			snprintf(buff, bufflen,
110 				 "mount --bind %s %s failed: %s",
111 				 target, target, strerror(errno));
112 			return -1;
113 		}
114 
115 		bind_done = true;
116 	}
117 
118 	if (mount("bpf", target, "bpf", 0, "mode=0700")) {
119 		snprintf(buff, bufflen, "mount -t bpf bpf %s failed: %s",
120 			 target, strerror(errno));
121 		return -1;
122 	}
123 
124 	return 0;
125 }
126 
127 int open_obj_pinned(char *path)
128 {
129 	int fd;
130 
131 	fd = bpf_obj_get(path);
132 	if (fd < 0) {
133 		p_err("bpf obj get (%s): %s", path,
134 		      errno == EACCES && !is_bpffs(dirname(path)) ?
135 		    "directory not in bpf file system (bpffs)" :
136 		    strerror(errno));
137 		return -1;
138 	}
139 
140 	return fd;
141 }
142 
143 int open_obj_pinned_any(char *path, enum bpf_obj_type exp_type)
144 {
145 	enum bpf_obj_type type;
146 	int fd;
147 
148 	fd = open_obj_pinned(path);
149 	if (fd < 0)
150 		return -1;
151 
152 	type = get_fd_type(fd);
153 	if (type < 0) {
154 		close(fd);
155 		return type;
156 	}
157 	if (type != exp_type) {
158 		p_err("incorrect object type: %s", get_fd_type_name(type));
159 		close(fd);
160 		return -1;
161 	}
162 
163 	return fd;
164 }
165 
166 int do_pin_any(int argc, char **argv, int (*get_fd_by_id)(__u32))
167 {
168 	char err_str[ERR_MAX_LEN];
169 	unsigned int id;
170 	char *endptr;
171 	char *file;
172 	char *dir;
173 	int err;
174 	int fd;
175 
176 	if (!is_prefix(*argv, "id")) {
177 		p_err("expected 'id' got %s", *argv);
178 		return -1;
179 	}
180 	NEXT_ARG();
181 
182 	id = strtoul(*argv, &endptr, 0);
183 	if (*endptr) {
184 		p_err("can't parse %s as ID", *argv);
185 		return -1;
186 	}
187 	NEXT_ARG();
188 
189 	if (argc != 1)
190 		usage();
191 
192 	fd = get_fd_by_id(id);
193 	if (fd < 0) {
194 		p_err("can't get prog by id (%u): %s", id, strerror(errno));
195 		return -1;
196 	}
197 
198 	err = bpf_obj_pin(fd, *argv);
199 	if (!err)
200 		goto out_close;
201 
202 	file = malloc(strlen(*argv) + 1);
203 	strcpy(file, *argv);
204 	dir = dirname(file);
205 
206 	if (errno != EPERM || is_bpffs(dir)) {
207 		p_err("can't pin the object (%s): %s", *argv, strerror(errno));
208 		goto out_free;
209 	}
210 
211 	/* Attempt to mount bpffs, then retry pinning. */
212 	err = mnt_bpffs(dir, err_str, ERR_MAX_LEN);
213 	if (!err) {
214 		err = bpf_obj_pin(fd, *argv);
215 		if (err)
216 			p_err("can't pin the object (%s): %s", *argv,
217 			      strerror(errno));
218 	} else {
219 		err_str[ERR_MAX_LEN - 1] = '\0';
220 		p_err("can't mount BPF file system to pin the object (%s): %s",
221 		      *argv, err_str);
222 	}
223 
224 out_free:
225 	free(file);
226 out_close:
227 	close(fd);
228 	return err;
229 }
230 
231 const char *get_fd_type_name(enum bpf_obj_type type)
232 {
233 	static const char * const names[] = {
234 		[BPF_OBJ_UNKNOWN]	= "unknown",
235 		[BPF_OBJ_PROG]		= "prog",
236 		[BPF_OBJ_MAP]		= "map",
237 	};
238 
239 	if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
240 		return names[BPF_OBJ_UNKNOWN];
241 
242 	return names[type];
243 }
244 
245 int get_fd_type(int fd)
246 {
247 	char path[PATH_MAX];
248 	char buf[512];
249 	ssize_t n;
250 
251 	snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), fd);
252 
253 	n = readlink(path, buf, sizeof(buf));
254 	if (n < 0) {
255 		p_err("can't read link type: %s", strerror(errno));
256 		return -1;
257 	}
258 	if (n == sizeof(path)) {
259 		p_err("can't read link type: path too long!");
260 		return -1;
261 	}
262 
263 	if (strstr(buf, "bpf-map"))
264 		return BPF_OBJ_MAP;
265 	else if (strstr(buf, "bpf-prog"))
266 		return BPF_OBJ_PROG;
267 
268 	return BPF_OBJ_UNKNOWN;
269 }
270 
271 char *get_fdinfo(int fd, const char *key)
272 {
273 	char path[PATH_MAX];
274 	char *line = NULL;
275 	size_t line_n = 0;
276 	ssize_t n;
277 	FILE *fdi;
278 
279 	snprintf(path, sizeof(path), "/proc/%d/fdinfo/%d", getpid(), fd);
280 
281 	fdi = fopen(path, "r");
282 	if (!fdi) {
283 		p_err("can't open fdinfo: %s", strerror(errno));
284 		return NULL;
285 	}
286 
287 	while ((n = getline(&line, &line_n, fdi))) {
288 		char *value;
289 		int len;
290 
291 		if (!strstr(line, key))
292 			continue;
293 
294 		fclose(fdi);
295 
296 		value = strchr(line, '\t');
297 		if (!value || !value[1]) {
298 			p_err("malformed fdinfo!?");
299 			free(line);
300 			return NULL;
301 		}
302 		value++;
303 
304 		len = strlen(value);
305 		memmove(line, value, len);
306 		line[len - 1] = '\0';
307 
308 		return line;
309 	}
310 
311 	p_err("key '%s' not found in fdinfo", key);
312 	free(line);
313 	fclose(fdi);
314 	return NULL;
315 }
316 
317 void print_hex_data_json(uint8_t *data, size_t len)
318 {
319 	unsigned int i;
320 
321 	jsonw_start_array(json_wtr);
322 	for (i = 0; i < len; i++)
323 		jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
324 	jsonw_end_array(json_wtr);
325 }
326 
327 int build_pinned_obj_table(struct pinned_obj_table *tab,
328 			   enum bpf_obj_type type)
329 {
330 	struct bpf_prog_info pinned_info = {};
331 	struct pinned_obj *obj_node = NULL;
332 	__u32 len = sizeof(pinned_info);
333 	struct mntent *mntent = NULL;
334 	enum bpf_obj_type objtype;
335 	FILE *mntfile = NULL;
336 	FTSENT *ftse = NULL;
337 	FTS *fts = NULL;
338 	int fd, err;
339 
340 	mntfile = setmntent("/proc/mounts", "r");
341 	if (!mntfile)
342 		return -1;
343 
344 	while ((mntent = getmntent(mntfile))) {
345 		char *path[] = { mntent->mnt_dir, NULL };
346 
347 		if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
348 			continue;
349 
350 		fts = fts_open(path, 0, NULL);
351 		if (!fts)
352 			continue;
353 
354 		while ((ftse = fts_read(fts))) {
355 			if (!(ftse->fts_info & FTS_F))
356 				continue;
357 			fd = open_obj_pinned(ftse->fts_path);
358 			if (fd < 0)
359 				continue;
360 
361 			objtype = get_fd_type(fd);
362 			if (objtype != type) {
363 				close(fd);
364 				continue;
365 			}
366 			memset(&pinned_info, 0, sizeof(pinned_info));
367 			err = bpf_obj_get_info_by_fd(fd, &pinned_info, &len);
368 			if (err) {
369 				close(fd);
370 				continue;
371 			}
372 
373 			obj_node = malloc(sizeof(*obj_node));
374 			if (!obj_node) {
375 				close(fd);
376 				fts_close(fts);
377 				fclose(mntfile);
378 				return -1;
379 			}
380 
381 			memset(obj_node, 0, sizeof(*obj_node));
382 			obj_node->id = pinned_info.id;
383 			obj_node->path = strdup(ftse->fts_path);
384 			hash_add(tab->table, &obj_node->hash, obj_node->id);
385 
386 			close(fd);
387 		}
388 		fts_close(fts);
389 	}
390 	fclose(mntfile);
391 	return 0;
392 }
393 
394 void delete_pinned_obj_table(struct pinned_obj_table *tab)
395 {
396 	struct pinned_obj *obj;
397 	struct hlist_node *tmp;
398 	unsigned int bkt;
399 
400 	hash_for_each_safe(tab->table, bkt, tmp, obj, hash) {
401 		hash_del(&obj->hash);
402 		free(obj->path);
403 		free(obj);
404 	}
405 }
406