Skip to content

Commit 0707a77

Browse files
selftests/bpf: add network helpers to generate udp checksums
JIRA: https://issues.redhat.com/browse/RHEL-78201 commit bcc0098 Author: Alexis Lothoré (eBPF Foundation) <alexis.lothore@bootlin.com> Date: Wed Nov 20 08:43:22 2024 +0100 selftests/bpf: add network helpers to generate udp checksums network_helpers.c provides some helpers to generate ip checksums or ip pseudo-header checksums, but not for upper layers (eg: udp checksums) Add helpers for udp checksum to allow manually building udp packets. Signed-off-by: Alexis Lothoré (eBPF Foundation) <alexis.lothore@bootlin.com> Acked-by: Stanislav Fomichev <sdf@fomichev.me> Link: https://lore.kernel.org/r/20241120-flow_dissector-v3-12-45b46494f937@bootlin.com Signed-off-by: Alexei Starovoitov <ast@kernel.org> Signed-off-by: Jerome Marchand <jmarchan@redhat.com>
1 parent ce012bf commit 0707a77

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

tools/testing/selftests/bpf/network_helpers.h

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ typedef __u16 __sum16;
1313
#include <linux/sockios.h>
1414
#include <linux/err.h>
1515
#include <netinet/tcp.h>
16+
#include <netinet/udp.h>
1617
#include <bpf/bpf_endian.h>
1718
#include <net/if.h>
1819

@@ -192,6 +193,47 @@ static inline __sum16 csum_ipv6_magic(const struct in6_addr *saddr,
192193
return csum_fold((__u32)s);
193194
}
194195

196+
/**
197+
* build_udp_v4_csum - compute UDP checksum for UDP over IPv4
198+
*
199+
* Compute the checksum to embed in UDP header, composed of the sum of IP
200+
* pseudo-header checksum, UDP header checksum and UDP data checksum
201+
* @iph IP header
202+
* @udph UDP header, which must be immediately followed by UDP data
203+
*
204+
* Returns the total checksum
205+
*/
206+
207+
static inline __sum16 build_udp_v4_csum(const struct iphdr *iph,
208+
const struct udphdr *udph)
209+
{
210+
unsigned long sum;
211+
212+
sum = csum_partial(udph, ntohs(udph->len), 0);
213+
return csum_tcpudp_magic(iph->saddr, iph->daddr, ntohs(udph->len),
214+
IPPROTO_UDP, sum);
215+
}
216+
217+
/**
218+
* build_udp_v6_csum - compute UDP checksum for UDP over IPv6
219+
*
220+
* Compute the checksum to embed in UDP header, composed of the sum of IPv6
221+
* pseudo-header checksum, UDP header checksum and UDP data checksum
222+
* @ip6h IPv6 header
223+
* @udph UDP header, which must be immediately followed by UDP data
224+
*
225+
* Returns the total checksum
226+
*/
227+
static inline __sum16 build_udp_v6_csum(const struct ipv6hdr *ip6h,
228+
const struct udphdr *udph)
229+
{
230+
unsigned long sum;
231+
232+
sum = csum_partial(udph, ntohs(udph->len), 0);
233+
return csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr, ntohs(udph->len),
234+
IPPROTO_UDP, sum);
235+
}
236+
195237
struct tmonitor_ctx;
196238

197239
#ifdef TRAFFIC_MONITOR

0 commit comments

Comments
 (0)