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

char _license[] SEC("license") = "GPL";

__s32 page_size = 0;

SEC("cgroup/getsockopt")
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)
		goto out;

	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;

out:
	/* optval larger than PAGE_SIZE use kernel's buffer. */
	if (ctx->optlen > page_size)
		ctx->optlen = 0;
	return 1;
}

SEC("cgroup/getsockopt")
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)
		goto out;

	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;

out:
	/* optval larger than PAGE_SIZE use kernel's buffer. */
	if (ctx->optlen > page_size)
		ctx->optlen = 0;
	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)
		goto out;

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

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

	return 1;

out:
	/* optval larger than PAGE_SIZE use kernel's buffer. */
	if (ctx->optlen > page_size)
		ctx->optlen = 0;
	return 1;
}