Commit 374e74de authored by Xu Liu's avatar Xu Liu Committed by Daniel Borkmann

selftests/bpf: Test for get_netns_cookie

Add test to use get_netns_cookie() from BPF_PROG_TYPE_SOCK_OPS.
Signed-off-by: default avatarXu Liu <liuxu623@gmail.com>
Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
Acked-by: default avatarSong Liu <songliubraving@fb.com>
Link: https://lore.kernel.org/bpf/20210818105820.91894-3-liuxu623@gmail.com
parent 6cf1770d
// SPDX-License-Identifier: GPL-2.0
#include <test_progs.h>
#include "netns_cookie_prog.skel.h"
#include "network_helpers.h"
#ifndef SO_NETNS_COOKIE
#define SO_NETNS_COOKIE 71
#endif
static int duration;
void test_netns_cookie(void)
{
int server_fd = 0, client_fd = 0, cgroup_fd = 0, err = 0, val = 0;
struct netns_cookie_prog *skel;
uint64_t cookie_expected_value;
socklen_t vallen = sizeof(cookie_expected_value);
skel = netns_cookie_prog__open_and_load();
if (!ASSERT_OK_PTR(skel, "skel_open"))
return;
cgroup_fd = test__join_cgroup("/netns_cookie");
if (CHECK(cgroup_fd < 0, "join_cgroup", "cgroup creation failed\n"))
goto out;
skel->links.get_netns_cookie_sockops = bpf_program__attach_cgroup(
skel->progs.get_netns_cookie_sockops, cgroup_fd);
if (!ASSERT_OK_PTR(skel->links.get_netns_cookie_sockops, "prog_attach"))
goto close_cgroup_fd;
server_fd = start_server(AF_INET6, SOCK_STREAM, "::1", 0, 0);
if (CHECK(server_fd < 0, "start_server", "errno %d\n", errno))
goto close_cgroup_fd;
client_fd = connect_to_fd(server_fd, 0);
if (CHECK(client_fd < 0, "connect_to_fd", "errno %d\n", errno))
goto close_server_fd;
err = bpf_map_lookup_elem(bpf_map__fd(skel->maps.netns_cookies),
&client_fd, &val);
if (!ASSERT_OK(err, "map_lookup(socket_cookies)"))
goto close_client_fd;
err = getsockopt(client_fd, SOL_SOCKET, SO_NETNS_COOKIE,
&cookie_expected_value, &vallen);
if (!ASSERT_OK(err, "getsockopt)"))
goto close_client_fd;
ASSERT_EQ(val, cookie_expected_value, "cookie_value");
close_client_fd:
close(client_fd);
close_server_fd:
close(server_fd);
close_cgroup_fd:
close(cgroup_fd);
out:
netns_cookie_prog__destroy(skel);
}
// SPDX-License-Identifier: GPL-2.0
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#define AF_INET6 10
struct {
__uint(type, BPF_MAP_TYPE_SK_STORAGE);
__uint(map_flags, BPF_F_NO_PREALLOC);
__type(key, int);
__type(value, int);
} netns_cookies SEC(".maps");
SEC("sockops")
int get_netns_cookie_sockops(struct bpf_sock_ops *ctx)
{
struct bpf_sock *sk = ctx->sk;
int *cookie;
if (ctx->family != AF_INET6)
return 1;
if (ctx->op != BPF_SOCK_OPS_TCP_CONNECT_CB)
return 1;
if (!sk)
return 1;
cookie = bpf_sk_storage_get(&netns_cookies, sk, 0,
BPF_SK_STORAGE_GET_F_CREATE);
if (!cookie)
return 1;
*cookie = bpf_get_netns_cookie(ctx);
return 1;
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment