aboutsummaryrefslogtreecommitdiffstats
path: root/src/bpfswitch/usrc/xdp_dummy_user.c
blob: 7741f3305e2b3585796175418ac30efc6ece6d75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// SPDX-License-Identifier: GPL-2.0
#include <linux/bpf.h>
#include <linux/if_link.h>
#include <linux/limits.h>
#include <net/if.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <libgen.h>

#include <bpf/bpf.h>
#include <bpf/libbpf.h>

#include "libbpf_helpers.h"

static void usage(const char *prog)
{
	fprintf(stderr,
		"usage: %s [OPTS] interface-list\n"
		"\nOPTS:\n"
		"    -d            detach program\n"
		"    -f bpf-file   bpf filename to load\n"
		"    -g            skb mode\n"
		, prog);
}

int main(int argc, char **argv)
{
	int (*attach_fn)(int idx, int prog_fd, const char *dev) = attach_to_dev;
	int (*detach_fn)(int idx, const char *dev) = detach_from_dev;
	struct bpf_prog_load_attr prog_load_attr = { };
	const char *objfile = "xdp_dummy_kern.o";
	const char *pname = "xdp_dummy";
	bool filename_set = false;
	struct bpf_program *prog;
	struct bpf_object *obj;
	int opt, i, prog_fd;
	bool attach = true;
	int ret = 0;

	while ((opt = getopt(argc, argv, ":df:g")) != -1) {
		switch (opt) {
		case 'f':
			objfile = optarg;
			filename_set = true;
			break;
		case 'd':
			attach = false;
			break;
		case 'g':
			attach_fn = attach_to_dev_generic;
			detach_fn = detach_from_dev_generic;
			break;
		default:
			usage(basename(argv[0]));
			return 1;
		}
	}

	if (optind == argc) {
		usage(basename(argv[0]));
		return 1;
	}

	if (!attach) {
		for (i = optind; i < argc; ++i) {
			int idx, err;

			idx = if_nametoindex(argv[i]);
			if (!idx)
				idx = strtoul(argv[i], NULL, 0);

			if (!idx) {
				fprintf(stderr, "Invalid device argument\n");
				return 1;
			}
			err = detach_fn(idx, argv[i]);
			if (err)
				ret = err;
		}
		return ret;
	}

	if (load_obj_file(&prog_load_attr, &obj, objfile, filename_set))
                return 1;

	prog = bpf_object__find_program_by_title(obj, pname);
	prog_fd = bpf_program__fd(prog);
	if (prog_fd < 0) {
		printf("program not found: %s\n", strerror(prog_fd));
		return 1;
	}

	for (i = optind; i < argc; ++i) {
		int idx, err;

		idx = if_nametoindex(argv[i]);
		if (!idx)
			idx = strtoul(argv[i], NULL, 0);

		if (!idx) {
			fprintf(stderr, "Invalid device argument\n");
			return 1;
		}

		err = attach_fn(idx, prog_fd, argv[i]);
		if (err)
			ret = err;
	}

	return ret;
}