]>
git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blob - tools/testing/selftests/bpf/network_helpers.c
1 // SPDX-License-Identifier: GPL-2.0-only
10 #include <sys/epoll.h>
12 #include <linux/err.h>
14 #include <linux/in6.h>
17 #include "network_helpers.h"
19 #define clean_errno() (errno == 0 ? "None" : strerror(errno))
20 #define log_err(MSG, ...) fprintf(stderr, "(%s:%d: errno: %s) " MSG "\n", \
21 __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
23 struct ipv4_packet pkt_v4
= {
24 .eth
.h_proto
= __bpf_constant_htons(ETH_P_IP
),
26 .iph
.protocol
= IPPROTO_TCP
,
27 .iph
.tot_len
= __bpf_constant_htons(MAGIC_BYTES
),
32 struct ipv6_packet pkt_v6
= {
33 .eth
.h_proto
= __bpf_constant_htons(ETH_P_IPV6
),
34 .iph
.nexthdr
= IPPROTO_TCP
,
35 .iph
.payload_len
= __bpf_constant_htons(MAGIC_BYTES
),
40 int start_server_with_port(int family
, int type
, __u16 port
)
42 struct sockaddr_storage addr
= {};
46 if (family
== AF_INET
) {
47 struct sockaddr_in
*sin
= (void *)&addr
;
49 sin
->sin_family
= AF_INET
;
50 sin
->sin_port
= htons(port
);
53 struct sockaddr_in6
*sin6
= (void *)&addr
;
55 sin6
->sin6_family
= AF_INET6
;
56 sin6
->sin6_port
= htons(port
);
60 fd
= socket(family
, type
| SOCK_NONBLOCK
, 0);
62 log_err("Failed to create server socket");
66 if (bind(fd
, (const struct sockaddr
*)&addr
, len
) < 0) {
67 log_err("Failed to bind socket");
72 if (type
== SOCK_STREAM
) {
73 if (listen(fd
, 1) < 0) {
74 log_err("Failed to listed on socket");
83 int start_server(int family
, int type
)
85 return start_server_with_port(family
, type
, 0);
88 static const struct timeval timeo_sec
= { .tv_sec
= 3 };
89 static const size_t timeo_optlen
= sizeof(timeo_sec
);
91 int connect_to_fd(int family
, int type
, int server_fd
)
95 fd
= socket(family
, type
, 0);
97 log_err("Failed to create client socket");
101 if (connect_fd_to_fd(fd
, server_fd
) < 0 && errno
!= EINPROGRESS
) {
111 int connect_fd_to_fd(int client_fd
, int server_fd
)
113 struct sockaddr_storage addr
;
114 socklen_t len
= sizeof(addr
);
117 if (setsockopt(client_fd
, SOL_SOCKET
, SO_RCVTIMEO
, &timeo_sec
,
119 log_err("Failed to set SO_RCVTIMEO");
123 if (getsockname(server_fd
, (struct sockaddr
*)&addr
, &len
)) {
124 log_err("Failed to get server addr");
128 if (connect(client_fd
, (const struct sockaddr
*)&addr
, len
) < 0) {
129 if (errno
!= EINPROGRESS
) {
131 log_err("Failed to connect to server");
140 int connect_wait(int fd
)
142 struct epoll_event ev
= {}, events
[2];
143 int timeout_ms
= 1000;
146 efd
= epoll_create1(EPOLL_CLOEXEC
);
148 log_err("Failed to open epoll fd");
152 ev
.events
= EPOLLRDHUP
| EPOLLOUT
;
155 if (epoll_ctl(efd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0) {
156 log_err("Failed to register fd=%d on epoll fd=%d", fd
, efd
);
161 nfd
= epoll_wait(efd
, events
, ARRAY_SIZE(events
), timeout_ms
);
163 log_err("Failed to wait for I/O event on epoll fd=%d", efd
);