1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 Facebook
10 #include <netinet/in.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
16 #include <bpf/libbpf.h>
18 #include "bpf_rlimit.h"
19 #include "cgroup_helpers.h"
21 #define CGROUP_PATH "/skb_cgroup_test"
22 #define NUM_CGROUP_LEVELS 4
24 /* RFC 4291, Section 2.7.1 */
25 #define LINKLOCAL_MULTICAST "ff02::1"
27 static int mk_dst_addr(const char *ip
, const char *iface
,
28 struct sockaddr_in6
*dst
)
30 memset(dst
, 0, sizeof(*dst
));
32 dst
->sin6_family
= AF_INET6
;
33 dst
->sin6_port
= htons(1025);
35 if (inet_pton(AF_INET6
, ip
, &dst
->sin6_addr
) != 1) {
36 log_err("Invalid IPv6: %s", ip
);
40 dst
->sin6_scope_id
= if_nametoindex(iface
);
41 if (!dst
->sin6_scope_id
) {
42 log_err("Failed to get index of iface: %s", iface
);
49 static int send_packet(const char *iface
)
51 struct sockaddr_in6 dst
;
56 if (mk_dst_addr(LINKLOCAL_MULTICAST
, iface
, &dst
))
59 fd
= socket(AF_INET6
, SOCK_DGRAM
, 0);
61 log_err("Failed to create UDP socket");
65 if (sendto(fd
, &msg
, sizeof(msg
), 0, (const struct sockaddr
*)&dst
,
67 log_err("Failed to send datagram");
80 int get_map_fd_by_prog_id(int prog_id
)
82 struct bpf_prog_info info
= {};
83 __u32 info_len
= sizeof(info
);
88 prog_fd
= bpf_prog_get_fd_by_id(prog_id
);
90 log_err("Failed to get fd by prog id %d", prog_id
);
95 info
.map_ids
= (__u64
) (unsigned long) map_ids
;
97 if (bpf_obj_get_info_by_fd(prog_fd
, &info
, &info_len
)) {
98 log_err("Failed to get info by prog fd %d", prog_fd
);
102 if (!info
.nr_map_ids
) {
103 log_err("No maps found for prog fd %d", prog_fd
);
107 map_fd
= bpf_map_get_fd_by_id(map_ids
[0]);
109 log_err("Failed to get fd by map id %d", map_ids
[0]);
116 int check_ancestor_cgroup_ids(int prog_id
)
118 __u64 actual_ids
[NUM_CGROUP_LEVELS
], expected_ids
[NUM_CGROUP_LEVELS
];
123 expected_ids
[0] = 0x100000001; /* root cgroup */
124 expected_ids
[1] = get_cgroup_id("");
125 expected_ids
[2] = get_cgroup_id(CGROUP_PATH
);
126 expected_ids
[3] = 0; /* non-existent cgroup */
128 map_fd
= get_map_fd_by_prog_id(prog_id
);
132 for (level
= 0; level
< NUM_CGROUP_LEVELS
; ++level
) {
133 if (bpf_map_lookup_elem(map_fd
, &level
, &actual_ids
[level
])) {
134 log_err("Failed to lookup key %d", level
);
137 if (actual_ids
[level
] != expected_ids
[level
]) {
138 log_err("%llx (actual) != %llx (expected), level: %u\n",
139 actual_ids
[level
], expected_ids
[level
], level
);
153 int main(int argc
, char **argv
)
159 fprintf(stderr
, "Usage: %s iface prog_id\n", argv
[0]);
163 if (setup_cgroup_environment())
166 cgfd
= create_and_get_cgroup(CGROUP_PATH
);
170 if (join_cgroup(CGROUP_PATH
))
173 if (send_packet(argv
[1]))
176 if (check_ancestor_cgroup_ids(atoi(argv
[2])))
184 cleanup_cgroup_environment();
185 printf("[%s]\n", err
? "FAIL" : "PASS");