Skip to contentSkip to conversation

meta: Introduce new conditions 'time', 'day' and 'hour'

PATCH Superseded Ander Juaristi 2 participants 8 messages Jul 7, 2019 – Jul 18, 2019 netfilter

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

PATCH v5 1/3 meta: Introduce new conditions 'time', 'day' and 'hour'

These keywords introduce new checks for a timestamp, an absolute date (which is converted to a timestamp), an hour in the day (which is converted to the number of seconds since midnight) and a day of week.

When converting an ISO date (eg. 2019-06-06 17:00) to a timestamp, we need to substract it the GMT difference in seconds, that is, the value of the 'tm_gmtoff' field in the tm structure. This is because the kernel doesn't know about time zones. And hence the kernel manages different timestamps than those that are advertised in userspace when running, for instance, date +%s.

The same conversion needs to be done when converting hours (e.g 17:00) to seconds since midnight as well.

The result needs to be computed modulo 86400 in case GMT offset (difference in seconds from UTC) is negative.

We also introduce a new command line option (-t, --seconds) to show the actual timestamps when printing the values, rather than the ISO dates, or the hour.

Some usage examples:

	time < "2019-06-06 17:00" drop;
	time < "2019-06-06 17:20:20" drop;
	time < 12341234 drop;
	day "Sat" drop;
	day 6 drop;
	hour >= 17:00 drop;
	hour >= "17:00:01" drop;
	hour >= 63000 drop;

We need to convert an ISO date to a timestamp
without taking into account the time zone offset, since comparison will be done in kernel space and there is no time zone information there.

Overwriting TZ is portable, but will cause problems when parsing a ruleset that has 'time' and 'hour' rules. Parsing an 'hour' type must not do time zone conversion, but that will be automatically done if TZ has been overwritten to UTC.

Hence, we use timegm() to parse the 'time' type, even though it's not portable. Overwriting TZ seems to be a much worse solution.

Finally, be aware that timestamps are converted to nanoseconds when transferring to the kernel (as comparison is done with nanosecond precision), and back to seconds when retrieving them for printing.

---
 include/datatype.h                  |   3 +
 include/linux/netfilter/nf_tables.h |   6 +
 include/meta.h                      |   3 +
 include/nftables.h                  |   5 +
 include/nftables/libnftables.h      |   4 +-
 src/datatype.c                      |   3 +
 src/main.c                          |  11 +-
 src/meta.c                          | 320 ++++++++++++++++++++++++++++
 src/parser_bison.y                  |   4 +
 src/scanner.l                       |   4 +-
 tests/py/ip/meta.t.payload          |  84 ++++++++
 11 files changed, 444 insertions(+), 3 deletions(-)
include/datatype.h +3 -0
index 63617eb..1f46eb0 100644
@@ -90,6 +90,9 @@ enum datatypes {
 	TYPE_CT_EVENTBIT,
 	TYPE_IFNAME,
 	TYPE_IGMP_TYPE,
+	TYPE_TIME_DATE,
+	TYPE_TIME_HOUR,
+	TYPE_TIME_DAY,
 	__TYPE_MAX
 };
 #define TYPE_MAX		(__TYPE_MAX - 1)
include/linux/netfilter/nf_tables.h +6 -0
index 7bdb234..ce621ed 100644
@@ -793,6 +793,9 @@ enum nft_exthdr_attributes {
  * @NFT_META_SECPATH: boolean, secpath_exists (!!skb->sp)
  * @NFT_META_IIFKIND: packet input interface kind name (dev->rtnl_link_ops->kind)
  * @NFT_META_OIFKIND: packet output interface kind name (dev->rtnl_link_ops->kind)
+ * @NFT_META_TIME: a UNIX timestamp
+ * @NFT_META_TIME_DAY: day of week
+ * @NFT_META_TIME_HOUR: hour of day
  */
 enum nft_meta_keys {
 	NFT_META_LEN,
@@ -823,6 +826,9 @@ enum nft_meta_keys {
 	NFT_META_SECPATH,
 	NFT_META_IIFKIND,
 	NFT_META_OIFKIND,
+	NFT_META_TIME,
+	NFT_META_TIME_DAY,
+	NFT_META_TIME_HOUR,
 };
 
 /**
include/meta.h +3 -0
index a49b4ff..a62a130 100644
@@ -41,6 +41,9 @@ extern const struct datatype uid_type;
 extern const struct datatype devgroup_type;
 extern const struct datatype pkttype_type;
 extern const struct datatype ifname_type;
+extern const struct datatype date_type;
+extern const struct datatype hour_type;
+extern const struct datatype day_type;
 
 extern struct symbol_table *devgroup_tbl;
 
include/nftables.h +5 -0
index ed446e2..b807004 100644
@@ -62,6 +62,11 @@ static inline bool nft_output_guid(const struct output_ctx *octx)
 	return octx->flags & NFT_CTX_OUTPUT_GUID;
 }
 
+static inline bool nft_output_seconds(const struct output_ctx *octx)
+{
+	return octx->flags & NFT_CTX_OUTPUT_NUMERIC_TIME;
+}
+
 static inline bool nft_output_numeric_proto(const struct output_ctx *octx)
 {
 	return octx->flags & NFT_CTX_OUTPUT_NUMERIC_PROTO;
include/nftables/libnftables.h +3 -1
index e39c588..b84297b 100644
@@ -52,9 +52,11 @@ enum {
 	NFT_CTX_OUTPUT_NUMERIC_PROTO	= (1 << 7),
 	NFT_CTX_OUTPUT_NUMERIC_PRIO     = (1 << 8),
 	NFT_CTX_OUTPUT_NUMERIC_SYMBOL	= (1 << 9),
+	NFT_CTX_OUTPUT_NUMERIC_TIME     = (1 << 10),
 	NFT_CTX_OUTPUT_NUMERIC_ALL	= (NFT_CTX_OUTPUT_NUMERIC_PROTO |
 					   NFT_CTX_OUTPUT_NUMERIC_PRIO |
-					   NFT_CTX_OUTPUT_NUMERIC_SYMBOL),
+					   NFT_CTX_OUTPUT_NUMERIC_SYMBOL |
+					   NFT_CTX_OUTPUT_NUMERIC_TIME),
 };
 
 unsigned int nft_ctx_output_get_flags(struct nft_ctx *ctx);
src/datatype.c +3 -0
index 6d6826e..0a00535 100644
@@ -71,6 +71,9 @@ static const struct datatype *datatypes[TYPE_MAX + 1] = {
 	[TYPE_BOOLEAN]		= &boolean_type,
 	[TYPE_IFNAME]		= &ifname_type,
 	[TYPE_IGMP_TYPE]	= &igmp_type_type,
+	[TYPE_TIME_DATE]	= &date_type,
+	[TYPE_TIME_HOUR]	= &hour_type,
+	[TYPE_TIME_DAY]		= &day_type,
 };
 
 const struct datatype *datatype_lookup(enum datatypes type)
src/main.c +10 -1
index 9a50f30..73036a9 100644
@@ -43,8 +43,9 @@ enum opt_vals {
 	OPT_NUMERIC_PRIO	= 'y',
 	OPT_NUMERIC_PROTO	= 'p',
 	OPT_INVALID		= '?',
+	OPT_SECONDS		= 't',
 };
-#define OPTSTRING	"hvcf:iI:jvnsNaeSupyp"
+#define OPTSTRING	"hvcf:iI:jvnsNaeSupypt"
 
 static const struct option options[] = {
 	{
@@ -114,6 +115,10 @@ static const struct option options[] = {
 		.name		= "numeric-priority",
 		.val		= OPT_NUMERIC_PRIO,
 	},
+	{
+		.name		= "seconds",
+		.val		= OPT_SECONDS,
+	},
 	{
 		.name		= NULL
 	}
@@ -143,6 +148,7 @@ static void show_help(const char *name)
 "  -a, --handle			Output rule handle.\n"
 "  -e, --echo			Echo what has been added, inserted or replaced.\n"
 "  -I, --includepath <directory>	Add <directory> to the paths searched for include files. Default is: %s\n"
+"  -t, --seconds                Show hour values in seconds since midnight.\n"
 "  --debug <level [,level...]>	Specify debugging level (scanner, parser, eval, netlink, mnl, proto-ctx, segtree, all)\n"
 "\n",
 	name, DEFAULT_INCLUDE_PATH);
@@ -282,6 +288,9 @@ int main(int argc, char * const *argv)
 		case OPT_GUID:
 			output_flags |= NFT_CTX_OUTPUT_GUID;
 			break;
+		case OPT_SECONDS:
+			output_flags |= NFT_CTX_OUTPUT_NUMERIC_TIME;
+			break;
 		case OPT_NUMERIC_PRIO:
 			output_flags |= NFT_CTX_OUTPUT_NUMERIC_PRIO;
 			break;
src/meta.c +320 -0

338 lines not on this page · raw message

src/parser_bison.y +4 -0
index 670e91f..26b64da 100644
@@ -415,6 +415,7 @@ int nft_lex(void *, void *, void *);
 %token IIFGROUP			"iifgroup"
 %token OIFGROUP			"oifgroup"
 %token CGROUP			"cgroup"
+%token TIME			"time"
 
 %token CLASSID			"classid"
 %token NEXTHOP			"nexthop"
@@ -3886,6 +3887,9 @@ meta_key_unqualified	:	MARK		{ $$ = NFT_META_MARK; }
 			|       OIFGROUP	{ $$ = NFT_META_OIFGROUP; }
 			|       CGROUP		{ $$ = NFT_META_CGROUP; }
 			|       IPSEC		{ $$ = NFT_META_SECPATH; }
+			|       TIME		{ $$ = NFT_META_TIME; }
+			|       DAY		{ $$ = NFT_META_TIME_DAY; }
+			|       HOUR		{ $$ = NFT_META_TIME_HOUR; }
 			;
 
 meta_stmt		:	META	meta_key	SET	stmt_expr
src/scanner.l +3 -1
index d1f6e87..bd28141 100644
@@ -411,7 +411,9 @@ addrstring	({macaddr}|{ip4addr}|{ip6addr})
 "sack2"			{ return SACK2; }
 "sack3"			{ return SACK3; }
 "sack-permitted"	{ return SACK_PERMITTED; }
-"timestamp"		{ return TIMESTAMP; }
+"time"			{ return TIME; }
+"day"			{ return DAY; }
+"hour"			{ return HOUR; }
 
 "kind"			{ return KIND; }
 "count"			{ return COUNT; }
tests/py/ip/meta.t.payload +84 -0

87 lines not on this page · raw message

Signature · 1 line
2.17.1
#1 lore raw

PATCH v5 2/3 tests/py: Add tests for 'time', 'day' and 'hour'

This commit also modifies nft to print the days of the week in short format (e.g. "Sat" instead of "Saturday").

---
 src/meta.c                     |  14 +-
 tests/py/ip/meta.t             |  15 ++
 tests/py/ip/meta.t.json        | 252 +++++++++++++++++++++++++++++++++
 tests/py/ip/meta.t.json.output | 252 +++++++++++++++++++++++++++++++++
 4 files changed, 526 insertions(+), 7 deletions(-)
src/meta.c +7 -7
index 00ff267..642741f 100644
@@ -477,13 +477,13 @@ success:
 static void day_type_print(const struct expr *expr, struct output_ctx *octx)
 {
 	const char *days[] = {
-		"Sunday",
-		"Monday",
-		"Tuesday",
-		"Wednesday",
-		"Thursday",
-		"Friday",
-		"Saturday"
+		"Sun",
+		"Mon",
+		"Tue",
+		"Wed",
+		"Thu",
+		"Fri",
+		"Sat"
 	};
 
 	uint8_t daynum = mpz_get_uint8(expr->value), numdays = array_size(days);
tests/py/ip/meta.t +15 -0
index 4db8835..ce3da1d 100644
@@ -3,6 +3,21 @@
 *ip;test-ip4;input
 
 icmp type echo-request;ok
+meta time "1970-05-23 21:07:14" drop;ok
+meta time 12341234 drop;ok;meta time "1970-05-23 21:07:14" drop
+meta time "2019-06-21 17:00:00" drop;ok
+meta time "2019-07-01 00:00:00" drop;ok
+meta time "2019-07-01 00:01:00" drop;ok
+meta time "2019-07-01 00:00:01" drop;ok
+meta day "Sat" drop;ok
+meta day "Saturday" drop;ok;meta day "Sat" drop
+meta day 6 drop;ok;meta day "Sat" drop
+meta day "Sa" drop;fail
+meta hour "17:00" drop;ok
+meta hour "17:00:00" drop;ok;meta hour "17:00" drop
+meta hour "17:00:01" drop;ok
+meta hour "00:00" drop;ok
+meta hour "00:01" drop;ok
 meta l4proto icmp icmp type echo-request;ok;icmp type echo-request
 meta l4proto ipv6-icmp icmpv6 type nd-router-advert;ok;icmpv6 type nd-router-advert
 meta l4proto 58 icmpv6 type nd-router-advert;ok;icmpv6 type nd-router-advert
tests/py/ip/meta.t.json +252 -0

258 lines not on this page · raw message

tests/py/ip/meta.t.json.output +252 -0

258 lines not on this page · raw message

Signature · 1 line
2.17.1
maintainer
#2 lore raw

Re: [PATCH v5 2/3] tests/py: Add tests for 'time', 'day' and 'hour'

Quoted 2 lines · Ander Juaristi

This commit also modifies nft to print the days of the week in short format (e.g. "Sat" instead of "Saturday").

Please do that in the first patch.
It makes little sense to first add the long versions just to shorten them again in next patch.

#3 lore raw

PATCH v5 3/3 nft: Update documentation

In reply to Ander Juaristi
---
 doc/nft.txt                |  6 +++++-
 doc/primary-expression.txt | 27 +++++++++++++++++++++++++--
 src/main.c                 |  2 +-
 3 files changed, 31 insertions(+), 4 deletions(-)
doc/nft.txt +5 -1
index 3f1074b..b7a8ee8 100644
@@ -9,7 +9,7 @@ nft - Administration tool of the nftables framework for packet filtering and cla
 SYNOPSIS
 --------
 [verse]
-*nft* [ *-nNscaeSupyj* ] [ *-I* 'directory' ] [ *-f* 'filename' | *-i* | 'cmd' ...]
+*nft* [ *-nNscaeSupyjt* ] [ *-I* 'directory' ] [ *-f* 'filename' | *-i* | 'cmd' ...]
 *nft* *-h*
 *nft* *-v*
 
@@ -93,6 +93,10 @@ For a full summary of options, run *nft --help*.
 	Read input from an interactive readline CLI. You can use quit to exit, or use the EOF marker,
 	normally this is CTRL-D.
 
+*-t*::
+*--seconds*::
+	Show time, day and hour values in seconds.
+
 INPUT FILE FORMATS
 ------------------
 LEXICAL CONVENTIONS
doc/primary-expression.txt +25 -2
index 6eb9583..cef2afc 100644
@@ -2,7 +2,7 @@ META EXPRESSIONS
 ~~~~~~~~~~~~~~~~
 [verse]
 *meta* {*length* | *nfproto* | *l4proto* | *protocol* | *priority*}
-[*meta*] {*mark* | *iif* | *iifname* | *iiftype* | *oif* | *oifname* | *oiftype* | *skuid* | *skgid* | *nftrace* | *rtclassid* | *ibrname* | *obrname* | *pkttype* | *cpu* | *iifgroup* | *oifgroup* | *cgroup* | *random* | *ipsec* | *iifkind* | *oifkind*}
+[*meta*] {*mark* | *iif* | *iifname* | *iiftype* | *oif* | *oifname* | *oiftype* | *skuid* | *skgid* | *nftrace* | *rtclassid* | *ibrname* | *obrname* | *pkttype* | *cpu* | *iifgroup* | *oifgroup* | *cgroup* | *random* | *ipsec* | *iifkind* | *oifkind* | *time* | *hour* | *day* }
 
 A meta expression refers to meta data associated with a packet.
 
@@ -115,7 +115,16 @@ boolean (1 bit)
 |iifkind|
 Input interface kind |
 |oifkind|
-Output interface kind
+Output interface kind|
+|time|
+Absolute time of packet reception|
+Integer (32 bit) or string
+|day|
+Day of week|
+Integer (8 bit) or string
+|hour|
+Hour of day|
+String
 |====================
 
 .Meta expression specific types
@@ -141,6 +150,20 @@ Packet type: *host* (addressed to local host), *broadcast* (to all),
 *multicast* (to group), *other* (addressed to another host).
 |ifkind|
 Interface kind (16 byte string). Does not have to exist.
+|time|
+Either an integer or a date in ISO format. For example: "2019-06-06 17:00".
+Hour and seconds are optional and can be omitted if desired. If omitted,
+midnight will be assumed.
+The following three would be equivalent: "2019-06-06", "2019-06-06 00:00"
+and "2019-06-06 00:00:00".
+When an integer is given, it is assumed to be a UNIX timestamp.
+|day|
+Either a day of week ("Monday", "Tuesday", etc.), or an integer between 0 and 6.
+Strings are matched case-insensitively, and a full match is not expected (e.g. "Mon" would match "Monday").
+When an integer is given, 0 is Sunday and 6 is Saturday.
+|hour|
+A string representing an hour in 24-hour format. Seconds can optionally be specified.
+For example, 17:00 and 17:00:00 would be equivalent.
 |=============================
 
 .Using meta expressions
src/main.c +1 -1
index 73036a9..ab0d4e2 100644
@@ -148,7 +148,7 @@ static void show_help(const char *name)
 "  -a, --handle			Output rule handle.\n"
 "  -e, --echo			Echo what has been added, inserted or replaced.\n"
 "  -I, --includepath <directory>	Add <directory> to the paths searched for include files. Default is: %s\n"
-"  -t, --seconds                Show hour values in seconds since midnight.\n"
+"  -t, --seconds                Show time, day and hour values in seconds.\n"
 "  --debug <level [,level...]>	Specify debugging level (scanner, parser, eval, netlink, mnl, proto-ctx, segtree, all)\n"
 "\n",
 	name, DEFAULT_INCLUDE_PATH);
Signature · 1 line
2.17.1
maintainer
#4 lore raw
In reply to Ander Juaristi
Quoted 2 lines · Ander Juaristi

These keywords introduce new checks for a timestamp, an absolute date (which is converted to a timestamp), an hour in the day (which is converted to the number of seconds since midnight) and a day of week.

[ Pablo, please see below for a usability question ]

This patch causes following compiler warnings for me:
meta.c: In function 'hour_type_print':
meta.c:582:26: warning: '%02d' directive output may be truncated writing between 2 and 10 bytes into a region of size 9 [-Wformat-truncation=]

   snprintf(out, buflen, "%02d:%02d:%02d", hours, minutes, seconds);
                          ^~~~
meta.c:582:25: note: directive argument in the range [0, 2147483647]
   snprintf(out, buflen, "%02d:%02d:%02d", hours, minutes, seconds);
                         ^~~~~~~~~~~~~~~~

meta.c:582:25: note: directive argument in the range [0, 60]
In file included from /usr/include/stdio.h:867, from meta.c:17:
/usr/include/bits/stdio2.h:67:10: note: '__builtin___snprintf_chk' output between 9 and 26 bytes into a destination of size 9
return __builtin___snprintf_chk (__s, __n, __USE_FORTIFY_LEVEL - 1,

          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
meta.c:580:26: warning: '%02d' directive output may be truncated writing between 2 and 10 bytes into a region of size 9 [-Wformat-truncation=]
   snprintf(out, buflen, "%02d:%02d", hours, minutes);
meta.c:580:25: note: directive argument in the range [0, 2147483647] snprintf(out, buflen, "%02d:%02d", hours, minutes);
                         ^~~~~~~~~~~
meta.c:580:25: note: directive argument in the range [0, 60] In file included from /usr/include/stdio.h:867, from meta.c:17:
/usr/include/bits/stdio2.h:67:10: note: '__builtin___snprintf_chk' output between 6 and 14 bytes into a destination of size 9
   return __builtin___snprintf_chk (__s, __n, __USE_FORTIFY_LEVEL - 1,
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There is no bug here, compiler doesn't know that those intergers only contains numbers in the two digit range.

I suggest to "fix" this by increasing out[] to 32 bytes.

Quoted 16 lines
src/meta.c +4 -0
index 1e8964e..00ff267 100644
@@ -37,6 +37,10 @@
 #include <iface.h>
 #include <json.h>
 
+#define _XOPEN_SOURCE
+#define __USE_XOPEN
+#include <time.h>
+
 static struct symbol_table *realm_tbl;
 void realm_table_meta_init(void)
 {

src/meta.c const struct datatype ifname_type = { · line 394

Quoted 8 lines
src/meta.c +5 -0
@@ -383,6 +387,313 @@ const struct datatype ifname_type = {
 	.basetype	= &string_type,
 };
 
+static void date_type_print(const struct expr *expr, struct output_ctx *octx)
+{
+	char timestr[21];
+	struct tm *tm, *cur_tm;
+	uint64_t tstamp = mpz_get_uint64(expr->value);

I would suggest to always order in reverse xmas tree, i.e.

src/meta.c const struct datatype ifname_type = { · line 397

Quoted 3 lines
src/meta.c +3 -0
+	uint64_t tstamp = mpz_get_uint64(expr->value);
+	struct tm *tm, *cur_tm;
+	char timestr[21];

just to get used to this. The networking maintainer (David Miller) prefers it this way for kernel patches (yes, this is an nftables patch but getting used to this ordering is a good idea.

src/meta.c const struct datatype ifname_type = { · line 397

Quoted 2 lines
src/meta.c +2 -0
+	/* Convert from nanoseconds to seconds */
+	tstamp /= 1000000000L;

[..]

This looks good to me, but there are three usability issues.

The worst one first:

nft add rule filter input hour 23:15-00:22 counter

This works. But this fails:
nft add rule filter input hour 23:15-03:22 counter
Error: Range has zero or negative size

Because values are converted to UTC, the first one will be a range from 21:15 to 22:22 UTC, so left < right. Second one is not.

The obvious workaround:

meta hour < "04:22" will NOT match at 00:28 (GMT+2), as its still 22:28 in the UTC time zone.

It will match once local time is past 0 hours UTC.

I suggest to try to fix this from the evaluation step, by swapping left and right and inverting the match.

So 76500-8520 (left larger right) turns into "!= 8520-76500", which appears to do the right thing.

shape and I have no idea how to fix this without using/relying on kernel time zone.

Even when relying on kernel time zone for everything, I don't see how we can support cross-day ("22:23-00:42") matching, as the range is invalid.

Second problem:
For same reason, "Weekday" matching is broken.
If its Monday (00:31), rule that asks for monday won't match, because day is relative to UTC, and since its 22:31 UTC, its still Sunday.

This is unusable when in a time zone much further away.

Only solution I see is to change kernel patch to rely on sys_tz, just like xt_time, with all the pain this brings.

Third problem, but NOT directly related to this patch, its due to existing range expression forcing numeric output:

All time based ranges get printed like this:
meta hour 72600-72720
meta time 1563142680000000000-1563143400000000000

I think we should relax range printing and only force numeric for the new time/hour/day when user did specify the --seconds option.

Ander, you can fix this by finding out where the range print function gets called and by only propagating NFT_CTX_OUTPUT_NUMERIC_TIME when user asked for it instead of doing so unconditionally.

Currently we always force numeric because something like "ssh-http" or "daemon-ftpd" looks very silly, but in case of hours and days I don't think it makes sense to do the raw-printing by default.

Quoted 21 lines
src/meta.c +21 -0
+static struct error_record *hour_type_parse(const struct expr *sym,
+					    struct expr **res)
+{
+	time_t ts;
+	char *endptr;
+	struct tm tm, *cur_tm;
+	uint64_t result = 0;
+	struct error_record *er;
+
+	memset(&tm, 0, sizeof(struct tm));
+
+	/* First, try to parse it as a number */
+	result = strtoul(sym->identifier, (char **) &endptr, 10);
+	if (*endptr == '\0' && endptr != sym->identifier)
+		goto success;
+
+	result = 0;
+
+	/* Obtain current tm, so that we can substract tm_gmtoff */
+	ts = time(NULL);
+	cur_tm = localtime(&ts);

src/meta.c const struct datatype ifname_type = { · line 639

Quoted 10 lines
src/meta.c +10 -0
+
+	if (strptime(sym->identifier, "%T", &tm))
+		goto convert;
+	if (strptime(sym->identifier, "%R", &tm))
+		goto convert;
+
+	if ((er = time_parse(&sym->location, sym->identifier, &result)) == NULL) {
+		result /= 1000;
+		goto convert;
+	}

Seems this function accepts 'meta hour "04:22-23:15"'. This should cause
an error instead of letting user wonder why things don't work as expected:

This passes the string "04:22-23:15" as "04:22".

So this should fail, as this contains invalid '-' character, respectively has too many ":".

src/meta.c const struct meta_template meta_templates[] = { · line 772

Quoted 3 lines
src/meta.c +3 -0
+	[NFT_META_TIME_HOUR]	= META_TEMPLATE("hour", &hour_type,
+						8 * BITS_PER_BYTE,
+						BYTEORDER_HOST_ENDIAN),

Why does hour need 64bits of register space? I think u32 is enough?

Quoted 28 lines
src/meta.c +0 -0
 static bool meta_key_is_unqualified(enum nft_meta_keys key)
src/parser_bison.y +4 -0
index 670e91f..26b64da 100644
@@ -415,6 +415,7 @@ int nft_lex(void *, void *, void *);
 %token IIFGROUP			"iifgroup"
 %token OIFGROUP			"oifgroup"
 %token CGROUP			"cgroup"
+%token TIME			"time"
 
 %token CLASSID			"classid"
 %token NEXTHOP			"nexthop"
@@ -3886,6 +3887,9 @@ meta_key_unqualified	:	MARK		{ $$ = NFT_META_MARK; }
 			|       OIFGROUP	{ $$ = NFT_META_OIFGROUP; }
 			|       CGROUP		{ $$ = NFT_META_CGROUP; }
 			|       IPSEC		{ $$ = NFT_META_SECPATH; }
+			|       TIME		{ $$ = NFT_META_TIME; }
+			|       DAY		{ $$ = NFT_META_TIME_DAY; }
+			|       HOUR		{ $$ = NFT_META_TIME_HOUR; }
 			;
 
 meta_stmt		:	META	meta_key	SET	stmt_expr
src/scanner.l +0 -0
index d1f6e87..bd28141 100644

src/scanner.l addrstring ({macaddr}|{ip4addr}|{ip6addr}) · line 414

Quoted 4 lines
src/scanner.l +0 -1
@@ -411,7 +411,9 @@ addrstring	({macaddr}|{ip4addr}|{ip6addr})
 "sack2"			{ return SACK2; }
 "sack3"			{ return SACK3; }
 "sack-permitted"	{ return SACK_PERMITTED; }
-"timestamp"		{ return TIMESTAMP; }

Won't that break the tcp timestamp option? I think this token needs to stay where it is.

src/scanner.l addrstring ({macaddr}|{ip4addr}|{ip6addr}) · line 416

Quoted 3 lines
src/scanner.l +3 -0
+"time"			{ return TIME; }
+"day"			{ return DAY; }
+"hour"			{ return HOUR; }

Causes:
src/scanner.l:424: warning, rule cannot be matched src/scanner.l:425: warning, rule cannot be matched

as DAY and HOUR rules are duplicates, just remove them.

tests/py/ip/meta.t.payload line 3

Quoted 8 lines
tests/py/ip/meta.t.payload +3 -0
index 322c087..c9bc09f 100644
@@ -1,3 +1,87 @@
+# meta time "1970-05-23 21:07:14" drop
+ip meta-test input
+  [ meta load unknown => reg 1 ]

This "unknown" is coming from libnftnl.
You need to fix up meta_key2str_array[] in src/expr/meta.c in libnftnl.

This should say "time", "time_day" or similar.
Also, shouldn't this come in patch #2 when those tests get added?

Alternatively, you can squash your three patches into one, it would
be fine I think.

maintainer
#5 lore raw
Quoted 21 lines · Florian Westphal

Ander Juaristi <[email protected]> wrote:
This looks good to me, but there are three usability issues.

The worst one first:

nft add rule filter input hour 23:15-00:22 counter

This works. But this fails:
nft add rule filter input hour 23:15-03:22 counter
Error: Range has zero or negative size

Because values are converted to UTC, the first one will be a range from 21:15 to 22:22 UTC, so left < right. Second one is not.

The obvious workaround:

meta hour < "04:22" will NOT match at 00:28 (GMT+2), as its still 22:28 in the UTC time zone.

It will match once local time is past 0 hours UTC.

Quoted 7 lines

I suggest to try to fix this from the evaluation step, by swapping left and right and inverting the match.

So 76500-8520 (left larger right) turns into "!= 8520-76500", which appears to do the right thing.

shape and I have no idea how to fix this without using/relying on kernel time zone.

Argh, I reworded this and forgot to delete this half-sentence above.

Quoted 3 lines

Even when relying on kernel time zone for everything, I don't see how we can support cross-day ("22:23-00:42") matching, as the range is invalid.

And that as well of course, swap and invert should work just fine.

Quoted 3 lines

Second problem:
Only solution I see is to change kernel patch to rely on sys_tz, just like xt_time, with all the pain this brings.

This stands, as the weekday is computed in the kernel, we will need to bring sys_tz into this on the kernel side, the current code uses UTC so we could be several hours off.

This can be restricted to the 'DAY' case of course.

#6 lore raw
Quoted 10 lines · Florian Westphal
Quoted 3 lines

Even when relying on kernel time zone for everything, I don't see how we can support cross-day ("22:23-00:42") matching, as the range is invalid.

And that as well of course, swap and invert should work just fine.

Quoted 3 lines

Second problem:
Only solution I see is to change kernel patch to rely on sys_tz, just like xt_time, with all the pain this brings.

Quoted 6 lines

This stands, as the weekday is computed in the kernel, we will need to bring sys_tz into this on the kernel side, the current code uses UTC so we could be several hours off.

This can be restricted to the 'DAY' case of course.

I see... Thank you. You saved me hours of work figuring this out.

So, for the TIME case we just swap left and right, and for the DAY case, just add (tz_minuteswest * 60) to the seconds before breaking it into day/mon/year?

And what does tz_dsttime do? gettimeofday(2) man says it is there for historical reasons and should be ignored on Linux. But I don't know what is it for in the kernel.

maintainer
#7 lore raw
Quoted 11 lines · Ander Juaristi
Quoted 10 lines · Florian Westphal
Quoted 3 lines

Even when relying on kernel time zone for everything, I don't see how we can support cross-day ("22:23-00:42") matching, as the range is invalid.

And that as well of course, swap and invert should work just fine.

Quoted 3 lines

Second problem:
Only solution I see is to change kernel patch to rely on sys_tz, just like xt_time, with all the pain this brings.

Quoted 8 lines
Quoted 6 lines

This stands, as the weekday is computed in the kernel, we will need to bring sys_tz into this on the kernel side, the current code uses UTC so we could be several hours off.

This can be restricted to the 'DAY' case of course.

I see... Thank you. You saved me hours of work figuring this out.

Giving hints is what I am supposed to do :-)

Quoted 3 lines

So, for the TIME case we just swap left and right, and for the DAY case, just add (tz_minuteswest * 60) to the seconds before breaking it into day/mon/year?

Yes, swap and eq -> not eq -- at least I think that should work and would make something like 18:00-07:00 work.

Quoted 3 lines

And what does tz_dsttime do? gettimeofday(2) man says it is there for historical reasons and should be ignored on Linux. But I don't know what is it for in the kernel.

The kernel has no idea what a time zone is, the tz_dsttime setting comes from userspace, typically during boot via hwclock(8).

IIRC it only flags if we're in 'daylight saving time' or not, i.e. 0 for CET and 1 in CEST case.