]> git.proxmox.com Git - mirror_iproute2.git/blame - tc/tc_bpf.c
man: Point to 'devlink-sb' from 'devlink' man page
[mirror_iproute2.git] / tc / tc_bpf.c
CommitLineData
1d129d19
JP
1/*
2 * tc_bpf.c BPF common code
3 *
4 * This program is free software; you can distribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
8 *
9 * Authors: Daniel Borkmann <dborkman@redhat.com>
10 * Jiri Pirko <jiri@resnulli.us>
11c39b5e 11 * Alexei Starovoitov <ast@plumgrid.com>
1d129d19
JP
12 */
13
14#include <stdio.h>
15#include <stdlib.h>
16#include <unistd.h>
17#include <string.h>
18#include <stdbool.h>
473d7840 19#include <stdint.h>
1d129d19 20#include <errno.h>
11c39b5e
DB
21#include <fcntl.h>
22#include <stdarg.h>
5c5a0f3d 23#include <limits.h>
1d129d19 24
11c39b5e
DB
25#ifdef HAVE_ELF
26#include <libelf.h>
27#include <gelf.h>
28#endif
29
32e93fb7
DB
30#include <sys/types.h>
31#include <sys/stat.h>
32#include <sys/un.h>
33#include <sys/vfs.h>
34#include <sys/mount.h>
35#include <sys/syscall.h>
36#include <sys/sendfile.h>
37#include <sys/resource.h>
38
39#include <linux/bpf.h>
40#include <linux/filter.h>
41#include <linux/if_alg.h>
42
8187b012
DB
43#include <arpa/inet.h>
44
1d129d19 45#include "utils.h"
6256f8c9
DB
46
47#include "bpf_elf.h"
48#include "bpf_scm.h"
49
1d129d19
JP
50#include "tc_util.h"
51#include "tc_bpf.h"
52
67584e3a
ND
53#ifndef AF_ALG
54#define AF_ALG 38
55#endif
56
32e93fb7
DB
57#ifdef HAVE_ELF
58static int bpf_obj_open(const char *path, enum bpf_prog_type type,
59 const char *sec, bool verbose);
60#else
61static int bpf_obj_open(const char *path, enum bpf_prog_type type,
62 const char *sec, bool verbose)
63{
64 fprintf(stderr, "No ELF library support compiled in.\n");
65 errno = ENOSYS;
66 return -1;
67}
68#endif
69
70static inline __u64 bpf_ptr_to_u64(const void *ptr)
71{
72 return (__u64)(unsigned long)ptr;
73}
74
75static int bpf(int cmd, union bpf_attr *attr, unsigned int size)
76{
77#ifdef __NR_bpf
78 return syscall(__NR_bpf, cmd, attr, size);
79#else
80 fprintf(stderr, "No bpf syscall, kernel headers too old?\n");
81 errno = ENOSYS;
82 return -1;
83#endif
84}
85
91d88eeb
DB
86static int bpf_map_update(int fd, const void *key, const void *value,
87 uint64_t flags)
32e93fb7 88{
67584e3a
ND
89 union bpf_attr attr;
90
91 memset(&attr, 0, sizeof(attr));
92 attr.map_fd = fd;
93 attr.key = bpf_ptr_to_u64(key);
94 attr.value = bpf_ptr_to_u64(value);
95 attr.flags = flags;
32e93fb7 96
91d88eeb 97 return bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
32e93fb7
DB
98}
99
100static int bpf_parse_string(char *arg, bool from_file, __u16 *bpf_len,
101 char **bpf_string, bool *need_release,
102 const char separator)
1d129d19
JP
103{
104 char sp;
105
106 if (from_file) {
107 size_t tmp_len, op_len = sizeof("65535 255 255 4294967295,");
108 char *tmp_string;
109 FILE *fp;
110
111 tmp_len = sizeof("4096,") + BPF_MAXINSNS * op_len;
112 tmp_string = malloc(tmp_len);
113 if (tmp_string == NULL)
114 return -ENOMEM;
115
116 memset(tmp_string, 0, tmp_len);
117
118 fp = fopen(arg, "r");
119 if (fp == NULL) {
120 perror("Cannot fopen");
121 free(tmp_string);
122 return -ENOENT;
123 }
124
125 if (!fgets(tmp_string, tmp_len, fp)) {
126 free(tmp_string);
127 fclose(fp);
128 return -EIO;
129 }
130
131 fclose(fp);
132
133 *need_release = true;
134 *bpf_string = tmp_string;
135 } else {
136 *need_release = false;
137 *bpf_string = arg;
138 }
139
140 if (sscanf(*bpf_string, "%hu%c", bpf_len, &sp) != 2 ||
141 sp != separator) {
142 if (*need_release)
143 free(*bpf_string);
144 return -EINVAL;
145 }
146
147 return 0;
148}
149
32e93fb7
DB
150static int bpf_ops_parse(int argc, char **argv, struct sock_filter *bpf_ops,
151 bool from_file)
1d129d19
JP
152{
153 char *bpf_string, *token, separator = ',';
154 int ret = 0, i = 0;
155 bool need_release;
156 __u16 bpf_len = 0;
157
158 if (argc < 1)
159 return -EINVAL;
160 if (bpf_parse_string(argv[0], from_file, &bpf_len, &bpf_string,
161 &need_release, separator))
162 return -EINVAL;
163 if (bpf_len == 0 || bpf_len > BPF_MAXINSNS) {
164 ret = -EINVAL;
165 goto out;
166 }
167
168 token = bpf_string;
169 while ((token = strchr(token, separator)) && (++token)[0]) {
170 if (i >= bpf_len) {
32a121cb 171 fprintf(stderr, "Real program length exceeds encoded length parameter!\n");
1d129d19
JP
172 ret = -EINVAL;
173 goto out;
174 }
175
176 if (sscanf(token, "%hu %hhu %hhu %u,",
177 &bpf_ops[i].code, &bpf_ops[i].jt,
178 &bpf_ops[i].jf, &bpf_ops[i].k) != 4) {
179 fprintf(stderr, "Error at instruction %d!\n", i);
180 ret = -EINVAL;
181 goto out;
182 }
183
184 i++;
185 }
186
187 if (i != bpf_len) {
afc1a200 188 fprintf(stderr, "Parsed program length is less than encoded length parameter!\n");
1d129d19
JP
189 ret = -EINVAL;
190 goto out;
191 }
192 ret = bpf_len;
1d129d19
JP
193out:
194 if (need_release)
195 free(bpf_string);
196
197 return ret;
198}
199
200void bpf_print_ops(FILE *f, struct rtattr *bpf_ops, __u16 len)
201{
202 struct sock_filter *ops = (struct sock_filter *) RTA_DATA(bpf_ops);
203 int i;
204
205 if (len == 0)
206 return;
207
208 fprintf(f, "bytecode \'%u,", len);
209
210 for (i = 0; i < len - 1; i++)
211 fprintf(f, "%hu %hhu %hhu %u,", ops[i].code, ops[i].jt,
212 ops[i].jf, ops[i].k);
213
6256f8c9 214 fprintf(f, "%hu %hhu %hhu %u\'", ops[i].code, ops[i].jt,
1d129d19
JP
215 ops[i].jf, ops[i].k);
216}
11c39b5e 217
afc1a200
DB
218static void bpf_map_pin_report(const struct bpf_elf_map *pin,
219 const struct bpf_elf_map *obj)
220{
221 fprintf(stderr, "Map specification differs from pinned file!\n");
222
223 if (obj->type != pin->type)
224 fprintf(stderr, " - Type: %u (obj) != %u (pin)\n",
225 obj->type, pin->type);
226 if (obj->size_key != pin->size_key)
227 fprintf(stderr, " - Size key: %u (obj) != %u (pin)\n",
228 obj->size_key, pin->size_key);
229 if (obj->size_value != pin->size_value)
230 fprintf(stderr, " - Size value: %u (obj) != %u (pin)\n",
231 obj->size_value, pin->size_value);
232 if (obj->max_elem != pin->max_elem)
233 fprintf(stderr, " - Max elems: %u (obj) != %u (pin)\n",
234 obj->max_elem, pin->max_elem);
4dd3f50a
DB
235 if (obj->flags != pin->flags)
236 fprintf(stderr, " - Flags: %#x (obj) != %#x (pin)\n",
237 obj->flags, pin->flags);
afc1a200
DB
238
239 fprintf(stderr, "\n");
240}
241
91d88eeb
DB
242static int bpf_map_selfcheck_pinned(int fd, const struct bpf_elf_map *map,
243 int length)
9e607f2e
DB
244{
245 char file[PATH_MAX], buff[4096];
246 struct bpf_elf_map tmp, zero;
247 unsigned int val;
248 FILE *fp;
249
250 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
251
252 fp = fopen(file, "r");
253 if (!fp) {
254 fprintf(stderr, "No procfs support?!\n");
255 return -EIO;
256 }
257
258 memset(&tmp, 0, sizeof(tmp));
259 while (fgets(buff, sizeof(buff), fp)) {
260 if (sscanf(buff, "map_type:\t%u", &val) == 1)
261 tmp.type = val;
262 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
263 tmp.size_key = val;
264 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
265 tmp.size_value = val;
266 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
267 tmp.max_elem = val;
4dd3f50a
DB
268 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
269 tmp.flags = val;
9e607f2e
DB
270 }
271
272 fclose(fp);
273
91d88eeb 274 if (!memcmp(&tmp, map, length)) {
9e607f2e
DB
275 return 0;
276 } else {
277 memset(&zero, 0, sizeof(zero));
278 /* If kernel doesn't have eBPF-related fdinfo, we cannot do much,
279 * so just accept it. We know we do have an eBPF fd and in this
280 * case, everything is 0. It is guaranteed that no such map exists
281 * since map type of 0 is unloadable BPF_MAP_TYPE_UNSPEC.
282 */
91d88eeb 283 if (!memcmp(&tmp, &zero, length))
9e607f2e
DB
284 return 0;
285
afc1a200 286 bpf_map_pin_report(&tmp, map);
9e607f2e
DB
287 return -EINVAL;
288 }
289}
290
91d88eeb
DB
291static int bpf_mnt_fs(const char *target)
292{
293 bool bind_done = false;
294
295 while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
296 if (errno != EINVAL || bind_done) {
297 fprintf(stderr, "mount --make-private %s failed: %s\n",
298 target, strerror(errno));
299 return -1;
300 }
301
302 if (mount(target, target, "none", MS_BIND, NULL)) {
303 fprintf(stderr, "mount --bind %s %s failed: %s\n",
304 target, target, strerror(errno));
305 return -1;
306 }
307
308 bind_done = true;
309 }
310
311 if (mount("bpf", target, "bpf", 0, NULL)) {
312 fprintf(stderr, "mount -t bpf bpf %s failed: %s\n",
313 target, strerror(errno));
314 return -1;
315 }
316
317 return 0;
318}
319
32e93fb7
DB
320static int bpf_valid_mntpt(const char *mnt, unsigned long magic)
321{
322 struct statfs st_fs;
323
324 if (statfs(mnt, &st_fs) < 0)
325 return -ENOENT;
326 if ((unsigned long)st_fs.f_type != magic)
327 return -ENOENT;
328
329 return 0;
330}
331
332static const char *bpf_find_mntpt(const char *fstype, unsigned long magic,
333 char *mnt, int len,
334 const char * const *known_mnts)
335{
336 const char * const *ptr;
337 char type[100];
338 FILE *fp;
339
340 if (known_mnts) {
341 ptr = known_mnts;
342 while (*ptr) {
343 if (bpf_valid_mntpt(*ptr, magic) == 0) {
344 strncpy(mnt, *ptr, len - 1);
345 mnt[len - 1] = 0;
346 return mnt;
347 }
348 ptr++;
349 }
350 }
351
352 fp = fopen("/proc/mounts", "r");
353 if (fp == NULL || len != PATH_MAX)
354 return NULL;
355
356 while (fscanf(fp, "%*s %" textify(PATH_MAX) "s %99s %*s %*d %*d\n",
357 mnt, type) == 2) {
358 if (strcmp(type, fstype) == 0)
359 break;
360 }
361
362 fclose(fp);
363 if (strcmp(type, fstype) != 0)
364 return NULL;
365
366 return mnt;
367}
368
369int bpf_trace_pipe(void)
370{
371 char tracefs_mnt[PATH_MAX] = TRACE_DIR_MNT;
372 static const char * const tracefs_known_mnts[] = {
373 TRACE_DIR_MNT,
374 "/sys/kernel/debug/tracing",
375 "/tracing",
376 "/trace",
377 0,
378 };
379 char tpipe[PATH_MAX];
380 const char *mnt;
381 int fd;
382
383 mnt = bpf_find_mntpt("tracefs", TRACEFS_MAGIC, tracefs_mnt,
384 sizeof(tracefs_mnt), tracefs_known_mnts);
385 if (!mnt) {
386 fprintf(stderr, "tracefs not mounted?\n");
387 return -1;
388 }
389
390 snprintf(tpipe, sizeof(tpipe), "%s/trace_pipe", mnt);
391
392 fd = open(tpipe, O_RDONLY);
393 if (fd < 0)
394 return -1;
395
396 fprintf(stderr, "Running! Hang up with ^C!\n\n");
397 while (1) {
398 static char buff[4096];
399 ssize_t ret;
400
401 ret = read(fd, buff, sizeof(buff) - 1);
402 if (ret > 0) {
403 write(2, buff, ret);
404 fflush(stderr);
405 }
406 }
407
408 return 0;
409}
410
91d88eeb
DB
411static const char *bpf_get_tc_dir(void)
412{
32a121cb 413 static bool bpf_mnt_cached;
91d88eeb
DB
414 static char bpf_tc_dir[PATH_MAX];
415 static const char *mnt;
416 static const char * const bpf_known_mnts[] = {
417 BPF_DIR_MNT,
418 0,
419 };
420 char bpf_mnt[PATH_MAX] = BPF_DIR_MNT;
421 char bpf_glo_dir[PATH_MAX];
422 int ret;
423
424 if (bpf_mnt_cached)
425 goto done;
426
427 mnt = bpf_find_mntpt("bpf", BPF_FS_MAGIC, bpf_mnt, sizeof(bpf_mnt),
428 bpf_known_mnts);
429 if (!mnt) {
430 mnt = getenv(BPF_ENV_MNT);
431 if (!mnt)
432 mnt = BPF_DIR_MNT;
433 ret = bpf_mnt_fs(mnt);
434 if (ret) {
435 mnt = NULL;
436 goto out;
437 }
438 }
439
440 snprintf(bpf_tc_dir, sizeof(bpf_tc_dir), "%s/%s", mnt, BPF_DIR_TC);
441 ret = mkdir(bpf_tc_dir, S_IRWXU);
442 if (ret && errno != EEXIST) {
443 fprintf(stderr, "mkdir %s failed: %s\n", bpf_tc_dir,
444 strerror(errno));
445 mnt = NULL;
446 goto out;
447 }
448
449 snprintf(bpf_glo_dir, sizeof(bpf_glo_dir), "%s/%s",
450 bpf_tc_dir, BPF_DIR_GLOBALS);
451 ret = mkdir(bpf_glo_dir, S_IRWXU);
452 if (ret && errno != EEXIST) {
453 fprintf(stderr, "mkdir %s failed: %s\n", bpf_glo_dir,
454 strerror(errno));
455 mnt = NULL;
456 goto out;
457 }
458
459 mnt = bpf_tc_dir;
460out:
461 bpf_mnt_cached = true;
462done:
463 return mnt;
464}
465
466static int bpf_obj_get(const char *pathname)
467{
468 union bpf_attr attr;
469 char tmp[PATH_MAX];
470
471 if (strlen(pathname) > 2 && pathname[0] == 'm' &&
472 pathname[1] == ':' && bpf_get_tc_dir()) {
473 snprintf(tmp, sizeof(tmp), "%s/%s",
474 bpf_get_tc_dir(), pathname + 2);
475 pathname = tmp;
476 }
477
478 memset(&attr, 0, sizeof(attr));
479 attr.pathname = bpf_ptr_to_u64(pathname);
480
481 return bpf(BPF_OBJ_GET, &attr, sizeof(attr));
482}
483
6256f8c9 484const char *bpf_default_section(const enum bpf_prog_type type)
11c39b5e
DB
485{
486 switch (type) {
487 case BPF_PROG_TYPE_SCHED_CLS:
488 return ELF_SECTION_CLASSIFIER;
6256f8c9
DB
489 case BPF_PROG_TYPE_SCHED_ACT:
490 return ELF_SECTION_ACTION;
11c39b5e
DB
491 default:
492 return NULL;
493 }
494}
495
91d88eeb
DB
496enum bpf_mode {
497 CBPF_BYTECODE = 0,
498 CBPF_FILE,
499 EBPF_OBJECT,
500 EBPF_PINNED,
501 __BPF_MODE_MAX,
502#define BPF_MODE_MAX __BPF_MODE_MAX
503};
504
505static int bpf_parse(int *ptr_argc, char ***ptr_argv, const bool *opt_tbl,
506 enum bpf_prog_type *type, enum bpf_mode *mode,
507 const char **ptr_object, const char **ptr_section,
508 const char **ptr_uds_name, struct sock_filter *opcodes)
32e93fb7 509{
32e93fb7 510 const char *file, *section, *uds_name;
32e93fb7 511 bool verbose = false;
91d88eeb
DB
512 int ret, argc;
513 char **argv;
514
515 argv = *ptr_argv;
516 argc = *ptr_argc;
517
518 if (opt_tbl[CBPF_BYTECODE] &&
519 (matches(*argv, "bytecode") == 0 ||
520 strcmp(*argv, "bc") == 0)) {
521 *mode = CBPF_BYTECODE;
522 } else if (opt_tbl[CBPF_FILE] &&
523 (matches(*argv, "bytecode-file") == 0 ||
524 strcmp(*argv, "bcf") == 0)) {
525 *mode = CBPF_FILE;
526 } else if (opt_tbl[EBPF_OBJECT] &&
527 (matches(*argv, "object-file") == 0 ||
528 strcmp(*argv, "obj") == 0)) {
529 *mode = EBPF_OBJECT;
530 } else if (opt_tbl[EBPF_PINNED] &&
531 (matches(*argv, "object-pinned") == 0 ||
532 matches(*argv, "pinned") == 0 ||
533 matches(*argv, "fd") == 0)) {
534 *mode = EBPF_PINNED;
32e93fb7
DB
535 } else {
536 fprintf(stderr, "What mode is \"%s\"?\n", *argv);
537 return -1;
538 }
539
540 NEXT_ARG();
541 file = section = uds_name = NULL;
91d88eeb 542 if (*mode == EBPF_OBJECT || *mode == EBPF_PINNED) {
32e93fb7
DB
543 file = *argv;
544 NEXT_ARG_FWD();
545
91d88eeb
DB
546 if (*type == BPF_PROG_TYPE_UNSPEC) {
547 if (argc > 0 && matches(*argv, "type") == 0) {
548 NEXT_ARG();
549 if (matches(*argv, "cls") == 0) {
550 *type = BPF_PROG_TYPE_SCHED_CLS;
551 } else if (matches(*argv, "act") == 0) {
552 *type = BPF_PROG_TYPE_SCHED_ACT;
553 } else {
554 fprintf(stderr, "What type is \"%s\"?\n",
555 *argv);
556 return -1;
557 }
558 NEXT_ARG_FWD();
559 } else {
560 *type = BPF_PROG_TYPE_SCHED_CLS;
561 }
562 }
563
564 section = bpf_default_section(*type);
32e93fb7
DB
565 if (argc > 0 && matches(*argv, "section") == 0) {
566 NEXT_ARG();
567 section = *argv;
568 NEXT_ARG_FWD();
569 }
570
571 uds_name = getenv(BPF_ENV_UDS);
572 if (argc > 0 && !uds_name &&
573 matches(*argv, "export") == 0) {
574 NEXT_ARG();
575 uds_name = *argv;
576 NEXT_ARG_FWD();
577 }
578
579 if (argc > 0 && matches(*argv, "verbose") == 0) {
580 verbose = true;
581 NEXT_ARG_FWD();
582 }
583
584 PREV_ARG();
585 }
586
91d88eeb
DB
587 if (*mode == CBPF_BYTECODE || *mode == CBPF_FILE)
588 ret = bpf_ops_parse(argc, argv, opcodes, *mode == CBPF_FILE);
589 else if (*mode == EBPF_OBJECT)
590 ret = bpf_obj_open(file, *type, section, verbose);
591 else if (*mode == EBPF_PINNED)
32e93fb7 592 ret = bpf_obj_get(file);
91d88eeb 593 else
32e93fb7
DB
594 return -1;
595
91d88eeb
DB
596 if (ptr_object)
597 *ptr_object = file;
598 if (ptr_section)
599 *ptr_section = section;
600 if (ptr_uds_name)
601 *ptr_uds_name = uds_name;
602
603 *ptr_argc = argc;
604 *ptr_argv = argv;
605
606 return ret;
607}
608
609int bpf_parse_common(int *ptr_argc, char ***ptr_argv, const int *nla_tbl,
610 enum bpf_prog_type type, const char **ptr_object,
611 const char **ptr_uds_name, struct nlmsghdr *n)
612{
613 struct sock_filter opcodes[BPF_MAXINSNS];
614 const bool opt_tbl[BPF_MODE_MAX] = {
615 [CBPF_BYTECODE] = true,
616 [CBPF_FILE] = true,
617 [EBPF_OBJECT] = true,
618 [EBPF_PINNED] = true,
619 };
620 char annotation[256];
621 const char *section;
622 enum bpf_mode mode;
623 int ret;
624
625 ret = bpf_parse(ptr_argc, ptr_argv, opt_tbl, &type, &mode,
626 ptr_object, &section, ptr_uds_name, opcodes);
627 if (ret < 0)
628 return ret;
629
32e93fb7
DB
630 if (mode == CBPF_BYTECODE || mode == CBPF_FILE) {
631 addattr16(n, MAX_MSG, nla_tbl[BPF_NLA_OPS_LEN], ret);
632 addattr_l(n, MAX_MSG, nla_tbl[BPF_NLA_OPS], opcodes,
633 ret * sizeof(struct sock_filter));
91d88eeb
DB
634 }
635
636 if (mode == EBPF_OBJECT || mode == EBPF_PINNED) {
32e93fb7 637 snprintf(annotation, sizeof(annotation), "%s:[%s]",
91d88eeb
DB
638 basename(*ptr_object), mode == EBPF_PINNED ?
639 "*fsobj" : section);
32e93fb7
DB
640
641 addattr32(n, MAX_MSG, nla_tbl[BPF_NLA_FD], ret);
642 addattrstrz(n, MAX_MSG, nla_tbl[BPF_NLA_NAME], annotation);
643 }
644
91d88eeb
DB
645 return 0;
646}
32e93fb7 647
91d88eeb
DB
648int bpf_graft_map(const char *map_path, uint32_t *key, int argc, char **argv)
649{
650 enum bpf_prog_type type = BPF_PROG_TYPE_UNSPEC;
651 const bool opt_tbl[BPF_MODE_MAX] = {
652 [CBPF_BYTECODE] = false,
653 [CBPF_FILE] = false,
654 [EBPF_OBJECT] = true,
655 [EBPF_PINNED] = true,
656 };
657 const struct bpf_elf_map test = {
658 .type = BPF_MAP_TYPE_PROG_ARRAY,
659 .size_key = sizeof(int),
660 .size_value = sizeof(int),
661 };
662 int ret, prog_fd, map_fd;
663 const char *section;
664 enum bpf_mode mode;
665 uint32_t map_key;
666
667 prog_fd = bpf_parse(&argc, &argv, opt_tbl, &type, &mode,
668 NULL, &section, NULL, NULL);
669 if (prog_fd < 0)
670 return prog_fd;
671 if (key) {
672 map_key = *key;
673 } else {
674 ret = sscanf(section, "%*i/%i", &map_key);
675 if (ret != 1) {
32a121cb 676 fprintf(stderr, "Couldn\'t infer map key from section name! Please provide \'key\' argument!\n");
91d88eeb
DB
677 ret = -EINVAL;
678 goto out_prog;
679 }
680 }
32e93fb7 681
91d88eeb
DB
682 map_fd = bpf_obj_get(map_path);
683 if (map_fd < 0) {
684 fprintf(stderr, "Couldn\'t retrieve pinned map \'%s\': %s\n",
685 map_path, strerror(errno));
686 ret = map_fd;
687 goto out_prog;
688 }
689
690 ret = bpf_map_selfcheck_pinned(map_fd, &test,
691 offsetof(struct bpf_elf_map, max_elem));
692 if (ret < 0) {
693 fprintf(stderr, "Map \'%s\' self-check failed!\n", map_path);
694 goto out_map;
695 }
696
697 ret = bpf_map_update(map_fd, &map_key, &prog_fd, BPF_ANY);
698 if (ret < 0)
699 fprintf(stderr, "Map update failed: %s\n", strerror(errno));
700out_map:
701 close(map_fd);
702out_prog:
703 close(prog_fd);
704 return ret;
32e93fb7
DB
705}
706
6256f8c9 707#ifdef HAVE_ELF
32e93fb7
DB
708struct bpf_elf_prog {
709 enum bpf_prog_type type;
710 const struct bpf_insn *insns;
711 size_t size;
712 const char *license;
713};
714
f6793eec
DB
715struct bpf_hash_entry {
716 unsigned int pinning;
717 const char *subpath;
718 struct bpf_hash_entry *next;
719};
720
32e93fb7
DB
721struct bpf_elf_ctx {
722 Elf *elf_fd;
723 GElf_Ehdr elf_hdr;
724 Elf_Data *sym_tab;
725 Elf_Data *str_tab;
726 int obj_fd;
727 int map_fds[ELF_MAX_MAPS];
728 struct bpf_elf_map maps[ELF_MAX_MAPS];
729 int sym_num;
730 int map_num;
731 bool *sec_done;
732 int sec_maps;
733 char license[ELF_MAX_LICENSE_LEN];
734 enum bpf_prog_type type;
735 bool verbose;
736 struct bpf_elf_st stat;
f6793eec 737 struct bpf_hash_entry *ht[256];
f31645d1
DB
738 char *log;
739 size_t log_size;
32e93fb7
DB
740};
741
6256f8c9 742struct bpf_elf_sec_data {
32e93fb7
DB
743 GElf_Shdr sec_hdr;
744 Elf_Data *sec_data;
745 const char *sec_name;
6256f8c9
DB
746};
747
748struct bpf_map_data {
32e93fb7
DB
749 int *fds;
750 const char *obj;
751 struct bpf_elf_st *st;
752 struct bpf_elf_map *ent;
6256f8c9
DB
753};
754
f31645d1
DB
755static __check_format_string(2, 3) void
756bpf_dump_error(struct bpf_elf_ctx *ctx, const char *format, ...)
11c39b5e
DB
757{
758 va_list vl;
759
760 va_start(vl, format);
761 vfprintf(stderr, format, vl);
762 va_end(vl);
763
f31645d1 764 if (ctx->log && ctx->log[0]) {
afc1a200
DB
765 if (ctx->verbose) {
766 fprintf(stderr, "%s\n", ctx->log);
767 } else {
768 unsigned int off = 0, len = strlen(ctx->log);
769
770 if (len > BPF_MAX_LOG) {
771 off = len - BPF_MAX_LOG;
772 fprintf(stderr, "Skipped %u bytes, use \'verb\' option for the full verbose log.\n[...]\n",
773 off);
774 }
775 fprintf(stderr, "%s\n", ctx->log + off);
776 }
777
f31645d1
DB
778 memset(ctx->log, 0, ctx->log_size);
779 }
780}
781
782static int bpf_log_realloc(struct bpf_elf_ctx *ctx)
783{
784 size_t log_size = ctx->log_size;
785 void *ptr;
786
787 if (!ctx->log) {
788 log_size = 65536;
789 } else {
790 log_size <<= 1;
791 if (log_size > (UINT_MAX >> 8))
792 return -EINVAL;
d937a74b 793 }
f31645d1
DB
794
795 ptr = realloc(ctx->log, log_size);
796 if (!ptr)
797 return -ENOMEM;
798
799 ctx->log = ptr;
800 ctx->log_size = log_size;
801
802 return 0;
11c39b5e
DB
803}
804
4dd3f50a
DB
805static int bpf_map_create(enum bpf_map_type type, uint32_t size_key,
806 uint32_t size_value, uint32_t max_elem,
807 uint32_t flags)
11c39b5e 808{
67584e3a
ND
809 union bpf_attr attr;
810
811 memset(&attr, 0, sizeof(attr));
812 attr.map_type = type;
813 attr.key_size = size_key;
814 attr.value_size = size_value;
815 attr.max_entries = max_elem;
4dd3f50a 816 attr.map_flags = flags;
11c39b5e
DB
817
818 return bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
819}
820
821static int bpf_prog_load(enum bpf_prog_type type, const struct bpf_insn *insns,
f31645d1
DB
822 size_t size_insns, const char *license, char *log,
823 size_t size_log)
11c39b5e 824{
67584e3a
ND
825 union bpf_attr attr;
826
827 memset(&attr, 0, sizeof(attr));
828 attr.prog_type = type;
829 attr.insns = bpf_ptr_to_u64(insns);
f31645d1 830 attr.insn_cnt = size_insns / sizeof(struct bpf_insn);
67584e3a 831 attr.license = bpf_ptr_to_u64(license);
11c39b5e 832
f31645d1
DB
833 if (size_log > 0) {
834 attr.log_buf = bpf_ptr_to_u64(log);
835 attr.log_size = size_log;
836 attr.log_level = 1;
32e93fb7
DB
837 }
838
11c39b5e
DB
839 return bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
840}
841
32e93fb7 842static int bpf_obj_pin(int fd, const char *pathname)
11c39b5e 843{
67584e3a
ND
844 union bpf_attr attr;
845
846 memset(&attr, 0, sizeof(attr));
847 attr.pathname = bpf_ptr_to_u64(pathname);
848 attr.bpf_fd = fd;
32e93fb7
DB
849
850 return bpf(BPF_OBJ_PIN, &attr, sizeof(attr));
851}
11c39b5e 852
32e93fb7
DB
853static int bpf_obj_hash(const char *object, uint8_t *out, size_t len)
854{
855 struct sockaddr_alg alg = {
856 .salg_family = AF_ALG,
857 .salg_type = "hash",
858 .salg_name = "sha1",
859 };
860 int ret, cfd, ofd, ffd;
861 struct stat stbuff;
862 ssize_t size;
863
864 if (!object || len != 20)
865 return -EINVAL;
866
867 cfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
868 if (cfd < 0) {
869 fprintf(stderr, "Cannot get AF_ALG socket: %s\n",
870 strerror(errno));
871 return cfd;
872 }
873
874 ret = bind(cfd, (struct sockaddr *)&alg, sizeof(alg));
875 if (ret < 0) {
876 fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
877 goto out_cfd;
878 }
879
880 ofd = accept(cfd, NULL, 0);
881 if (ofd < 0) {
882 fprintf(stderr, "Error accepting socket: %s\n",
883 strerror(errno));
884 ret = ofd;
885 goto out_cfd;
886 }
887
888 ffd = open(object, O_RDONLY);
889 if (ffd < 0) {
890 fprintf(stderr, "Error opening object %s: %s\n",
891 object, strerror(errno));
892 ret = ffd;
893 goto out_ofd;
894 }
895
32a121cb 896 ret = fstat(ffd, &stbuff);
32e93fb7
DB
897 if (ret < 0) {
898 fprintf(stderr, "Error doing fstat: %s\n",
899 strerror(errno));
900 goto out_ffd;
d937a74b 901 }
11c39b5e 902
32e93fb7
DB
903 size = sendfile(ofd, ffd, NULL, stbuff.st_size);
904 if (size != stbuff.st_size) {
905 fprintf(stderr, "Error from sendfile (%zd vs %zu bytes): %s\n",
906 size, stbuff.st_size, strerror(errno));
907 ret = -1;
908 goto out_ffd;
909 }
910
911 size = read(ofd, out, len);
912 if (size != len) {
913 fprintf(stderr, "Error from read (%zd vs %zu bytes): %s\n",
914 size, len, strerror(errno));
915 ret = -1;
916 } else {
917 ret = 0;
918 }
919out_ffd:
920 close(ffd);
921out_ofd:
922 close(ofd);
923out_cfd:
924 close(cfd);
925 return ret;
11c39b5e
DB
926}
927
32e93fb7 928static const char *bpf_get_obj_uid(const char *pathname)
11c39b5e 929{
32a121cb 930 static bool bpf_uid_cached;
32e93fb7
DB
931 static char bpf_uid[64];
932 uint8_t tmp[20];
933 int ret;
11c39b5e 934
32e93fb7
DB
935 if (bpf_uid_cached)
936 goto done;
11c39b5e 937
32e93fb7
DB
938 ret = bpf_obj_hash(pathname, tmp, sizeof(tmp));
939 if (ret) {
940 fprintf(stderr, "Object hashing failed!\n");
941 return NULL;
942 }
943
944 hexstring_n2a(tmp, sizeof(tmp), bpf_uid, sizeof(bpf_uid));
945 bpf_uid_cached = true;
946done:
947 return bpf_uid;
11c39b5e
DB
948}
949
32e93fb7
DB
950static int bpf_init_env(const char *pathname)
951{
952 struct rlimit limit = {
953 .rlim_cur = RLIM_INFINITY,
954 .rlim_max = RLIM_INFINITY,
955 };
956
957 /* Don't bother in case we fail! */
958 setrlimit(RLIMIT_MEMLOCK, &limit);
959
960 if (!bpf_get_tc_dir()) {
32a121cb 961 fprintf(stderr, "Continuing without mounted eBPF fs. Too old kernel?\n");
32e93fb7
DB
962 return 0;
963 }
964
965 if (!bpf_get_obj_uid(pathname))
966 return -1;
967
968 return 0;
6256f8c9
DB
969}
970
f6793eec
DB
971static const char *bpf_custom_pinning(const struct bpf_elf_ctx *ctx,
972 uint32_t pinning)
973{
974 struct bpf_hash_entry *entry;
975
976 entry = ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)];
977 while (entry && entry->pinning != pinning)
978 entry = entry->next;
979
980 return entry ? entry->subpath : NULL;
981}
982
983static bool bpf_no_pinning(const struct bpf_elf_ctx *ctx,
984 uint32_t pinning)
11c39b5e 985{
32e93fb7
DB
986 switch (pinning) {
987 case PIN_OBJECT_NS:
988 case PIN_GLOBAL_NS:
989 return false;
990 case PIN_NONE:
32e93fb7 991 return true;
f6793eec
DB
992 default:
993 return !bpf_custom_pinning(ctx, pinning);
32e93fb7
DB
994 }
995}
996
997static void bpf_make_pathname(char *pathname, size_t len, const char *name,
f6793eec 998 const struct bpf_elf_ctx *ctx, uint32_t pinning)
32e93fb7
DB
999{
1000 switch (pinning) {
1001 case PIN_OBJECT_NS:
1002 snprintf(pathname, len, "%s/%s/%s", bpf_get_tc_dir(),
1003 bpf_get_obj_uid(NULL), name);
1004 break;
1005 case PIN_GLOBAL_NS:
1006 snprintf(pathname, len, "%s/%s/%s", bpf_get_tc_dir(),
1007 BPF_DIR_GLOBALS, name);
1008 break;
f6793eec
DB
1009 default:
1010 snprintf(pathname, len, "%s/../%s/%s", bpf_get_tc_dir(),
1011 bpf_custom_pinning(ctx, pinning), name);
1012 break;
32e93fb7
DB
1013 }
1014}
1015
f6793eec
DB
1016static int bpf_probe_pinned(const char *name, const struct bpf_elf_ctx *ctx,
1017 uint32_t pinning)
32e93fb7
DB
1018{
1019 char pathname[PATH_MAX];
1020
f6793eec 1021 if (bpf_no_pinning(ctx, pinning) || !bpf_get_tc_dir())
32e93fb7
DB
1022 return 0;
1023
f6793eec 1024 bpf_make_pathname(pathname, sizeof(pathname), name, ctx, pinning);
32e93fb7
DB
1025 return bpf_obj_get(pathname);
1026}
1027
f6793eec 1028static int bpf_make_obj_path(void)
32e93fb7 1029{
f6793eec 1030 char tmp[PATH_MAX];
32e93fb7
DB
1031 int ret;
1032
f6793eec
DB
1033 snprintf(tmp, sizeof(tmp), "%s/%s", bpf_get_tc_dir(),
1034 bpf_get_obj_uid(NULL));
1035
1036 ret = mkdir(tmp, S_IRWXU);
1037 if (ret && errno != EEXIST) {
1038 fprintf(stderr, "mkdir %s failed: %s\n", tmp, strerror(errno));
1039 return ret;
1040 }
1041
1042 return 0;
1043}
1044
1045static int bpf_make_custom_path(const char *todo)
1046{
1047 char tmp[PATH_MAX], rem[PATH_MAX], *sub;
1048 int ret;
1049
1050 snprintf(tmp, sizeof(tmp), "%s/../", bpf_get_tc_dir());
1051 snprintf(rem, sizeof(rem), "%s/", todo);
1052 sub = strtok(rem, "/");
32e93fb7 1053
f6793eec
DB
1054 while (sub) {
1055 if (strlen(tmp) + strlen(sub) + 2 > PATH_MAX)
1056 return -EINVAL;
1057
1058 strcat(tmp, sub);
1059 strcat(tmp, "/");
32e93fb7 1060
f6793eec 1061 ret = mkdir(tmp, S_IRWXU);
32e93fb7 1062 if (ret && errno != EEXIST) {
f6793eec 1063 fprintf(stderr, "mkdir %s failed: %s\n", tmp,
32e93fb7
DB
1064 strerror(errno));
1065 return ret;
1066 }
f6793eec
DB
1067
1068 sub = strtok(NULL, "/");
32e93fb7
DB
1069 }
1070
f6793eec
DB
1071 return 0;
1072}
1073
1074static int bpf_place_pinned(int fd, const char *name,
1075 const struct bpf_elf_ctx *ctx, uint32_t pinning)
1076{
1077 char pathname[PATH_MAX];
1078 const char *tmp;
1079 int ret = 0;
1080
1081 if (bpf_no_pinning(ctx, pinning) || !bpf_get_tc_dir())
1082 return 0;
1083
1084 if (pinning == PIN_OBJECT_NS)
1085 ret = bpf_make_obj_path();
1086 else if ((tmp = bpf_custom_pinning(ctx, pinning)))
1087 ret = bpf_make_custom_path(tmp);
1088 if (ret < 0)
1089 return ret;
1090
1091 bpf_make_pathname(pathname, sizeof(pathname), name, ctx, pinning);
32e93fb7
DB
1092 return bpf_obj_pin(fd, pathname);
1093}
1094
f31645d1
DB
1095static void bpf_prog_report(int fd, const char *section,
1096 const struct bpf_elf_prog *prog,
1097 struct bpf_elf_ctx *ctx)
32e93fb7 1098{
afc1a200
DB
1099 unsigned int insns = prog->size / sizeof(struct bpf_insn);
1100
1101 fprintf(stderr, "\nProg section \'%s\' %s%s (%d)!\n", section,
f31645d1
DB
1102 fd < 0 ? "rejected: " : "loaded",
1103 fd < 0 ? strerror(errno) : "",
1104 fd < 0 ? errno : fd);
1105
1106 fprintf(stderr, " - Type: %u\n", prog->type);
afc1a200
DB
1107 fprintf(stderr, " - Instructions: %u (%u over limit)\n",
1108 insns, insns > BPF_MAXINSNS ? insns - BPF_MAXINSNS : 0);
f31645d1
DB
1109 fprintf(stderr, " - License: %s\n\n", prog->license);
1110
1111 bpf_dump_error(ctx, "Verifier analysis:\n\n");
1112}
32e93fb7 1113
f31645d1
DB
1114static int bpf_prog_attach(const char *section,
1115 const struct bpf_elf_prog *prog,
1116 struct bpf_elf_ctx *ctx)
1117{
1118 int tries = 0, fd;
1119retry:
32e93fb7
DB
1120 errno = 0;
1121 fd = bpf_prog_load(prog->type, prog->insns, prog->size,
f31645d1
DB
1122 prog->license, ctx->log, ctx->log_size);
1123 if (fd < 0 || ctx->verbose) {
1124 /* The verifier log is pretty chatty, sometimes so chatty
1125 * on larger programs, that we could fail to dump everything
1126 * into our buffer. Still, try to give a debuggable error
1127 * log for the user, so enlarge it and re-fail.
1128 */
1129 if (fd < 0 && (errno == ENOSPC || !ctx->log_size)) {
1130 if (tries++ < 6 && !bpf_log_realloc(ctx))
1131 goto retry;
1132
32a121cb 1133 fprintf(stderr, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
f31645d1
DB
1134 ctx->log_size, tries);
1135 return fd;
1136 }
1137
1138 bpf_prog_report(fd, section, prog, ctx);
32e93fb7
DB
1139 }
1140
1141 return fd;
1142}
1143
f31645d1
DB
1144static void bpf_map_report(int fd, const char *name,
1145 const struct bpf_elf_map *map,
1146 struct bpf_elf_ctx *ctx)
1147{
1148 fprintf(stderr, "Map object \'%s\' %s%s (%d)!\n", name,
1149 fd < 0 ? "rejected: " : "loaded",
1150 fd < 0 ? strerror(errno) : "",
1151 fd < 0 ? errno : fd);
1152
1153 fprintf(stderr, " - Type: %u\n", map->type);
1154 fprintf(stderr, " - Identifier: %u\n", map->id);
1155 fprintf(stderr, " - Pinning: %u\n", map->pinning);
1156 fprintf(stderr, " - Size key: %u\n", map->size_key);
1157 fprintf(stderr, " - Size value: %u\n", map->size_value);
4dd3f50a
DB
1158 fprintf(stderr, " - Max elems: %u\n", map->max_elem);
1159 fprintf(stderr, " - Flags: %#x\n\n", map->flags);
f31645d1
DB
1160}
1161
32e93fb7 1162static int bpf_map_attach(const char *name, const struct bpf_elf_map *map,
f31645d1 1163 struct bpf_elf_ctx *ctx)
32e93fb7
DB
1164{
1165 int fd, ret;
1166
f6793eec 1167 fd = bpf_probe_pinned(name, ctx, map->pinning);
32e93fb7 1168 if (fd > 0) {
91d88eeb
DB
1169 ret = bpf_map_selfcheck_pinned(fd, map,
1170 offsetof(struct bpf_elf_map,
1171 id));
9e607f2e
DB
1172 if (ret < 0) {
1173 close(fd);
1174 fprintf(stderr, "Map \'%s\' self-check failed!\n",
1175 name);
1176 return ret;
1177 }
f31645d1 1178 if (ctx->verbose)
32e93fb7
DB
1179 fprintf(stderr, "Map \'%s\' loaded as pinned!\n",
1180 name);
1181 return fd;
1182 }
1183
1184 errno = 0;
1185 fd = bpf_map_create(map->type, map->size_key, map->size_value,
4dd3f50a 1186 map->max_elem, map->flags);
f31645d1
DB
1187 if (fd < 0 || ctx->verbose) {
1188 bpf_map_report(fd, name, map, ctx);
32e93fb7
DB
1189 if (fd < 0)
1190 return fd;
1191 }
1192
f6793eec 1193 ret = bpf_place_pinned(fd, name, ctx, map->pinning);
32e93fb7
DB
1194 if (ret < 0 && errno != EEXIST) {
1195 fprintf(stderr, "Could not pin %s map: %s\n", name,
1196 strerror(errno));
1197 close(fd);
1198 return ret;
1199 }
1200
1201 return fd;
1202}
1203
32e93fb7
DB
1204static const char *bpf_str_tab_name(const struct bpf_elf_ctx *ctx,
1205 const GElf_Sym *sym)
1206{
1207 return ctx->str_tab->d_buf + sym->st_name;
1208}
1209
1210static const char *bpf_map_fetch_name(struct bpf_elf_ctx *ctx, int which)
1211{
1212 GElf_Sym sym;
11c39b5e
DB
1213 int i;
1214
32e93fb7
DB
1215 for (i = 0; i < ctx->sym_num; i++) {
1216 if (gelf_getsym(ctx->sym_tab, i, &sym) != &sym)
1217 continue;
1218
5230a2ed
DB
1219 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1220 GELF_ST_TYPE(sym.st_info) != STT_NOTYPE ||
32e93fb7
DB
1221 sym.st_shndx != ctx->sec_maps ||
1222 sym.st_value / sizeof(struct bpf_elf_map) != which)
1223 continue;
1224
1225 return bpf_str_tab_name(ctx, &sym);
11c39b5e 1226 }
32e93fb7
DB
1227
1228 return NULL;
11c39b5e
DB
1229}
1230
32e93fb7 1231static int bpf_maps_attach_all(struct bpf_elf_ctx *ctx)
11c39b5e 1232{
32e93fb7
DB
1233 const char *map_name;
1234 int i, fd;
11c39b5e 1235
32e93fb7
DB
1236 for (i = 0; i < ctx->map_num; i++) {
1237 map_name = bpf_map_fetch_name(ctx, i);
1238 if (!map_name)
1239 return -EIO;
11c39b5e 1240
f31645d1 1241 fd = bpf_map_attach(map_name, &ctx->maps[i], ctx);
32e93fb7
DB
1242 if (fd < 0)
1243 return fd;
11c39b5e 1244
32e93fb7 1245 ctx->map_fds[i] = fd;
11c39b5e
DB
1246 }
1247
1248 return 0;
11c39b5e
DB
1249}
1250
32e93fb7
DB
1251static int bpf_fill_section_data(struct bpf_elf_ctx *ctx, int section,
1252 struct bpf_elf_sec_data *data)
11c39b5e 1253{
32e93fb7 1254 Elf_Data *sec_edata;
11c39b5e
DB
1255 GElf_Shdr sec_hdr;
1256 Elf_Scn *sec_fd;
11c39b5e
DB
1257 char *sec_name;
1258
32e93fb7 1259 memset(data, 0, sizeof(*data));
11c39b5e 1260
32e93fb7 1261 sec_fd = elf_getscn(ctx->elf_fd, section);
11c39b5e
DB
1262 if (!sec_fd)
1263 return -EINVAL;
11c39b5e
DB
1264 if (gelf_getshdr(sec_fd, &sec_hdr) != &sec_hdr)
1265 return -EIO;
1266
32e93fb7 1267 sec_name = elf_strptr(ctx->elf_fd, ctx->elf_hdr.e_shstrndx,
11c39b5e
DB
1268 sec_hdr.sh_name);
1269 if (!sec_name || !sec_hdr.sh_size)
1270 return -ENOENT;
1271
1272 sec_edata = elf_getdata(sec_fd, NULL);
1273 if (!sec_edata || elf_getdata(sec_fd, sec_edata))
1274 return -EIO;
1275
32e93fb7 1276 memcpy(&data->sec_hdr, &sec_hdr, sizeof(sec_hdr));
11c39b5e 1277
32e93fb7
DB
1278 data->sec_name = sec_name;
1279 data->sec_data = sec_edata;
11c39b5e
DB
1280 return 0;
1281}
1282
32e93fb7
DB
1283static int bpf_fetch_maps(struct bpf_elf_ctx *ctx, int section,
1284 struct bpf_elf_sec_data *data)
11c39b5e 1285{
32e93fb7
DB
1286 if (data->sec_data->d_size % sizeof(struct bpf_elf_map) != 0)
1287 return -EINVAL;
11c39b5e 1288
32e93fb7
DB
1289 ctx->map_num = data->sec_data->d_size / sizeof(struct bpf_elf_map);
1290 ctx->sec_maps = section;
1291 ctx->sec_done[section] = true;
11c39b5e 1292
32e93fb7
DB
1293 if (ctx->map_num > ARRAY_SIZE(ctx->map_fds)) {
1294 fprintf(stderr, "Too many BPF maps in ELF section!\n");
1295 return -ENOMEM;
1296 }
11c39b5e 1297
32e93fb7
DB
1298 memcpy(ctx->maps, data->sec_data->d_buf, data->sec_data->d_size);
1299 return 0;
1300}
11c39b5e 1301
32e93fb7
DB
1302static int bpf_fetch_license(struct bpf_elf_ctx *ctx, int section,
1303 struct bpf_elf_sec_data *data)
1304{
1305 if (data->sec_data->d_size > sizeof(ctx->license))
1306 return -ENOMEM;
11c39b5e 1307
32e93fb7
DB
1308 memcpy(ctx->license, data->sec_data->d_buf, data->sec_data->d_size);
1309 ctx->sec_done[section] = true;
1310 return 0;
1311}
11c39b5e 1312
32e93fb7
DB
1313static int bpf_fetch_symtab(struct bpf_elf_ctx *ctx, int section,
1314 struct bpf_elf_sec_data *data)
1315{
1316 ctx->sym_tab = data->sec_data;
1317 ctx->sym_num = data->sec_hdr.sh_size / data->sec_hdr.sh_entsize;
1318 ctx->sec_done[section] = true;
11c39b5e
DB
1319 return 0;
1320}
1321
32e93fb7
DB
1322static int bpf_fetch_strtab(struct bpf_elf_ctx *ctx, int section,
1323 struct bpf_elf_sec_data *data)
11c39b5e 1324{
32e93fb7
DB
1325 ctx->str_tab = data->sec_data;
1326 ctx->sec_done[section] = true;
1327 return 0;
1328}
11c39b5e 1329
afc1a200
DB
1330static bool bpf_has_map_data(const struct bpf_elf_ctx *ctx)
1331{
1332 return ctx->sym_tab && ctx->str_tab && ctx->sec_maps;
1333}
1334
32e93fb7
DB
1335static int bpf_fetch_ancillary(struct bpf_elf_ctx *ctx)
1336{
1337 struct bpf_elf_sec_data data;
1338 int i, ret = -1;
11c39b5e 1339
32e93fb7
DB
1340 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
1341 ret = bpf_fill_section_data(ctx, i, &data);
11c39b5e
DB
1342 if (ret < 0)
1343 continue;
1344
cce3d466
DB
1345 if (data.sec_hdr.sh_type == SHT_PROGBITS &&
1346 !strcmp(data.sec_name, ELF_SECTION_MAPS))
32e93fb7 1347 ret = bpf_fetch_maps(ctx, i, &data);
cce3d466
DB
1348 else if (data.sec_hdr.sh_type == SHT_PROGBITS &&
1349 !strcmp(data.sec_name, ELF_SECTION_LICENSE))
32e93fb7 1350 ret = bpf_fetch_license(ctx, i, &data);
cce3d466
DB
1351 else if (data.sec_hdr.sh_type == SHT_SYMTAB &&
1352 !strcmp(data.sec_name, ".symtab"))
32e93fb7
DB
1353 ret = bpf_fetch_symtab(ctx, i, &data);
1354 else if (data.sec_hdr.sh_type == SHT_STRTAB &&
cce3d466 1355 !strcmp(data.sec_name, ".strtab"))
32e93fb7
DB
1356 ret = bpf_fetch_strtab(ctx, i, &data);
1357 if (ret < 0) {
afc1a200 1358 fprintf(stderr, "Error parsing section %d! Perhaps check with readelf -a?\n",
32a121cb 1359 i);
32e93fb7 1360 break;
11c39b5e 1361 }
32e93fb7
DB
1362 }
1363
afc1a200 1364 if (bpf_has_map_data(ctx)) {
32e93fb7
DB
1365 ret = bpf_maps_attach_all(ctx);
1366 if (ret < 0) {
1367 fprintf(stderr, "Error loading maps into kernel!\n");
1368 return ret;
11c39b5e
DB
1369 }
1370 }
1371
1372 return ret;
1373}
1374
32e93fb7 1375static int bpf_fetch_prog(struct bpf_elf_ctx *ctx, const char *section)
11c39b5e 1376{
32e93fb7
DB
1377 struct bpf_elf_sec_data data;
1378 struct bpf_elf_prog prog;
1379 int ret, i, fd = -1;
11c39b5e 1380
32e93fb7
DB
1381 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
1382 if (ctx->sec_done[i])
11c39b5e
DB
1383 continue;
1384
32e93fb7 1385 ret = bpf_fill_section_data(ctx, i, &data);
cce3d466
DB
1386 if (ret < 0 ||
1387 !(data.sec_hdr.sh_type == SHT_PROGBITS &&
1388 data.sec_hdr.sh_flags & SHF_EXECINSTR &&
1389 !strcmp(data.sec_name, section)))
11c39b5e
DB
1390 continue;
1391
32e93fb7
DB
1392 memset(&prog, 0, sizeof(prog));
1393 prog.type = ctx->type;
1394 prog.insns = data.sec_data->d_buf;
1395 prog.size = data.sec_data->d_size;
1396 prog.license = ctx->license;
11c39b5e 1397
f31645d1 1398 fd = bpf_prog_attach(section, &prog, ctx);
32e93fb7 1399 if (fd < 0)
afc1a200 1400 break;
11c39b5e 1401
32e93fb7 1402 ctx->sec_done[i] = true;
11c39b5e
DB
1403 break;
1404 }
1405
32e93fb7 1406 return fd;
11c39b5e
DB
1407}
1408
32e93fb7
DB
1409static int bpf_apply_relo_data(struct bpf_elf_ctx *ctx,
1410 struct bpf_elf_sec_data *data_relo,
1411 struct bpf_elf_sec_data *data_insn)
11c39b5e 1412{
32e93fb7
DB
1413 Elf_Data *idata = data_insn->sec_data;
1414 GElf_Shdr *rhdr = &data_relo->sec_hdr;
1415 int relo_ent, relo_num = rhdr->sh_size / rhdr->sh_entsize;
1416 struct bpf_insn *insns = idata->d_buf;
1417 unsigned int num_insns = idata->d_size / sizeof(*insns);
11c39b5e 1418
32e93fb7
DB
1419 for (relo_ent = 0; relo_ent < relo_num; relo_ent++) {
1420 unsigned int ioff, rmap;
1421 GElf_Rel relo;
1422 GElf_Sym sym;
1423
1424 if (gelf_getrel(data_relo->sec_data, relo_ent, &relo) != &relo)
1425 return -EIO;
1426
1427 ioff = relo.r_offset / sizeof(struct bpf_insn);
1428 if (ioff >= num_insns ||
a576c6b9 1429 insns[ioff].code != (BPF_LD | BPF_IMM | BPF_DW)) {
32a121cb 1430 fprintf(stderr, "ELF contains relo data for non ld64 instruction at offset %u! Compiler bug?!\n",
a576c6b9
DB
1431 ioff);
1432 if (ioff < num_insns &&
1433 insns[ioff].code == (BPF_JMP | BPF_CALL))
32a121cb 1434 fprintf(stderr, " - Try to annotate functions with always_inline attribute!\n");
32e93fb7 1435 return -EINVAL;
a576c6b9 1436 }
32e93fb7
DB
1437
1438 if (gelf_getsym(ctx->sym_tab, GELF_R_SYM(relo.r_info), &sym) != &sym)
1439 return -EIO;
2486337a 1440 if (sym.st_shndx != ctx->sec_maps) {
32a121cb 1441 fprintf(stderr, "ELF contains non-map related relo data in entry %u pointing to section %u! Compiler bug?!\n",
2486337a
DB
1442 relo_ent, sym.st_shndx);
1443 return -EIO;
1444 }
32e93fb7
DB
1445
1446 rmap = sym.st_value / sizeof(struct bpf_elf_map);
1447 if (rmap >= ARRAY_SIZE(ctx->map_fds))
1448 return -EINVAL;
1449 if (!ctx->map_fds[rmap])
1450 return -EINVAL;
1451
1452 if (ctx->verbose)
32a121cb 1453 fprintf(stderr, "Map \'%s\' (%d) injected into prog section \'%s\' at offset %u!\n",
32e93fb7
DB
1454 bpf_str_tab_name(ctx, &sym), ctx->map_fds[rmap],
1455 data_insn->sec_name, ioff);
11c39b5e 1456
32e93fb7
DB
1457 insns[ioff].src_reg = BPF_PSEUDO_MAP_FD;
1458 insns[ioff].imm = ctx->map_fds[rmap];
1459 }
1460
1461 return 0;
1462}
1463
afc1a200
DB
1464static int bpf_fetch_prog_relo(struct bpf_elf_ctx *ctx, const char *section,
1465 bool *lderr)
32e93fb7
DB
1466{
1467 struct bpf_elf_sec_data data_relo, data_insn;
1468 struct bpf_elf_prog prog;
1469 int ret, idx, i, fd = -1;
1470
1471 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
1472 ret = bpf_fill_section_data(ctx, i, &data_relo);
1473 if (ret < 0 || data_relo.sec_hdr.sh_type != SHT_REL)
11c39b5e
DB
1474 continue;
1475
32e93fb7
DB
1476 idx = data_relo.sec_hdr.sh_info;
1477 ret = bpf_fill_section_data(ctx, idx, &data_insn);
cce3d466
DB
1478 if (ret < 0 ||
1479 !(data_insn.sec_hdr.sh_type == SHT_PROGBITS &&
1480 data_insn.sec_hdr.sh_flags & SHF_EXECINSTR &&
1481 !strcmp(data_insn.sec_name, section)))
11c39b5e 1482 continue;
32e93fb7
DB
1483
1484 ret = bpf_apply_relo_data(ctx, &data_relo, &data_insn);
1485 if (ret < 0)
11c39b5e
DB
1486 continue;
1487
32e93fb7
DB
1488 memset(&prog, 0, sizeof(prog));
1489 prog.type = ctx->type;
1490 prog.insns = data_insn.sec_data->d_buf;
1491 prog.size = data_insn.sec_data->d_size;
1492 prog.license = ctx->license;
1493
f31645d1 1494 fd = bpf_prog_attach(section, &prog, ctx);
afc1a200
DB
1495 if (fd < 0) {
1496 *lderr = true;
1497 break;
1498 }
11c39b5e 1499
32e93fb7
DB
1500 ctx->sec_done[i] = true;
1501 ctx->sec_done[idx] = true;
11c39b5e
DB
1502 break;
1503 }
1504
32e93fb7 1505 return fd;
11c39b5e
DB
1506}
1507
32e93fb7 1508static int bpf_fetch_prog_sec(struct bpf_elf_ctx *ctx, const char *section)
473d7840 1509{
afc1a200 1510 bool lderr = false;
473d7840
DB
1511 int ret = -1;
1512
afc1a200
DB
1513 if (bpf_has_map_data(ctx))
1514 ret = bpf_fetch_prog_relo(ctx, section, &lderr);
1515 if (ret < 0 && !lderr)
32e93fb7
DB
1516 ret = bpf_fetch_prog(ctx, section);
1517
473d7840
DB
1518 return ret;
1519}
1520
910b543d
DB
1521static int bpf_find_map_by_id(struct bpf_elf_ctx *ctx, uint32_t id)
1522{
1523 int i;
1524
1525 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++)
1526 if (ctx->map_fds[i] && ctx->maps[i].id == id &&
1527 ctx->maps[i].type == BPF_MAP_TYPE_PROG_ARRAY)
1528 return i;
1529 return -1;
1530}
1531
32e93fb7 1532static int bpf_fill_prog_arrays(struct bpf_elf_ctx *ctx)
473d7840 1533{
32e93fb7
DB
1534 struct bpf_elf_sec_data data;
1535 uint32_t map_id, key_id;
910b543d 1536 int fd, i, ret, idx;
473d7840 1537
32e93fb7
DB
1538 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
1539 if (ctx->sec_done[i])
473d7840
DB
1540 continue;
1541
32e93fb7 1542 ret = bpf_fill_section_data(ctx, i, &data);
473d7840
DB
1543 if (ret < 0)
1544 continue;
1545
910b543d
DB
1546 ret = sscanf(data.sec_name, "%i/%i", &map_id, &key_id);
1547 if (ret != 2)
32e93fb7 1548 continue;
910b543d
DB
1549
1550 idx = bpf_find_map_by_id(ctx, map_id);
1551 if (idx < 0)
473d7840
DB
1552 continue;
1553
32e93fb7
DB
1554 fd = bpf_fetch_prog_sec(ctx, data.sec_name);
1555 if (fd < 0)
473d7840
DB
1556 return -EIO;
1557
910b543d
DB
1558 ret = bpf_map_update(ctx->map_fds[idx], &key_id,
1559 &fd, BPF_ANY);
afc1a200
DB
1560 if (ret < 0) {
1561 if (errno == E2BIG)
1562 fprintf(stderr, "Tail call key %u for map %u out of bounds?\n",
1563 key_id, map_id);
1564 return -errno;
1565 }
473d7840 1566
32e93fb7 1567 ctx->sec_done[i] = true;
473d7840
DB
1568 }
1569
1570 return 0;
1571}
1572
32e93fb7 1573static void bpf_save_finfo(struct bpf_elf_ctx *ctx)
11c39b5e 1574{
32e93fb7
DB
1575 struct stat st;
1576 int ret;
11c39b5e 1577
32e93fb7 1578 memset(&ctx->stat, 0, sizeof(ctx->stat));
11c39b5e 1579
32e93fb7
DB
1580 ret = fstat(ctx->obj_fd, &st);
1581 if (ret < 0) {
1582 fprintf(stderr, "Stat of elf file failed: %s\n",
1583 strerror(errno));
1584 return;
1585 }
11c39b5e 1586
32e93fb7
DB
1587 ctx->stat.st_dev = st.st_dev;
1588 ctx->stat.st_ino = st.st_ino;
1589}
1590
f6793eec
DB
1591static int bpf_read_pin_mapping(FILE *fp, uint32_t *id, char *path)
1592{
1593 char buff[PATH_MAX];
1594
1595 while (fgets(buff, sizeof(buff), fp)) {
1596 char *ptr = buff;
1597
1598 while (*ptr == ' ' || *ptr == '\t')
1599 ptr++;
1600
1601 if (*ptr == '#' || *ptr == '\n' || *ptr == 0)
1602 continue;
1603
1604 if (sscanf(ptr, "%i %s\n", id, path) != 2 &&
1605 sscanf(ptr, "%i %s #", id, path) != 2) {
1606 strcpy(path, ptr);
1607 return -1;
1608 }
1609
1610 return 1;
1611 }
1612
1613 return 0;
1614}
1615
1616static bool bpf_pinning_reserved(uint32_t pinning)
1617{
1618 switch (pinning) {
1619 case PIN_NONE:
1620 case PIN_OBJECT_NS:
1621 case PIN_GLOBAL_NS:
1622 return true;
1623 default:
1624 return false;
1625 }
1626}
1627
1628static void bpf_hash_init(struct bpf_elf_ctx *ctx, const char *db_file)
1629{
1630 struct bpf_hash_entry *entry;
1631 char subpath[PATH_MAX];
1632 uint32_t pinning;
1633 FILE *fp;
1634 int ret;
1635
1636 fp = fopen(db_file, "r");
1637 if (!fp)
1638 return;
1639
1640 memset(subpath, 0, sizeof(subpath));
1641 while ((ret = bpf_read_pin_mapping(fp, &pinning, subpath))) {
1642 if (ret == -1) {
1643 fprintf(stderr, "Database %s is corrupted at: %s\n",
1644 db_file, subpath);
1645 fclose(fp);
1646 return;
1647 }
1648
1649 if (bpf_pinning_reserved(pinning)) {
32a121cb
SH
1650 fprintf(stderr, "Database %s, id %u is reserved - ignoring!\n",
1651 db_file, pinning);
f6793eec
DB
1652 continue;
1653 }
1654
1655 entry = malloc(sizeof(*entry));
1656 if (!entry) {
1657 fprintf(stderr, "No memory left for db entry!\n");
1658 continue;
1659 }
1660
1661 entry->pinning = pinning;
1662 entry->subpath = strdup(subpath);
1663 if (!entry->subpath) {
1664 fprintf(stderr, "No memory left for db entry!\n");
1665 free(entry);
1666 continue;
1667 }
1668
1669 entry->next = ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)];
1670 ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)] = entry;
1671 }
1672
1673 fclose(fp);
1674}
1675
1676static void bpf_hash_destroy(struct bpf_elf_ctx *ctx)
1677{
1678 struct bpf_hash_entry *entry;
1679 int i;
1680
1681 for (i = 0; i < ARRAY_SIZE(ctx->ht); i++) {
1682 while ((entry = ctx->ht[i]) != NULL) {
1683 ctx->ht[i] = entry->next;
1684 free((char *)entry->subpath);
1685 free(entry);
1686 }
1687 }
1688}
1689
8187b012
DB
1690static int bpf_elf_check_ehdr(const struct bpf_elf_ctx *ctx)
1691{
1692 if (ctx->elf_hdr.e_type != ET_REL ||
1693 ctx->elf_hdr.e_machine != 0 ||
1694 ctx->elf_hdr.e_version != EV_CURRENT) {
1695 fprintf(stderr, "ELF format error, ELF file not for eBPF?\n");
1696 return -EINVAL;
1697 }
1698
1699 switch (ctx->elf_hdr.e_ident[EI_DATA]) {
1700 default:
1701 fprintf(stderr, "ELF format error, wrong endianness info?\n");
1702 return -EINVAL;
1703 case ELFDATA2LSB:
1704 if (htons(1) == 1) {
1705 fprintf(stderr,
1706 "We are big endian, eBPF object is little endian!\n");
1707 return -EIO;
1708 }
1709 break;
1710 case ELFDATA2MSB:
1711 if (htons(1) != 1) {
1712 fprintf(stderr,
1713 "We are little endian, eBPF object is big endian!\n");
1714 return -EIO;
1715 }
1716 break;
1717 }
1718
1719 return 0;
1720}
1721
32e93fb7
DB
1722static int bpf_elf_ctx_init(struct bpf_elf_ctx *ctx, const char *pathname,
1723 enum bpf_prog_type type, bool verbose)
1724{
1725 int ret = -EINVAL;
1726
1727 if (elf_version(EV_CURRENT) == EV_NONE ||
1728 bpf_init_env(pathname))
1729 return ret;
1730
1731 memset(ctx, 0, sizeof(*ctx));
1732 ctx->verbose = verbose;
1733 ctx->type = type;
1734
1735 ctx->obj_fd = open(pathname, O_RDONLY);
1736 if (ctx->obj_fd < 0)
1737 return ctx->obj_fd;
1738
1739 ctx->elf_fd = elf_begin(ctx->obj_fd, ELF_C_READ, NULL);
1740 if (!ctx->elf_fd) {
11c39b5e 1741 ret = -EINVAL;
32e93fb7 1742 goto out_fd;
11c39b5e
DB
1743 }
1744
8187b012
DB
1745 if (elf_kind(ctx->elf_fd) != ELF_K_ELF) {
1746 ret = -EINVAL;
1747 goto out_fd;
1748 }
1749
32e93fb7
DB
1750 if (gelf_getehdr(ctx->elf_fd, &ctx->elf_hdr) !=
1751 &ctx->elf_hdr) {
11c39b5e
DB
1752 ret = -EIO;
1753 goto out_elf;
1754 }
1755
8187b012
DB
1756 ret = bpf_elf_check_ehdr(ctx);
1757 if (ret < 0)
1758 goto out_elf;
1759
32e93fb7
DB
1760 ctx->sec_done = calloc(ctx->elf_hdr.e_shnum,
1761 sizeof(*(ctx->sec_done)));
1762 if (!ctx->sec_done) {
11c39b5e
DB
1763 ret = -ENOMEM;
1764 goto out_elf;
1765 }
1766
f31645d1
DB
1767 if (ctx->verbose && bpf_log_realloc(ctx)) {
1768 ret = -ENOMEM;
1769 goto out_free;
1770 }
1771
32e93fb7 1772 bpf_save_finfo(ctx);
f6793eec
DB
1773 bpf_hash_init(ctx, CONFDIR "/bpf_pinning");
1774
32e93fb7 1775 return 0;
f31645d1
DB
1776out_free:
1777 free(ctx->sec_done);
32e93fb7
DB
1778out_elf:
1779 elf_end(ctx->elf_fd);
1780out_fd:
1781 close(ctx->obj_fd);
1782 return ret;
1783}
d937a74b 1784
32e93fb7
DB
1785static int bpf_maps_count(struct bpf_elf_ctx *ctx)
1786{
1787 int i, count = 0;
11c39b5e 1788
32e93fb7
DB
1789 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++) {
1790 if (!ctx->map_fds[i])
1791 break;
1792 count++;
1793 }
473d7840 1794
32e93fb7
DB
1795 return count;
1796}
6256f8c9 1797
32e93fb7
DB
1798static void bpf_maps_teardown(struct bpf_elf_ctx *ctx)
1799{
1800 int i;
1801
1802 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++) {
1803 if (ctx->map_fds[i])
1804 close(ctx->map_fds[i]);
473d7840 1805 }
32e93fb7
DB
1806}
1807
1808static void bpf_elf_ctx_destroy(struct bpf_elf_ctx *ctx, bool failure)
1809{
1810 if (failure)
1811 bpf_maps_teardown(ctx);
473d7840 1812
f6793eec 1813 bpf_hash_destroy(ctx);
f31645d1 1814
32e93fb7 1815 free(ctx->sec_done);
f31645d1
DB
1816 free(ctx->log);
1817
32e93fb7
DB
1818 elf_end(ctx->elf_fd);
1819 close(ctx->obj_fd);
1820}
6256f8c9 1821
32e93fb7 1822static struct bpf_elf_ctx __ctx;
6256f8c9 1823
32e93fb7
DB
1824static int bpf_obj_open(const char *pathname, enum bpf_prog_type type,
1825 const char *section, bool verbose)
1826{
1827 struct bpf_elf_ctx *ctx = &__ctx;
1828 int fd = 0, ret;
6256f8c9 1829
32e93fb7
DB
1830 ret = bpf_elf_ctx_init(ctx, pathname, type, verbose);
1831 if (ret < 0) {
1832 fprintf(stderr, "Cannot initialize ELF context!\n");
1833 return ret;
1834 }
6256f8c9 1835
32e93fb7
DB
1836 ret = bpf_fetch_ancillary(ctx);
1837 if (ret < 0) {
1838 fprintf(stderr, "Error fetching ELF ancillary data!\n");
1839 goto out;
1840 }
1841
1842 fd = bpf_fetch_prog_sec(ctx, section);
1843 if (fd < 0) {
1844 fprintf(stderr, "Error fetching program/map!\n");
1845 ret = fd;
1846 goto out;
1847 }
1848
1849 ret = bpf_fill_prog_arrays(ctx);
1850 if (ret < 0)
1851 fprintf(stderr, "Error filling program arrays!\n");
11c39b5e 1852out:
32e93fb7
DB
1853 bpf_elf_ctx_destroy(ctx, ret < 0);
1854 if (ret < 0) {
1855 if (fd)
1856 close(fd);
1857 return ret;
1858 }
1859
1860 return fd;
6256f8c9 1861}
11c39b5e 1862
6256f8c9 1863static int
4bd62446
DB
1864bpf_map_set_send(int fd, struct sockaddr_un *addr, unsigned int addr_len,
1865 const struct bpf_map_data *aux, unsigned int entries)
6256f8c9
DB
1866{
1867 struct bpf_map_set_msg msg;
1868 int *cmsg_buf, min_fd;
1869 char *amsg_buf;
1870 int i;
1871
1872 memset(&msg, 0, sizeof(msg));
1873
1874 msg.aux.uds_ver = BPF_SCM_AUX_VER;
4bd62446 1875 msg.aux.num_ent = entries;
6256f8c9
DB
1876
1877 strncpy(msg.aux.obj_name, aux->obj, sizeof(msg.aux.obj_name));
1878 memcpy(&msg.aux.obj_st, aux->st, sizeof(msg.aux.obj_st));
1879
1880 cmsg_buf = bpf_map_set_init(&msg, addr, addr_len);
1881 amsg_buf = (char *)msg.aux.ent;
1882
4bd62446 1883 for (i = 0; i < entries; i += min_fd) {
6256f8c9
DB
1884 int ret;
1885
4bd62446 1886 min_fd = min(BPF_SCM_MAX_FDS * 1U, entries - i);
6256f8c9
DB
1887 bpf_map_set_init_single(&msg, min_fd);
1888
1889 memcpy(cmsg_buf, &aux->fds[i], sizeof(aux->fds[0]) * min_fd);
1890 memcpy(amsg_buf, &aux->ent[i], sizeof(aux->ent[0]) * min_fd);
1891
1892 ret = sendmsg(fd, &msg.hdr, 0);
1893 if (ret <= 0)
1894 return ret ? : -1;
1895 }
1896
1897 return 0;
11c39b5e
DB
1898}
1899
4bd62446
DB
1900static int
1901bpf_map_set_recv(int fd, int *fds, struct bpf_map_aux *aux,
1902 unsigned int entries)
1903{
1904 struct bpf_map_set_msg msg;
1905 int *cmsg_buf, min_fd;
1906 char *amsg_buf, *mmsg_buf;
1907 unsigned int needed = 1;
1908 int i;
1909
1910 cmsg_buf = bpf_map_set_init(&msg, NULL, 0);
1911 amsg_buf = (char *)msg.aux.ent;
1912 mmsg_buf = (char *)&msg.aux;
1913
1914 for (i = 0; i < min(entries, needed); i += min_fd) {
1915 struct cmsghdr *cmsg;
1916 int ret;
1917
1918 min_fd = min(entries, entries - i);
1919 bpf_map_set_init_single(&msg, min_fd);
1920
1921 ret = recvmsg(fd, &msg.hdr, 0);
1922 if (ret <= 0)
1923 return ret ? : -1;
1924
1925 cmsg = CMSG_FIRSTHDR(&msg.hdr);
1926 if (!cmsg || cmsg->cmsg_type != SCM_RIGHTS)
1927 return -EINVAL;
1928 if (msg.hdr.msg_flags & MSG_CTRUNC)
1929 return -EIO;
1930 if (msg.aux.uds_ver != BPF_SCM_AUX_VER)
1931 return -ENOSYS;
1932
1933 min_fd = (cmsg->cmsg_len - sizeof(*cmsg)) / sizeof(fd);
1934 if (min_fd > entries || min_fd <= 0)
1935 return -EINVAL;
1936
1937 memcpy(&fds[i], cmsg_buf, sizeof(fds[0]) * min_fd);
1938 memcpy(&aux->ent[i], amsg_buf, sizeof(aux->ent[0]) * min_fd);
1939 memcpy(aux, mmsg_buf, offsetof(struct bpf_map_aux, ent));
1940
1941 needed = aux->num_ent;
1942 }
1943
1944 return 0;
1945}
1946
1947int bpf_send_map_fds(const char *path, const char *obj)
6256f8c9 1948{
32e93fb7 1949 struct bpf_elf_ctx *ctx = &__ctx;
6256f8c9
DB
1950 struct sockaddr_un addr;
1951 struct bpf_map_data bpf_aux;
1952 int fd, ret;
1953
1954 fd = socket(AF_UNIX, SOCK_DGRAM, 0);
1955 if (fd < 0) {
1956 fprintf(stderr, "Cannot open socket: %s\n",
1957 strerror(errno));
1958 return -1;
1959 }
1960
1961 memset(&addr, 0, sizeof(addr));
1962 addr.sun_family = AF_UNIX;
1963 strncpy(addr.sun_path, path, sizeof(addr.sun_path));
1964
1965 ret = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
1966 if (ret < 0) {
1967 fprintf(stderr, "Cannot connect to %s: %s\n",
1968 path, strerror(errno));
1969 return -1;
1970 }
1971
1972 memset(&bpf_aux, 0, sizeof(bpf_aux));
1973
32e93fb7
DB
1974 bpf_aux.fds = ctx->map_fds;
1975 bpf_aux.ent = ctx->maps;
1976 bpf_aux.st = &ctx->stat;
6256f8c9 1977 bpf_aux.obj = obj;
6256f8c9 1978
4bd62446 1979 ret = bpf_map_set_send(fd, &addr, sizeof(addr), &bpf_aux,
32e93fb7 1980 bpf_maps_count(ctx));
6256f8c9 1981 if (ret < 0)
4bd62446
DB
1982 fprintf(stderr, "Cannot send fds to %s: %s\n",
1983 path, strerror(errno));
1984
32e93fb7 1985 bpf_maps_teardown(ctx);
4bd62446
DB
1986 close(fd);
1987 return ret;
1988}
1989
1990int bpf_recv_map_fds(const char *path, int *fds, struct bpf_map_aux *aux,
1991 unsigned int entries)
1992{
1993 struct sockaddr_un addr;
1994 int fd, ret;
1995
1996 fd = socket(AF_UNIX, SOCK_DGRAM, 0);
1997 if (fd < 0) {
1998 fprintf(stderr, "Cannot open socket: %s\n",
1999 strerror(errno));
2000 return -1;
2001 }
2002
2003 memset(&addr, 0, sizeof(addr));
2004 addr.sun_family = AF_UNIX;
2005 strncpy(addr.sun_path, path, sizeof(addr.sun_path));
2006
2007 ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
2008 if (ret < 0) {
2009 fprintf(stderr, "Cannot bind to socket: %s\n",
2010 strerror(errno));
2011 return -1;
2012 }
2013
2014 ret = bpf_map_set_recv(fd, fds, aux, entries);
2015 if (ret < 0)
2016 fprintf(stderr, "Cannot recv fds from %s: %s\n",
6256f8c9
DB
2017 path, strerror(errno));
2018
4bd62446 2019 unlink(addr.sun_path);
6256f8c9
DB
2020 close(fd);
2021 return ret;
2022}
11c39b5e 2023#endif /* HAVE_ELF */