0001
0002
0003 #include "vmlinux.h"
0004
0005 #include <bpf/bpf_helpers.h>
0006
0007 #define AF_INET6 10
0008
0009 struct {
0010 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
0011 __uint(map_flags, BPF_F_NO_PREALLOC);
0012 __type(key, int);
0013 __type(value, int);
0014 } sockops_netns_cookies SEC(".maps");
0015
0016 struct {
0017 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
0018 __uint(map_flags, BPF_F_NO_PREALLOC);
0019 __type(key, int);
0020 __type(value, int);
0021 } sk_msg_netns_cookies SEC(".maps");
0022
0023 struct {
0024 __uint(type, BPF_MAP_TYPE_SOCKMAP);
0025 __uint(max_entries, 2);
0026 __type(key, __u32);
0027 __type(value, __u64);
0028 } sock_map SEC(".maps");
0029
0030 SEC("sockops")
0031 int get_netns_cookie_sockops(struct bpf_sock_ops *ctx)
0032 {
0033 struct bpf_sock *sk = ctx->sk;
0034 int *cookie;
0035 __u32 key = 0;
0036
0037 if (ctx->family != AF_INET6)
0038 return 1;
0039
0040 if (!sk)
0041 return 1;
0042
0043 switch (ctx->op) {
0044 case BPF_SOCK_OPS_TCP_CONNECT_CB:
0045 cookie = bpf_sk_storage_get(&sockops_netns_cookies, sk, 0,
0046 BPF_SK_STORAGE_GET_F_CREATE);
0047 if (!cookie)
0048 return 1;
0049
0050 *cookie = bpf_get_netns_cookie(ctx);
0051 break;
0052 case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
0053 bpf_sock_map_update(ctx, &sock_map, &key, BPF_NOEXIST);
0054 break;
0055 default:
0056 break;
0057 }
0058
0059 return 1;
0060 }
0061
0062 SEC("sk_msg")
0063 int get_netns_cookie_sk_msg(struct sk_msg_md *msg)
0064 {
0065 struct bpf_sock *sk = msg->sk;
0066 int *cookie;
0067
0068 if (msg->family != AF_INET6)
0069 return 1;
0070
0071 if (!sk)
0072 return 1;
0073
0074 cookie = bpf_sk_storage_get(&sk_msg_netns_cookies, sk, 0,
0075 BPF_SK_STORAGE_GET_F_CREATE);
0076 if (!cookie)
0077 return 1;
0078
0079 *cookie = bpf_get_netns_cookie(msg);
0080
0081 return 1;
0082 }
0083
0084 char _license[] SEC("license") = "GPL";