0001
0002
0003
0004
0005
0006
0007
0008
0009
0010 #define _GNU_SOURCE
0011
0012 #include <stdio.h>
0013 #include <stdlib.h>
0014 #include <stddef.h>
0015 #include <string.h>
0016 #include <unistd.h>
0017 #include <assert.h>
0018 #include <errno.h>
0019 #include <fcntl.h>
0020 #include <net/if.h>
0021 #include <linux/bpf.h>
0022 #include <bpf/bpf.h>
0023 #include <bpf/libbpf.h>
0024
0025 #include "bpf_insn.h"
0026
0027 static int usage(const char *argv0)
0028 {
0029 printf("Usage: %s cg-path filter-path [filter-id]\n", argv0);
0030 return EXIT_FAILURE;
0031 }
0032
0033 int main(int argc, char **argv)
0034 {
0035 int cg_fd, err, ret = EXIT_FAILURE, filter_id = 0, prog_cnt = 0;
0036 const char *link_pin_path = "/sys/fs/bpf/test_cgrp2_sock2";
0037 struct bpf_link *link = NULL;
0038 struct bpf_program *progs[2];
0039 struct bpf_program *prog;
0040 struct bpf_object *obj;
0041
0042 if (argc < 3)
0043 return usage(argv[0]);
0044
0045 if (argc > 3)
0046 filter_id = atoi(argv[3]);
0047
0048 cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
0049 if (cg_fd < 0) {
0050 printf("Failed to open cgroup path: '%s'\n", strerror(errno));
0051 return ret;
0052 }
0053
0054 obj = bpf_object__open_file(argv[2], NULL);
0055 if (libbpf_get_error(obj)) {
0056 printf("ERROR: opening BPF object file failed\n");
0057 return ret;
0058 }
0059
0060 bpf_object__for_each_program(prog, obj) {
0061 progs[prog_cnt] = prog;
0062 prog_cnt++;
0063 }
0064
0065 if (filter_id >= prog_cnt) {
0066 printf("Invalid program id; program not found in file\n");
0067 goto cleanup;
0068 }
0069
0070
0071 if (bpf_object__load(obj)) {
0072 printf("ERROR: loading BPF object file failed\n");
0073 goto cleanup;
0074 }
0075
0076 link = bpf_program__attach_cgroup(progs[filter_id], cg_fd);
0077 if (libbpf_get_error(link)) {
0078 printf("ERROR: bpf_program__attach failed\n");
0079 link = NULL;
0080 goto cleanup;
0081 }
0082
0083 err = bpf_link__pin(link, link_pin_path);
0084 if (err < 0) {
0085 printf("ERROR: bpf_link__pin failed: %d\n", err);
0086 goto cleanup;
0087 }
0088
0089 ret = EXIT_SUCCESS;
0090
0091 cleanup:
0092 bpf_link__destroy(link);
0093 bpf_object__close(obj);
0094 return ret;
0095 }