summaryrefslogtreecommitdiffstats
path: root/tools/testing/selftests/bpf/progs/sockopt_multi.c
blob: 9d8c212dde9f5f8bf60af4fee88361ef413d9986 (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
// SPDX-License-Identifier: GPL-2.0
#include <netinet/in.h>
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

char _license[] SEC("license") = "GPL";
__u32 _version SEC("version") = 1;

SEC("cgroup/getsockopt/child")
int _getsockopt_child(struct bpf_sockopt *ctx)
{
	__u8 *optval_end = ctx->optval_end;
	__u8 *optval = ctx->optval;

	if (ctx->level != SOL_IP || ctx->optname != IP_TOS)
		return 1;

	if (optval + 1 > optval_end)
		return 0; /* EPERM, bounds check */

	if (optval[0] != 0x80)
		return 0; /* EPERM, unexpected optval from the kernel */

	ctx->retval = 0; /* Reset system call return value to zero */

	optval[0] = 0x90;
	ctx->optlen = 1;

	return 1;
}

SEC("cgroup/getsockopt/parent")
int _getsockopt_parent(struct bpf_sockopt *ctx)
{
	__u8 *optval_end = ctx->optval_end;
	__u8 *optval = ctx->optval;

	if (ctx->level != SOL_IP || ctx->optname != IP_TOS)
		return 1;

	if (optval + 1 > optval_end)
		return 0; /* EPERM, bounds check */

	if (optval[0] != 0x90)
		return 0; /* EPERM, unexpected optval from the kernel */

	ctx->retval = 0; /* Reset system call return value to zero */

	optval[0] = 0xA0;
	ctx->optlen = 1;

	return 1;
}

SEC("cgroup/setsockopt")
int _setsockopt(struct bpf_sockopt *ctx)
{
	__u8 *optval_end = ctx->optval_end;
	__u8 *optval = ctx->optval;

	if (ctx->level != SOL_IP || ctx->optname != IP_TOS)
		return 1;

	if (optval + 1 > optval_end)
		return 0; /* EPERM, bounds check */

	optval[0] += 0x10;
	ctx->optlen = 1;

	return 1;
}