Greg Kroah-Hartman | b244131 | 2017-11-01 15:07:57 +0100 | [diff] [blame] | 1 | // SPDX-License-Identifier: GPL-2.0 |
David Ahern | 554ae6e | 2016-12-01 08:48:08 -0800 | [diff] [blame] | 2 | /* eBPF example program: |
| 3 | * |
| 4 | * - Loads eBPF program |
| 5 | * |
| 6 | * The eBPF program loads a filter from file and attaches the |
| 7 | * program to a cgroup using BPF_PROG_ATTACH |
| 8 | */ |
| 9 | |
| 10 | #define _GNU_SOURCE |
| 11 | |
| 12 | #include <stdio.h> |
| 13 | #include <stdlib.h> |
| 14 | #include <stddef.h> |
| 15 | #include <string.h> |
| 16 | #include <unistd.h> |
| 17 | #include <assert.h> |
| 18 | #include <errno.h> |
| 19 | #include <fcntl.h> |
| 20 | #include <net/if.h> |
| 21 | #include <linux/bpf.h> |
Jakub Kicinski | 8d93045 | 2018-05-14 22:35:03 -0700 | [diff] [blame] | 22 | #include <bpf/bpf.h> |
David Ahern | 554ae6e | 2016-12-01 08:48:08 -0800 | [diff] [blame] | 23 | |
Jakub Kicinski | 8d93045 | 2018-05-14 22:35:03 -0700 | [diff] [blame] | 24 | #include "bpf_insn.h" |
David Ahern | 554ae6e | 2016-12-01 08:48:08 -0800 | [diff] [blame] | 25 | #include "bpf_load.h" |
| 26 | |
| 27 | static int usage(const char *argv0) |
| 28 | { |
| 29 | printf("Usage: %s cg-path filter-path [filter-id]\n", argv0); |
| 30 | return EXIT_FAILURE; |
| 31 | } |
| 32 | |
| 33 | int main(int argc, char **argv) |
| 34 | { |
| 35 | int cg_fd, ret, filter_id = 0; |
| 36 | |
| 37 | if (argc < 3) |
| 38 | return usage(argv[0]); |
| 39 | |
| 40 | cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY); |
| 41 | if (cg_fd < 0) { |
| 42 | printf("Failed to open cgroup path: '%s'\n", strerror(errno)); |
| 43 | return EXIT_FAILURE; |
| 44 | } |
| 45 | |
| 46 | if (load_bpf_file(argv[2])) |
| 47 | return EXIT_FAILURE; |
| 48 | |
| 49 | printf("Output from kernel verifier:\n%s\n-------\n", bpf_log_buf); |
| 50 | |
| 51 | if (argc > 3) |
| 52 | filter_id = atoi(argv[3]); |
| 53 | |
Dan Carpenter | ee58301 | 2018-07-13 18:05:37 +0300 | [diff] [blame] | 54 | if (filter_id >= prog_cnt) { |
David Ahern | 554ae6e | 2016-12-01 08:48:08 -0800 | [diff] [blame] | 55 | printf("Invalid program id; program not found in file\n"); |
| 56 | return EXIT_FAILURE; |
| 57 | } |
| 58 | |
| 59 | ret = bpf_prog_attach(prog_fd[filter_id], cg_fd, |
Alexei Starovoitov | 7f67763 | 2017-02-10 20:28:24 -0800 | [diff] [blame] | 60 | BPF_CGROUP_INET_SOCK_CREATE, 0); |
David Ahern | 554ae6e | 2016-12-01 08:48:08 -0800 | [diff] [blame] | 61 | if (ret < 0) { |
| 62 | printf("Failed to attach prog to cgroup: '%s'\n", |
| 63 | strerror(errno)); |
| 64 | return EXIT_FAILURE; |
| 65 | } |
| 66 | |
| 67 | return EXIT_SUCCESS; |
| 68 | } |