From e7d3fc0f82f7bec1cdc22192561f3c9f8296623e Mon Sep 17 00:00:00 2001 From: Maximilian Eschenbacher Date: Wed, 14 Feb 2024 14:32:23 +0100 Subject: [PATCH] counters may be absent --- parser.go | 17 +++++++++++------ parser_test.go | 13 +++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/parser.go b/parser.go index 73a8d81..168d35f 100644 --- a/parser.go +++ b/parser.go @@ -412,7 +412,7 @@ func init() { } var ( - regDefault *regexp.Regexp = regexp.MustCompile(`^\s*(\S+)\s+(\S+)\s+(\[\d*\:\d*\])\s*$`) + regDefault *regexp.Regexp = regexp.MustCompile(`^\s*(\S+)\s+(\S+)(?:\s+(\[\d*\:\d*\]))?\s*$`) regCounter *regexp.Regexp = regexp.MustCompile(`^\[(\d*)\:(\d*)\]$`) ) @@ -422,12 +422,17 @@ func (p *Parser) parseDefault(lit string) (Line, error) { a := regDefault.ReplaceAll([]byte(lit), []byte("$2")) r.Action = string(a) cs := regDefault.ReplaceAll([]byte(lit), []byte("$3")) - c, err := parseCounter(cs) - if err != nil { - return nil, err + if string(cs) == "" { + // nothing has changed + // iptables-restore allows the counter to not exist + r.Counter = &Counter{} + } else { + c, err := parseCounter(cs) + if err != nil { + return nil, err + } + r.Counter = &c } - - r.Counter = &c return r, nil } diff --git a/parser_test.go b/parser_test.go index 6973c3b..7cf2278 100644 --- a/parser_test.go +++ b/parser_test.go @@ -347,6 +347,19 @@ func TestParser_Parse(t *testing.T) { }, err: nil, }, + { + name: "parse default rule without counter", + s: ":hello-chain DROP", + r: Policy{ + Chain: "hello-chain", + Action: "DROP", + Counter: &Counter{ + packets: 0, + bytes: 0, + }, + }, + err: nil, + }, { name: "parse policy", s: "-P hello-chain DROP",