1// SPDX-License-Identifier: GPL-2.0
2
3#include "vmlinux.h"
4
5#include <bpf/bpf_helpers.h>
6
7#define AF_INET6 10
8
9struct {
10	__uint(type, BPF_MAP_TYPE_SK_STORAGE);
11	__uint(map_flags, BPF_F_NO_PREALLOC);
12	__type(key, int);
13	__type(value, int);
14} sockops_netns_cookies SEC(".maps");
15
16struct {
17	__uint(type, BPF_MAP_TYPE_SK_STORAGE);
18	__uint(map_flags, BPF_F_NO_PREALLOC);
19	__type(key, int);
20	__type(value, int);
21} sk_msg_netns_cookies SEC(".maps");
22
23struct {
24	__uint(type, BPF_MAP_TYPE_SOCKMAP);
25	__uint(max_entries, 2);
26	__type(key, __u32);
27	__type(value, __u64);
28} sock_map SEC(".maps");
29
30SEC("sockops")
31int get_netns_cookie_sockops(struct bpf_sock_ops *ctx)
32{
33	struct bpf_sock *sk = ctx->sk;
34	int *cookie;
35	__u32 key = 0;
36
37	if (ctx->family != AF_INET6)
38		return 1;
39
40	if (!sk)
41		return 1;
42
43	switch (ctx->op) {
44	case BPF_SOCK_OPS_TCP_CONNECT_CB:
45		cookie = bpf_sk_storage_get(&sockops_netns_cookies, sk, 0,
46					    BPF_SK_STORAGE_GET_F_CREATE);
47		if (!cookie)
48			return 1;
49
50		*cookie = bpf_get_netns_cookie(ctx);
51		break;
52	case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
53		bpf_sock_map_update(ctx, &sock_map, &key, BPF_NOEXIST);
54		break;
55	default:
56		break;
57	}
58
59	return 1;
60}
61
62SEC("sk_msg")
63int get_netns_cookie_sk_msg(struct sk_msg_md *msg)
64{
65	struct bpf_sock *sk = msg->sk;
66	int *cookie;
67
68	if (msg->family != AF_INET6)
69		return 1;
70
71	if (!sk)
72		return 1;
73
74	cookie = bpf_sk_storage_get(&sk_msg_netns_cookies, sk, 0,
75				    BPF_SK_STORAGE_GET_F_CREATE);
76	if (!cookie)
77		return 1;
78
79	*cookie = bpf_get_netns_cookie(msg);
80
81	return 1;
82}
83
84char _license[] SEC("license") = "GPL";
85