blob: 43b4bde5d05c279e424a39ddbad4d523992aee9d [file] [log] [blame]
David Ahernad2805d2016-12-01 08:48:05 -08001/* eBPF example program:
2 *
3 * - Loads eBPF program
4 *
5 * The eBPF program sets the sk_bound_dev_if index in new AF_INET{6}
6 * sockets opened by processes in the cgroup.
7 *
8 * - Attaches the new program to a cgroup using BPF_PROG_ATTACH
9 */
10
11#define _GNU_SOURCE
12
13#include <stdio.h>
14#include <stdlib.h>
15#include <stddef.h>
16#include <string.h>
17#include <unistd.h>
18#include <assert.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <net/if.h>
22#include <linux/bpf.h>
23
24#include "libbpf.h"
25
Joe Stringerd40fc182016-12-14 14:43:38 -080026char bpf_log_buf[BPF_LOG_BUF_SIZE];
27
David Ahernad2805d2016-12-01 08:48:05 -080028static int prog_load(int idx)
29{
30 struct bpf_insn prog[] = {
31 BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
32 BPF_MOV64_IMM(BPF_REG_3, idx),
33 BPF_MOV64_IMM(BPF_REG_2, offsetof(struct bpf_sock, bound_dev_if)),
34 BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, offsetof(struct bpf_sock, bound_dev_if)),
35 BPF_MOV64_IMM(BPF_REG_0, 1), /* r0 = verdict */
36 BPF_EXIT_INSN(),
37 };
38
Joe Stringerd40fc182016-12-14 14:43:38 -080039 return bpf_load_program(BPF_PROG_TYPE_CGROUP_SOCK, prog, sizeof(prog),
40 "GPL", 0, bpf_log_buf, BPF_LOG_BUF_SIZE);
David Ahernad2805d2016-12-01 08:48:05 -080041}
42
43static int usage(const char *argv0)
44{
45 printf("Usage: %s cg-path device-index\n", argv0);
46 return EXIT_FAILURE;
47}
48
49int main(int argc, char **argv)
50{
51 int cg_fd, prog_fd, ret;
52 unsigned int idx;
53
54 if (argc < 2)
55 return usage(argv[0]);
56
57 idx = if_nametoindex(argv[2]);
58 if (!idx) {
59 printf("Invalid device name\n");
60 return EXIT_FAILURE;
61 }
62
63 cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
64 if (cg_fd < 0) {
65 printf("Failed to open cgroup path: '%s'\n", strerror(errno));
66 return EXIT_FAILURE;
67 }
68
69 prog_fd = prog_load(idx);
70 printf("Output from kernel verifier:\n%s\n-------\n", bpf_log_buf);
71
72 if (prog_fd < 0) {
73 printf("Failed to load prog: '%s'\n", strerror(errno));
74 return EXIT_FAILURE;
75 }
76
77 ret = bpf_prog_attach(prog_fd, cg_fd, BPF_CGROUP_INET_SOCK_CREATE);
78 if (ret < 0) {
79 printf("Failed to attach prog to cgroup: '%s'\n",
80 strerror(errno));
81 return EXIT_FAILURE;
82 }
83
84 return EXIT_SUCCESS;
85}