xref: /openbmc/linux/tools/bpf/bpftool/common.c (revision 2eb3ed33e55d003d721d4d1a5e72fe323c12b4c0)
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 <libgen.h>
38 #include <stdbool.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <linux/limits.h>
44 #include <linux/magic.h>
45 #include <sys/mount.h>
46 #include <sys/types.h>
47 #include <sys/vfs.h>
48 
49 #include <bpf.h>
50 
51 #include "main.h"
52 
53 void p_err(const char *fmt, ...)
54 {
55 	va_list ap;
56 
57 	va_start(ap, fmt);
58 	if (json_output) {
59 		jsonw_start_object(json_wtr);
60 		jsonw_name(json_wtr, "error");
61 		jsonw_vprintf_enquote(json_wtr, fmt, ap);
62 		jsonw_end_object(json_wtr);
63 	} else {
64 		fprintf(stderr, "Error: ");
65 		vfprintf(stderr, fmt, ap);
66 		fprintf(stderr, "\n");
67 	}
68 	va_end(ap);
69 }
70 
71 void p_info(const char *fmt, ...)
72 {
73 	va_list ap;
74 
75 	if (json_output)
76 		return;
77 
78 	va_start(ap, fmt);
79 	vfprintf(stderr, fmt, ap);
80 	fprintf(stderr, "\n");
81 	va_end(ap);
82 }
83 
84 static bool is_bpffs(char *path)
85 {
86 	struct statfs st_fs;
87 
88 	if (statfs(path, &st_fs) < 0)
89 		return false;
90 
91 	return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
92 }
93 
94 static int mnt_bpffs(const char *target, char *buff, size_t bufflen)
95 {
96 	bool bind_done = false;
97 
98 	while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
99 		if (errno != EINVAL || bind_done) {
100 			snprintf(buff, bufflen,
101 				 "mount --make-private %s failed: %s",
102 				 target, strerror(errno));
103 			return -1;
104 		}
105 
106 		if (mount(target, target, "none", MS_BIND, NULL)) {
107 			snprintf(buff, bufflen,
108 				 "mount --bind %s %s failed: %s",
109 				 target, target, strerror(errno));
110 			return -1;
111 		}
112 
113 		bind_done = true;
114 	}
115 
116 	if (mount("bpf", target, "bpf", 0, "mode=0700")) {
117 		snprintf(buff, bufflen, "mount -t bpf bpf %s failed: %s",
118 			 target, strerror(errno));
119 		return -1;
120 	}
121 
122 	return 0;
123 }
124 
125 int open_obj_pinned_any(char *path, enum bpf_obj_type exp_type)
126 {
127 	enum bpf_obj_type type;
128 	int fd;
129 
130 	fd = bpf_obj_get(path);
131 	if (fd < 0) {
132 		p_err("bpf obj get (%s): %s", path,
133 		      errno == EACCES && !is_bpffs(dirname(path)) ?
134 		    "directory not in bpf file system (bpffs)" :
135 		    strerror(errno));
136 		return -1;
137 	}
138 
139 	type = get_fd_type(fd);
140 	if (type < 0) {
141 		close(fd);
142 		return type;
143 	}
144 	if (type != exp_type) {
145 		p_err("incorrect object type: %s", get_fd_type_name(type));
146 		close(fd);
147 		return -1;
148 	}
149 
150 	return fd;
151 }
152 
153 int do_pin_any(int argc, char **argv, int (*get_fd_by_id)(__u32))
154 {
155 	char err_str[ERR_MAX_LEN];
156 	unsigned int id;
157 	char *endptr;
158 	char *file;
159 	char *dir;
160 	int err;
161 	int fd;
162 
163 	if (!is_prefix(*argv, "id")) {
164 		p_err("expected 'id' got %s", *argv);
165 		return -1;
166 	}
167 	NEXT_ARG();
168 
169 	id = strtoul(*argv, &endptr, 0);
170 	if (*endptr) {
171 		p_err("can't parse %s as ID", *argv);
172 		return -1;
173 	}
174 	NEXT_ARG();
175 
176 	if (argc != 1)
177 		usage();
178 
179 	fd = get_fd_by_id(id);
180 	if (fd < 0) {
181 		p_err("can't get prog by id (%u): %s", id, strerror(errno));
182 		return -1;
183 	}
184 
185 	err = bpf_obj_pin(fd, *argv);
186 	if (!err)
187 		goto out_close;
188 
189 	file = malloc(strlen(*argv) + 1);
190 	strcpy(file, *argv);
191 	dir = dirname(file);
192 
193 	if (errno != EPERM || is_bpffs(dir)) {
194 		p_err("can't pin the object (%s): %s", *argv, strerror(errno));
195 		goto out_free;
196 	}
197 
198 	/* Attempt to mount bpffs, then retry pinning. */
199 	err = mnt_bpffs(dir, err_str, ERR_MAX_LEN);
200 	if (!err) {
201 		err = bpf_obj_pin(fd, *argv);
202 		if (err)
203 			p_err("can't pin the object (%s): %s", *argv,
204 			      strerror(errno));
205 	} else {
206 		err_str[ERR_MAX_LEN - 1] = '\0';
207 		p_err("can't mount BPF file system to pin the object (%s): %s",
208 		      *argv, err_str);
209 	}
210 
211 out_free:
212 	free(file);
213 out_close:
214 	close(fd);
215 	return err;
216 }
217 
218 const char *get_fd_type_name(enum bpf_obj_type type)
219 {
220 	static const char * const names[] = {
221 		[BPF_OBJ_UNKNOWN]	= "unknown",
222 		[BPF_OBJ_PROG]		= "prog",
223 		[BPF_OBJ_MAP]		= "map",
224 	};
225 
226 	if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
227 		return names[BPF_OBJ_UNKNOWN];
228 
229 	return names[type];
230 }
231 
232 int get_fd_type(int fd)
233 {
234 	char path[PATH_MAX];
235 	char buf[512];
236 	ssize_t n;
237 
238 	snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), fd);
239 
240 	n = readlink(path, buf, sizeof(buf));
241 	if (n < 0) {
242 		p_err("can't read link type: %s", strerror(errno));
243 		return -1;
244 	}
245 	if (n == sizeof(path)) {
246 		p_err("can't read link type: path too long!");
247 		return -1;
248 	}
249 
250 	if (strstr(buf, "bpf-map"))
251 		return BPF_OBJ_MAP;
252 	else if (strstr(buf, "bpf-prog"))
253 		return BPF_OBJ_PROG;
254 
255 	return BPF_OBJ_UNKNOWN;
256 }
257 
258 char *get_fdinfo(int fd, const char *key)
259 {
260 	char path[PATH_MAX];
261 	char *line = NULL;
262 	size_t line_n = 0;
263 	ssize_t n;
264 	FILE *fdi;
265 
266 	snprintf(path, sizeof(path), "/proc/%d/fdinfo/%d", getpid(), fd);
267 
268 	fdi = fopen(path, "r");
269 	if (!fdi) {
270 		p_err("can't open fdinfo: %s", strerror(errno));
271 		return NULL;
272 	}
273 
274 	while ((n = getline(&line, &line_n, fdi))) {
275 		char *value;
276 		int len;
277 
278 		if (!strstr(line, key))
279 			continue;
280 
281 		fclose(fdi);
282 
283 		value = strchr(line, '\t');
284 		if (!value || !value[1]) {
285 			p_err("malformed fdinfo!?");
286 			free(line);
287 			return NULL;
288 		}
289 		value++;
290 
291 		len = strlen(value);
292 		memmove(line, value, len);
293 		line[len - 1] = '\0';
294 
295 		return line;
296 	}
297 
298 	p_err("key '%s' not found in fdinfo", key);
299 	free(line);
300 	fclose(fdi);
301 	return NULL;
302 }
303 
304 void print_hex_data_json(uint8_t *data, size_t len)
305 {
306 	unsigned int i;
307 
308 	jsonw_start_array(json_wtr);
309 	for (i = 0; i < len; i++)
310 		jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
311 	jsonw_end_array(json_wtr);
312 }
313