Split logging logic from XDP program into its own files.

This commit is contained in:
Christian Deacon
2025-02-26 16:31:45 -05:00
parent 353aedab42
commit d9998580f2
3 changed files with 68 additions and 27 deletions

View File

@@ -11,6 +11,7 @@
#include <common/all.h>
#include <xdp/utils/rl.h>
#include <xdp/utils/logging.h>
#include <xdp/utils/helpers.h>
#include <xdp/utils/maps.h>
@@ -538,33 +539,7 @@ int xdp_prog_main(struct xdp_md *ctx)
#ifdef ENABLE_FILTER_LOGGING
if (filter->log > 0)
{
filter_log_event_t* e = bpf_ringbuf_reserve(&filter_log_map, sizeof(*e), 0);
if (e)
{
e->ts = now;
e->filter_id = i;
if (iph)
{
e->src_ip = iph->saddr;
e->dst_ip = iph->daddr;
} else if (iph6)
{
memcpy(&e->src_ip6, iph6->saddr.in6_u.u6_addr32, 4);
memcpy(&e->dst_ip6, iph6->daddr.in6_u.u6_addr32, 4);
}
e->src_port = src_port;
e->dst_port = dst_port;
e->protocol = protocol;
e->pps = pps;
e->bps = bps;
bpf_ringbuf_submit(e, 0);
}
LogFilterMsg(iph, iph6, src_port, dst_port, protocol, now, pps, bps, i);
}
#endif

53
src/xdp/utils/logging.c Normal file
View File

@@ -0,0 +1,53 @@
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <xdp/utils/helpers.h>
#include <xdp/utils/maps.h>
/**
* Logs a message to the filter ringbuffer map.
*
* @param iph The IPv4 header.
* @param iph6 The IPv6 header.
* @param src_port The source port.
* @param dst_port The destination port.
* @param protocol The protocol.
* @param now The timestamp.
* @param pps The current PPS rate.
* @param bps The current BPS rate.
* @param filter_id The filter ID that matched.
*
* @return always 0
*/
static __always_inline int LogFilterMsg(struct iphdr* iph, struct ipv6hdr* iph6, u16 src_port, u16 dst_port, u8 protocol, u64 now, u64 pps, u64 bps, int filter_id)
{
filter_log_event_t* e = bpf_ringbuf_reserve(&filter_log_map, sizeof(*e), 0);
if (e)
{
e->ts = now;
e->filter_id = filter_id;
if (iph)
{
e->src_ip = iph->saddr;
e->dst_ip = iph->daddr;
} else if (iph6)
{
memcpy(&e->src_ip6, iph6->saddr.in6_u.u6_addr32, 4);
memcpy(&e->dst_ip6, iph6->daddr.in6_u.u6_addr32, 4);
}
e->src_port = src_port;
e->dst_port = dst_port;
e->protocol = protocol;
e->pps = pps;
e->bps = bps;
bpf_ringbuf_submit(e, 0);
}
return 0;
}

13
src/xdp/utils/logging.h Normal file
View File

@@ -0,0 +1,13 @@
#include <common/all.h>
#include <linux/bpf.h>
#include <xdp/xdp_helpers.h>
#include <xdp/prog_dispatcher.h>
static __always_inline int LogFilterMsg(struct iphdr* iph, struct ipv6hdr* iph6, u16 src_port, u16 dst_port, u8 protocol, u64 now, u64 pps, u64 bps, int filter_id);
// The source file is included directly below instead of compiled and linked as an object because when linking, there is no guarantee the compiler will inline the function (which is crucial for performance).
// I'd prefer not to include the function logic inside of the header file.
// More Info: https://stackoverflow.com/questions/24289599/always-inline-does-not-work-when-function-is-implemented-in-different-file
#include "logging.c"