Skip to content

Commit bcc0098

Browse files
TropicaoAlexei Starovoitov
authored andcommitted
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>
1 parent a2f482c commit bcc0098

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
@@ -14,6 +14,7 @@ typedef __u16 __sum16;
1414
#include <linux/sockios.h>
1515
#include <linux/err.h>
1616
#include <netinet/tcp.h>
17+
#include <netinet/udp.h>
1718
#include <bpf/bpf_endian.h>
1819
#include <net/if.h>
1920

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

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

198240
#ifdef TRAFFIC_MONITOR

0 commit comments

Comments
 (0)