diff mbox series

[conntrack-tools,2/2] conntrack: prefer kernel-provided event timestamp if it is available

Message ID 20250109131541.5856-2-fw@strlen.de
State Accepted, archived
Headers show
Series [libnetfilter_conntrack,1/2] src: add support for CTA_TIMESTAMP_EVENT | expand

Commit Message

Florian Westphal Jan. 9, 2025, 1:15 p.m. UTC
If kernel provided the event timestamp, then use it, else fall back
to gettimeofday.

This needs a recent kernel with
    netfilter: conntrack: add conntrack event timestamp

and net.netfilter.nf_conntrack_timestamp sysctl set to 1.

Signed-off-by: Florian Westphal <fw@strlen.de>
---
 src/conntrack.c | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)

Comments

Pablo Neira Ayuso Feb. 7, 2025, 11:59 a.m. UTC | #1
On Thu, Jan 09, 2025 at 02:15:37PM +0100, Florian Westphal wrote:
> If kernel provided the event timestamp, then use it, else fall back
> to gettimeofday.
> 
> This needs a recent kernel with
>     netfilter: conntrack: add conntrack event timestamp
> 
> and net.netfilter.nf_conntrack_timestamp sysctl set to 1.
> 
> Signed-off-by: Florian Westphal <fw@strlen.de>

Reviewed-by: Pablo Neira Ayuso <pablo@netfilter.org>
diff mbox series

Patch

diff --git a/src/conntrack.c b/src/conntrack.c
index 52ba4ac5e44f..22058736b374 100644
--- a/src/conntrack.c
+++ b/src/conntrack.c
@@ -1914,6 +1914,26 @@  static char *get_progname(uint32_t portid)
 	return NULL;
 }
 
+static void event_print_timestamp(const struct nf_conntrack *ct)
+{
+	struct timeval tv;
+
+	/* nfct_attr_is_set returns -1 if attr is unknown */
+	if (nfct_attr_is_set(ct, ATTR_TIMESTAMP_EVENT) > 0) {
+		uint64_t event_ts = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_EVENT);
+		static const uint64_t ns_per_s = 1000000000ul;
+		static const uint64_t ns_to_usec = 1000ul;
+
+		tv.tv_sec = event_ts / ns_per_s;
+
+		tv.tv_usec = (event_ts % ns_per_s) / ns_to_usec;
+	} else {
+		gettimeofday(&tv, NULL);
+	}
+
+	printf("[%-.8ld.%-.6ld]\t", tv.tv_sec, tv.tv_usec);
+}
+
 static int event_cb(const struct nlmsghdr *nlh, void *data)
 {
 	struct nfgenmsg *nfh = mnl_nlmsg_get_payload(nlh);
@@ -1969,9 +1989,7 @@  static int event_cb(const struct nlmsghdr *nlh, void *data)
 		op_flags = NFCT_OF_SHOW_LAYER3;
 	if (output_mask & _O_TMS) {
 		if (!(output_mask & _O_XML)) {
-			struct timeval tv;
-			gettimeofday(&tv, NULL);
-			printf("[%-.8ld.%-.6ld]\t", tv.tv_sec, tv.tv_usec);
+			event_print_timestamp(ct);
 		} else
 			op_flags |= NFCT_OF_TIME;
 	}