1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 Facebook
3 // Copyright (c) 2019 Cloudflare
10 #include <netinet/in.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
15 #include <bpf/libbpf.h>
17 #include "bpf_rlimit.h"
18 #include "cgroup_helpers.h"
20 static int start_server(const struct sockaddr
*addr
, socklen_t len
)
24 fd
= socket(addr
->sa_family
, SOCK_STREAM
, 0);
26 log_err("Failed to create server socket");
30 if (bind(fd
, addr
, len
) == -1) {
31 log_err("Failed to bind server socket");
35 if (listen(fd
, 128) == -1) {
36 log_err("Failed to listen on server socket");
49 static int connect_to_server(int server_fd
)
51 struct sockaddr_storage addr
;
52 socklen_t len
= sizeof(addr
);
55 if (getsockname(server_fd
, (struct sockaddr
*)&addr
, &len
)) {
56 log_err("Failed to get server addr");
60 fd
= socket(addr
.ss_family
, SOCK_STREAM
, 0);
62 log_err("Failed to create client socket");
66 if (connect(fd
, (const struct sockaddr
*)&addr
, len
) == -1) {
67 log_err("Fail to connect to server");
80 static 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 static int run_test(int server_fd
, int results_fd
)
118 int client
= -1, srv_client
= -1;
123 if (bpf_map_update_elem(results_fd
, &key
, &value
, 0) < 0) {
124 log_err("Can't clear results");
128 client
= connect_to_server(server_fd
);
132 srv_client
= accept(server_fd
, NULL
, 0);
133 if (srv_client
== -1) {
134 log_err("Can't accept connection");
138 if (bpf_map_lookup_elem(results_fd
, &key
, &value
) < 0) {
139 log_err("Can't lookup result");
144 log_err("Didn't match syncookie: %llu", value
);
158 int main(int argc
, char **argv
)
160 struct sockaddr_in addr4
;
161 struct sockaddr_in6 addr6
;
168 fprintf(stderr
, "Usage: %s prog_id\n", argv
[0]);
172 results
= get_map_fd_by_prog_id(atoi(argv
[1]));
174 log_err("Can't get map");
178 memset(&addr4
, 0, sizeof(addr4
));
179 addr4
.sin_family
= AF_INET
;
180 addr4
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
183 memset(&addr6
, 0, sizeof(addr6
));
184 addr6
.sin6_family
= AF_INET6
;
185 addr6
.sin6_addr
= in6addr_loopback
;
188 server
= start_server((const struct sockaddr
*)&addr4
, sizeof(addr4
));
192 server_v6
= start_server((const struct sockaddr
*)&addr6
,
197 if (run_test(server
, results
))
200 if (run_test(server_v6
, results
))