fw4: add support for `option log` in rule and redirect sections
[project/firewall4.git] / root / usr / share / ucode / fw4.uc
index 46dff9a95911371e07d1c798f4d563a236274b22..1b4764cea4fa04d4810b4786b4c28e9b59c84c17 100644 (file)
@@ -1,14 +1,17 @@
-{%
+const fs = require("fs");
+const uci = require("uci");
+const ubus = require("ubus");
 
-let STATEFILE = "/var/run/fw4.state";
+const STATEFILE = "/var/run/fw4.state";
 
-let PARSE_LIST   = 0x01;
-let FLATTEN_LIST = 0x02;
-let NO_INVERT    = 0x04;
-let UNSUPPORTED  = 0x08;
-let REQUIRED     = 0x10;
+const PARSE_LIST   = 0x01;
+const FLATTEN_LIST = 0x02;
+const NO_INVERT    = 0x04;
+const UNSUPPORTED  = 0x08;
+const REQUIRED     = 0x10;
+const DEPRECATED   = 0x20;
 
-let ipv4_icmptypes = {
+const ipv4_icmptypes = {
        "any": [ 0xFF, 0, 0xFF ],
        "echo-reply": [ 0, 0, 0xFF ],
        "pong": [ 0, 0, 0xFF ], /* Alias */
@@ -63,7 +66,7 @@ let ipv4_icmptypes = {
        "address-mask-reply": [ 18, 0, 0xFF ]
 };
 
-let ipv6_icmptypes = {
+const ipv6_icmptypes = {
        "destination-unreachable": [ 1, 0, 0xFF ],
        "no-route": [ 1, 0, 0 ],
        "communication-prohibited": [ 1, 1, 1 ],
@@ -101,7 +104,7 @@ let ipv6_icmptypes = {
        "redirect": [ 137, 0, 0xFF ]
 };
 
-let dscp_classes = {
+const dscp_classes = {
        "CS0": 0x00,
        "CS1": 0x08,
        "CS2": 0x10,
@@ -111,6 +114,7 @@ let dscp_classes = {
        "CS6": 0x30,
        "CS7": 0x38,
        "BE": 0x00,
+       "LE": 0x01,
        "AF11": 0x0a,
        "AF12": 0x0c,
        "AF13": 0x0e,
@@ -126,62 +130,36 @@ let dscp_classes = {
        "EF": 0x2e
 };
 
-/* cache used functions as upvalues */
-let _arrtoip = arrtoip;
-let _delete = delete;
-let _exists = exists;
-let _filter = filter;
-let _getenv = getenv;
-let _hex = hex;
-let _index = index;
-let _iptoarr = iptoarr;
-let _join = join;
-let _json = json;
-let _keys = keys;
-let _lc = lc;
-let _length = length;
-let _map = map;
-let _match = match;
-let _ord = ord;
-let _print = print;
-let _push = push;
-let _replace = replace;
-let _splice = splice;
-let _split = split;
-let _sprintf = sprintf;
-let _substr = substr;
-let _trim = trim;
-let _type = type;
-let _uc = uc;
-let _warn = warn;
-
-let _fs = fs;
-
 function to_mask(bits, v6) {
-       let m = [];
+       let m = [], n = false;
+
+       if (bits < 0) {
+               n = true;
+               bits = -bits;
+       }
 
-       if (bits < 0 || bits > (v6 ? 128 : 32))
+       if (bits > (v6 ? 128 : 32))
                return null;
 
        for (let i = 0; i < (v6 ? 16 : 4); i++) {
                let b = (bits < 8) ? bits : 8;
-               m[i] = (0xff << (8 - b)) & 0xff;
+               m[i] = (n ? ~(0xff << (8 - b)) : (0xff << (8 - b))) & 0xff;
                bits -= b;
        }
 
-       return _arrtoip(m);
+       return arrtoip(m);
 }
 
 function to_bits(mask) {
-       let a = _iptoarr(mask);
+       let a = iptoarr(mask);
 
        if (!a)
                return null;
 
        let bits = 0;
 
-       for (let i = 0, z = false; i < _length(a); i++) {
-               z = z || !a[i];
+       for (let i = 0, z = false; i < length(a); i++) {
+               z ||= !a[i];
 
                while (!z && (a[i] & 0x80)) {
                        a[i] = (a[i] << 1) & 0xff;
@@ -196,115 +174,153 @@ function to_bits(mask) {
 }
 
 function apply_mask(addr, mask) {
-       let a = _iptoarr(addr);
+       let a = iptoarr(addr);
 
        if (!a)
                return null;
 
-       if (_type(mask) == "int") {
-               for (let i = 0; i < _length(a); i++) {
+       if (type(mask) == "int") {
+               for (let i = 0; i < length(a); i++) {
                        let b = (mask < 8) ? mask : 8;
                        a[i] &= (0xff << (8 - b)) & 0xff;
                        mask -= b;
                }
        }
        else {
-               let m = _iptoarr(mask);
+               let m = iptoarr(mask);
 
-               if (!m || _length(a) != _length(m))
+               if (!m || length(a) != length(m))
                        return null;
 
-               for (let i = 0; i < _length(a); i++)
+               for (let i = 0; i < length(a); i++)
                        a[i] &= m[i];
        }
 
-       return _arrtoip(a);
+       return arrtoip(a);
 }
 
 function to_array(x) {
-       if (_type(x) == "array")
+       if (type(x) == "array")
                return x;
 
        if (x == null)
                return [];
 
-       if (_type(x) == "object")
+       if (type(x) == "object")
                return [ x ];
 
-       x = _trim("" + x);
+       x = trim("" + x);
 
-       return (x == "") ? [] : _split(x, /[ \t]+/);
+       return (x == "") ? [] : split(x, /[ \t]+/);
 }
 
 function filter_pos(x) {
-       let rv = _filter(x, e => !e.invert);
-       return _length(rv) ? rv : null;
+       let rv = filter(x, e => !e.invert);
+       return length(rv) ? rv : null;
 }
 
 function filter_neg(x) {
-       let rv = _filter(x, e => e.invert);
-       return _length(rv) ? rv : null;
+       let rv = filter(x, e => e.invert);
+       return length(rv) ? rv : null;
+}
+
+function null_if_empty(x) {
+       return length(x) ? x : null;
 }
 
 function subnets_split_af(x) {
-       let rv = [];
+       let rv = {};
 
        for (let ag in to_array(x)) {
-               for (let a in _filter(ag.addrs, a => (a.family == 4))) {
-                       rv[0] = rv[0] || [];
-                       _push(rv[0], { ...a, invert: ag.invert });
-               }
+               for (let a in filter(ag.addrs, a => (a.family == 4)))
+                       push(rv[0] ||= [], { ...a, invert: ag.invert });
 
-               for (let a in _filter(ag.addrs, a => (a.family == 6))) {
-                       rv[1] = rv[1] || [];
-                       _push(rv[1], { ...a, invert: ag.invert });
-               }
+               for (let a in filter(ag.addrs, a => (a.family == 6)))
+                       push(rv[1] ||= [], { ...a, invert: ag.invert });
        }
 
+       if (rv[0] || rv[1])
+               rv.family = (!rv[0] ^ !rv[1]) ? (rv[0] ? 4 : 6) : 0;
+
        return rv;
 }
 
+function subnets_group_by_masking(x) {
+       let groups = [], plain = [], nc = [], invert_plain = [], invert_masked = [];
+
+       for (let a in to_array(x)) {
+               if (a.bits == -1 && !a.invert)
+                       push(nc, a);
+               else if (!a.invert)
+                       push(plain, a);
+               else if (a.bits == -1)
+                       push(invert_masked, a);
+               else
+                       push(invert_plain, a);
+       }
+
+       for (let a in nc)
+               push(groups, [ null, null_if_empty(invert_plain), [ a, ...invert_masked ] ]);
+
+       if (length(plain)) {
+               push(groups, [
+                       plain,
+                       null_if_empty(invert_plain),
+                       null_if_empty(invert_masked)
+               ]);
+       }
+       else if (!length(groups)) {
+               push(groups, [
+                       null,
+                       null_if_empty(invert_plain),
+                       null_if_empty(invert_masked)
+               ]);
+       }
+
+       return groups;
+}
+
 function ensure_tcpudp(x) {
-       if (_length(_filter(x, p => (p.name == "tcp" || p.name == "udp"))))
+       if (length(filter(x, p => (p.name == "tcp" || p.name == "udp"))))
                return true;
 
-       let rest = _filter(x, p => !p.any),
-           any = _filter(x, p => p.any);
+       let rest = filter(x, p => !p.any),
+           any = filter(x, p => p.any);
 
-       if (_length(any) && !_length(rest)) {
-               _splice(x, 0);
-               _push(x, { name: "tcp" }, { name: "udp" });
+       if (length(any) && !length(rest)) {
+               splice(x, 0);
+               push(x, { name: "tcp" }, { name: "udp" });
                return true;
        }
 
        return false;
 }
 
-function is_family(x, v) { x.family == 0 || x.family == v }
-function family_is_ipv4(x) { x.family == 0 || x.family == 4 }
-function family_is_ipv6(x) { x.family == 0 || x.family == 6 }
+let is_family = (x, v) => (!x.family || x.family == v);
+let family_is_ipv4 = (x) => (!x.family || x.family == 4);
+let family_is_ipv6 = (x) => (!x.family || x.family == 6);
 
 function infer_family(f, objects) {
        let res = f;
        let by = null;
 
-       for (let i = 0; i < _length(objects); i += 2) {
+       for (let i = 0; i < length(objects); i += 2) {
                let objs = to_array(objects[i]),
                    desc = objects[i + 1];
 
                for (let obj in objs) {
-                       if (!obj || obj.family == 0 || obj.family == res)
+                       if (!obj || !obj.family || obj.family == res)
                                continue;
 
-                       if (res == 0) {
+                       if (!res) {
                                res = obj.family;
                                by = obj.desc;
                                continue;
                        }
 
                        return by
-                               ? _sprintf('references IPv%d only %s but is restricted to IPv%d by %s', obj.family, desc, res, by)
-                               : _sprintf('is restricted to IPv%d but referenced %s is IPv%d only', res, desc, obj.family);
+                               ? `references IPv${obj.family} only ${desc} but is restricted to IPv${res} by ${by}`
+                               : `is restricted to IPv${res} but referenced ${desc} is IPv${obj.family} only`;
                }
        }
 
@@ -318,15 +334,15 @@ function map_setmatch(set, match, proto) {
        let fields = [];
 
        for (let i, t in set.types) {
-               let dir = (((match.dir && match.dir[i]) || set.directions[i] || 'src') == 'src' ? 's' : 'd');
+               let dir = ((match.dir?.[i] || set.directions[i] || 'src') == 'src' ? 's' : 'd');
 
                switch (t) {
                case 'ipv4_addr':
-                       fields[i] = _sprintf('ip %saddr', dir);
+                       fields[i] = `ip ${dir}addr`;
                        break;
 
                case 'ipv6_addr':
-                       fields[i] = _sprintf('ip6 %saddr', dir);
+                       fields[i] = `ip6 ${dir}addr`;
                        break;
 
                case 'ether_addr':
@@ -337,7 +353,7 @@ function map_setmatch(set, match, proto) {
                        break;
 
                case 'inet_service':
-                       fields[i] = _sprintf('%s %sport', proto, dir);
+                       fields[i] = `${proto} ${dir}port`;
                        break;
                }
        }
@@ -345,14 +361,81 @@ function map_setmatch(set, match, proto) {
        return fields;
 }
 
+function resolve_lower_devices(devstatus, devname, require_hwoffload) {
+       let dir = fs.opendir(`/sys/class/net/${devname}`);
+       let devs = [];
+
+       if (dir) {
+               switch (devstatus[devname]?.devtype) {
+               case 'vlan':
+               case 'bridge':
+                       let e;
+
+                       while ((e = dir.read()) != null)
+                               if (index(e, "lower_") === 0)
+                                       push(devs, ...resolve_lower_devices(devstatus, substr(e, 6), require_hwoffload));
+
+                       break;
+
+               default:
+                       if (!require_hwoffload || devstatus[devname]?.["hw-tc-offload"])
+                               push(devs, devname);
+
+                       break;
+               }
+
+               dir.close();
+       }
+
+       return devs;
+}
+
+function nft_json_command(...args) {
+       let cmd = [ "/usr/sbin/nft", "--terse", "--json", ...args ];
+       let nft = fs.popen(join(" ", cmd), "r");
+       let info;
+
+       if (nft) {
+               try {
+                       info = filter(json(nft.read("all"))?.nftables,
+                               item => (type(item) == "object" && !item.metainfo));
+               }
+               catch (e) {
+                       warn(`Unable to parse nftables JSON output: ${e}\n`);
+               }
+
+               nft.close();
+       }
+       else {
+               warn(`Unable to popen() ${cmd}: ${fs.error()}\n`);
+       }
+
+       return info || [];
+}
+
+function nft_try_hw_offload(devices) {
+       let nft_test = `
+               add table inet fw4-hw-offload-test;
+               add flowtable inet fw4-hw-offload-test ft {
+                       hook ingress priority 0;
+                       devices = { "${join('", "', devices)}" };
+                       flags offload;
+               }
+       `;
+
+       let rc = system(`/usr/sbin/nft -c '${replace(nft_test, "'", "'\\''")}' 2>/dev/null`);
+
+       return (rc == 0);
+}
+
 
 return {
        read_kernel_version: function() {
-               let fd = _fs.open("/proc/version", "r"),
+               let fd = fs.open("/proc/version", "r"),
                    v = 0;
 
                if (fd) {
-                   let m = _match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
+                   let m = match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
 
                    v = m ? (+m[1] << 24) | (+m[2] << 16) | (+m[3] << 8) : 0;
                    fd.close();
@@ -361,16 +444,70 @@ return {
                return v;
        },
 
+       resolve_offload_devices: function() {
+               if (!this.default_option("flow_offloading"))
+                       return [];
+
+               let devstatus = null;
+               let devices = [];
+               let bus = ubus.connect();
+
+               if (bus) {
+                       devstatus = bus.call("network.device", "status") || {};
+                       bus.disconnect();
+               }
+
+               if (this.default_option("flow_offloading_hw")) {
+                       for (let zone in this.zones())
+                               for (let device in zone.related_physdevs)
+                                       push(devices, ...resolve_lower_devices(devstatus, device, true));
+
+                       devices = sort(uniq(devices));
+
+                       if (length(devices) && nft_try_hw_offload(devices))
+                               return devices;
+
+                       this.warn('Hardware flow offloading unavailable, falling back to software offloading');
+                       this.state.defaults.flow_offloading_hw = false;
+
+                       devices = [];
+               }
+
+               for (let zone in this.zones())
+                       for (let device in zone.related_physdevs)
+                               push(devices, ...resolve_lower_devices(devstatus, device, false));
+
+               return sort(uniq(devices));
+       },
+
+       check_set_types: function() {
+               let sets = {};
+
+               for (let item in nft_json_command("list", "sets", "inet"))
+                       if (item.set?.table == "fw4")
+                               sets[item.set.name] = (type(item.set.type) == "array") ? item.set.type : [ item.set.type ];
+
+               return sets;
+       },
+
+       check_flowtable: function() {
+               for (let item in nft_json_command("list", "flowtables", "inet"))
+                       if (item.flowtable?.table == "fw4" && item.flowtable?.name == "ft")
+                               return true;
+
+               return false;
+       },
+
        read_state: function() {
-               let fd = _fs.open(STATEFILE, "r");
+               let fd = fs.open(STATEFILE, "r");
                let state = null;
 
                if (fd) {
                        try {
-                               state = _json(fd.read("all"));
+                               state = json(fd.read("all"));
                        }
                        catch (e) {
-                               _warn(_sprintf("Unable to parse '%s': %s\n", STATEFILE, e));
+                               warn(`Unable to parse '${STATEFILE}': ${e}\n`);
                        }
 
                        fd.close();
@@ -392,7 +529,7 @@ return {
                    bus.disconnect();
                }
                else {
-                       _warn(_sprintf("Unable to connect to ubus: %s\n", ubus.error()));
+                       warn(`Unable to connect to ubus: ${ubus.error()}\n`);
                }
 
 
@@ -400,17 +537,18 @@ return {
                // Gather logical network information from ubus
                //
 
-               if (_type(ifaces) == "object" && _type(ifaces.interface) == "array") {
+               if (type(ifaces?.interface) == "array") {
                        for (let ifc in ifaces.interface) {
                                let net = {
                                        up: ifc.up,
-                                       device: ifc.l3_device
+                                       device: ifc.l3_device,
+                                       physdev: ifc.device,
+                                       zone: ifc.data?.zone
                                };
 
-                               if (_type(ifc["ipv4-address"]) == "array") {
+                               if (type(ifc["ipv4-address"]) == "array") {
                                        for (let addr in ifc["ipv4-address"]) {
-                                               net.ipaddrs = net.ipaddrs || [];
-                                               _push(net.ipaddrs, {
+                                               push(net.ipaddrs ||= [], {
                                                        family: 4,
                                                        addr: addr.address,
                                                        mask: to_mask(addr.mask, false),
@@ -419,10 +557,9 @@ return {
                                        }
                                }
 
-                               if (_type(ifc["ipv6-address"]) == "array") {
+                               if (type(ifc["ipv6-address"]) == "array") {
                                        for (let addr in ifc["ipv6-address"]) {
-                                               net.ipaddrs = net.ipaddrs || [];
-                                               _push(net.ipaddrs, {
+                                               push(net.ipaddrs ||= [], {
                                                        family: 6,
                                                        addr: addr.address,
                                                        mask: to_mask(addr.mask, true),
@@ -431,11 +568,10 @@ return {
                                        }
                                }
 
-                               if (_type(ifc["ipv6-prefix-assignment"]) == "array") {
+                               if (type(ifc["ipv6-prefix-assignment"]) == "array") {
                                        for (let addr in ifc["ipv6-prefix-assignment"]) {
                                                if (addr["local-address"]) {
-                                                       net.ipaddrs = net.ipaddrs || [];
-                                                       _push(net.ipaddrs, {
+                                                       push(net.ipaddrs ||= [], {
                                                                family: 6,
                                                                addr: addr["local-address"].address,
                                                                mask: to_mask(addr["local-address"].mask, true),
@@ -445,14 +581,14 @@ return {
                                        }
                                }
 
-                               if (_type(ifc.data) == "object" && _type(ifc.data.firewall) == "array") {
+                               if (type(ifc.data?.firewall) == "array") {
                                        let n = 0;
 
                                        for (let rulespec in ifc.data.firewall) {
-                                               _push(rules, {
+                                               push(rules, {
                                                        ...rulespec,
 
-                                                       name: (rulespec.type != 'ipset') ? _sprintf('ubus:%s[%s] %s %d', ifc.interface, ifc.proto, rulespec.type || 'rule', n) : rulespec.name,
+                                                       name: (rulespec.type != 'ipset') ? `ubus:${ifc.interface}[${ifc.proto}] ${rulespec.type || 'rule'} ${n}` : rulespec.name,
                                                        device: rulespec.device || ifc.l3_device
                                                });
 
@@ -469,16 +605,16 @@ return {
                // Gather firewall rule definitions from ubus services
                //
 
-               if (_type(services) == "object") {
+               if (type(services) == "object") {
                        for (let svcname, service in services) {
-                               if (_type(service) == "object" && _type(service.firewall) == "array") {
+                               if (type(service?.firewall) == "array") {
                                        let n = 0;
 
                                        for (let rulespec in services[svcname].firewall) {
-                                               _push(rules, {
+                                               push(rules, {
                                                        ...rulespec,
 
-                                                       name: (rulespec.type != 'ipset') ? _sprintf('ubus:%s %s %d', svcname, rulespec.type || 'rule', n) : rulespec.name
+                                                       name: (rulespec.type != 'ipset') ? `ubus:${svcname} ${rulespec.type || 'rule'} ${n}` : rulespec.name
                                                });
 
                                                n++;
@@ -486,14 +622,14 @@ return {
                                }
 
                                for (let svcinst, instance in service) {
-                                       if (_type(instance) == "object" && _type(instance.firewall) == "array") {
+                                       if (type(instance?.firewall) == "array") {
                                                let n = 0;
 
                                                for (let rulespec in instance.firewall) {
-                                                       _push(rules, {
+                                                       push(rules, {
                                                                ...rulespec,
 
-                                                               name: (rulespec.type != 'ipset') ? _sprintf('ubus:%s[%s] %s %d', svcname, svcinst, rulespec.type || 'rule', n) : rulespec.name
+                                                               name: (rulespec.type != 'ipset') ? `ubus:${svcname}[${svcinst}] ${rulespec.type || 'rule'} ${n}` : rulespec.name
                                                        });
 
                                                        n++;
@@ -537,13 +673,16 @@ return {
 
                this.cursor.foreach("firewall", "defaults", d => self.parse_defaults(d));
 
+               if (!this.state.defaults)
+                       this.parse_defaults({});
+
 
                //
                // Build list of ipsets
                //
 
                if (!this.state.ipsets) {
-                       _map(_filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
+                       map(filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
                        this.cursor.foreach("firewall", "ipset", s => self.parse_ipset(s));
                }
 
@@ -557,25 +696,25 @@ return {
 
 
                //
-               // Build list of forwardings
+               // Build list of rules
                //
 
-               this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
+               map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
+               this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
 
 
                //
-               // Build list of rules
+               // Build list of forwardings
                //
 
-               _map(_filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
-               this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
+               this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
 
 
                //
                // Build list of redirects
                //
 
-               _map(_filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
+               map(filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
                this.cursor.foreach("firewall", "redirect", r => self.parse_redirect(r));
 
 
@@ -583,39 +722,47 @@ return {
                // Build list of snats
                //
 
-               _map(_filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
+               map(filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
                this.cursor.foreach("firewall", "nat", n => self.parse_nat(n));
 
 
+               //
+               // Build list of includes
+               //
+
+               this.cursor.foreach("firewall", "include", i => self.parse_include(i));
+
+
                if (use_statefile) {
-                       let fd = _fs.open(STATEFILE, "w");
+                       let fd = fs.open(STATEFILE, "w");
 
                        if (fd) {
                                fd.write({
                                        zones: this.state.zones,
                                        ipsets: this.state.ipsets,
                                        networks: this.state.networks,
-                                       ubus_rules: this.state.ubus_rules
+                                       ubus_rules: this.state.ubus_rules,
+                                       includes: this.state.includes
                                });
 
                                fd.close();
                        }
                        else {
-                               _warn("Unable to write '%s': %s\n", STATEFILE, _fs.error());
+                               warn(`Unable to write '${STATEFILE}': ${fs.error()}\n`);
                        }
                }
        },
 
        warn: function(fmt, ...args) {
-               if (_getenv("QUIET"))
+               if (getenv("QUIET"))
                        return;
 
-               let msg = _sprintf(fmt, ...args);
+               let msg = sprintf(fmt, ...args);
 
-               if (_getenv("TTY"))
-                       _warn("\033[33m", msg, "\033[m\n");
+               if (getenv("TTY"))
+                       warn(`\033[33m${msg}\033[m\n`);
                else
-                       _warn("[!] ", msg, "\n");
+                       warn(`[!] ${msg}\n`);
        },
 
        get: function(sid, opt) {
@@ -630,7 +777,7 @@ return {
                let rv = {};
 
                for (let key, val in spec) {
-                       let datatype = "parse_" + val[0],
+                       let datatype = `parse_${val[0]}`,
                            defval = val[1],
                            flags = val[2] || 0,
                            parsefn = (flags & PARSE_LIST) ? "parse_list" : "parse_opt";
@@ -640,23 +787,24 @@ return {
                        if (res !== res)
                                return false;
 
-                       if (_type(res) == "object" && res.invert && (flags & NO_INVERT)) {
-                               this.warn_section(s, "option '" + key + '" must not be negated');
+                       if (type(res) == "object" && res.invert && (flags & NO_INVERT)) {
+                               this.warn_section(s, `option '${key}' must not be negated`);
                                return false;
                        }
 
                        if (res != null) {
-                               if (flags & UNSUPPORTED)
-                                       this.warn_section(s, "option '" + key + "' is not supported by fw4");
+                               if (flags & DEPRECATED)
+                                       this.warn_section(s, `option '${key}' is deprecated by fw4`);
+                               else if (flags & UNSUPPORTED)
+                                       this.warn_section(s, `option '${key}' is not supported by fw4`);
                                else
                                        rv[key] = res;
                        }
                }
 
                for (let opt in s) {
-                       if (_index(opt, '.') != 0 && opt != 'type' && !_exists(spec, opt)) {
-                               this.warn_section(s, "specifies unknown option '" + opt + "'");
-                               return false;
+                       if (index(opt, '.') != 0 && opt != 'type' && !exists(spec, opt)) {
+                               this.warn_section(s, `specifies unknown option '${opt}'`);
                        }
                }
 
@@ -664,57 +812,63 @@ return {
        },
 
        parse_subnet: function(subnet) {
-               let parts = _split(subnet, "/");
+               let parts = split(subnet, "/");
                let a, b, m, n;
 
-               switch (_length(parts)) {
+               switch (length(parts)) {
                case 2:
-                       a = _iptoarr(parts[0]);
-                       m = _iptoarr(parts[1]);
+                       a = iptoarr(parts[0]);
+                       m = iptoarr(parts[1]);
 
                        if (!a)
                                return null;
 
                        if (m) {
-                               if (_length(a) != _length(m))
+                               if (length(a) != length(m))
                                        return null;
 
                                b = to_bits(parts[1]);
 
-                               if (b == null)
-                                       return null;
+                               /* allow non-contiguous masks such as `::ffff:ffff:ffff:ffff` */
+                               if (b == null) {
+                                       b = -1;
 
-                               m = _arrtoip(m);
+                                       for (let i, x in m)
+                                               a[i] &= x;
+                               }
+
+                               m = arrtoip(m);
                        }
                        else {
                                b = +parts[1];
 
-                               if (_type(b) != "int")
+                               if (type(b) != "int")
                                        return null;
 
-                               m = to_mask(b, _length(a) == 16);
+                               m = to_mask(b, length(a) == 16);
+                               b = max(-1, b);
                        }
 
                        return [{
-                               family: (_length(a) == 16) ? 6 : 4,
-                               addr: _arrtoip(a),
+                               family: (length(a) == 16) ? 6 : 4,
+                               addr: arrtoip(a),
                                mask: m,
                                bits: b
                        }];
 
                case 1:
-                       parts = _split(parts[0], "-");
+                       parts = split(parts[0], "-");
 
-                       switch (_length(parts)) {
+                       switch (length(parts)) {
                        case 2:
-                               a = _iptoarr(parts[0]);
-                               b = _iptoarr(parts[1]);
+                               a = iptoarr(parts[0]);
+                               b = iptoarr(parts[1]);
 
-                               if (a && b && _length(a) == _length(b)) {
+                               if (a && b && length(a) == length(b)) {
                                        return [{
-                                               family: (_length(a) == 16) ? 6 : 4,
-                                               addr: _arrtoip(a),
-                                               addr2: _arrtoip(b),
+                                               family: (length(a) == 16) ? 6 : 4,
+                                               addr: arrtoip(a),
+                                               addr2: arrtoip(b),
                                                range: true
                                        }];
                                }
@@ -722,14 +876,14 @@ return {
                                break;
 
                        case 1:
-                               a = _iptoarr(parts[0]);
+                               a = iptoarr(parts[0]);
 
                                if (a) {
                                        return [{
-                                               family: (_length(a) == 16) ? 6 : 4,
-                                               addr: _arrtoip(a),
-                                               mask: to_mask(_length(a) * 8, _length(a) == 16),
-                                               bits: _length(a) * 8
+                                               family: (length(a) == 16) ? 6 : 4,
+                                               addr: arrtoip(a),
+                                               mask: to_mask(length(a) * 8, length(a) == 16),
+                                               bits: length(a) * 8
                                        }];
                                }
 
@@ -744,11 +898,11 @@ return {
        },
 
        parse_enum: function(val, choices) {
-               if (_type(val) == "string") {
-                       val = _lc(val);
+               if (type(val) == "string") {
+                       val = lc(val);
 
-                       for (let i = 0; i < _length(choices); i++)
-                               if (_substr(choices[i], 0, _length(val)) == val)
+                       for (let i = 0; i < length(choices); i++)
+                               if (lc(substr(choices[i], 0, length(val))) == val)
                                        return choices[i];
                }
 
@@ -771,7 +925,7 @@ return {
                                c++;
                        });
 
-                       return _sprintf("@%s[%d]", s[".type"], c);
+                       return `@${s['.type']}[${c}]`;
                }
 
                return s[".name"];
@@ -812,9 +966,9 @@ return {
        parse_family: function(val) {
                if (val == 'any' || val == 'all' || val == '*')
                        return 0;
-               else if (val == 'inet' || _index(val, '4') > -1)
+               else if (val == 'inet' || index(val, '4') > -1)
                        return 4;
-               else if (_index(val, '6') > -1)
+               else if (index(val, '6') > -1)
                        return 6;
 
                return null;
@@ -855,9 +1009,9 @@ return {
 
        parse_direction: function(val) {
                if (val == 'in' || val == 'ingress')
-                       return true;
-               else if (val == 'out' || val == 'egress')
                        return false;
+               else if (val == 'out' || val == 'egress')
+                       return true;
 
                return null;
        },
@@ -868,25 +1022,21 @@ return {
                if (!rv)
                        return null;
 
-               rv.val = _trim(_replace(rv.val, /^[^ \t]+/, function(m) {
+               rv.val = trim(replace(rv.val, /^[^ \t]+/, function(m) {
                        rv.name = m;
                        return '';
                }));
 
-               let dir = _split(rv.val, /[ \t,]/);
+               let dir = split(rv.val, /[ \t,]/);
 
-               for (let i = 0; i < 3 && i < _length(dir); i++) {
-                       if (dir[i] == "dst" || dir[i] == "dest") {
-                               rv.dir = rv.dir || [];
-                               rv.dir[i] = "dst";
-                       }
-                       else if (dir[i] == "src") {
-                               rv.dir = rv.dir || [];
-                               rv.dir[i] = "src";
-                       }
+               for (let i = 0; i < 3 && i < length(dir); i++) {
+                       if (dir[i] == "dst" || dir[i] == "dest")
+                               (rv.dir ||= [])[i] = "dst";
+                       else if (dir[i] == "src")
+                               (rv.dir ||= [])[i] = "src";
                }
 
-               return _length(rv.name) ? rv : null;
+               return length(rv.name) ? rv : null;
        },
 
        parse_cthelper: function(val) {
@@ -895,7 +1045,7 @@ return {
                if (!rv)
                        return null;
 
-               let helper = _filter(this.state.helpers, h => (h.name == rv.val))[0];
+               let helper = filter(this.state.helpers, h => (h.name == rv.val))?.[0];
 
                return helper ? { ...rv, ...helper } : null;
        },
@@ -906,7 +1056,7 @@ return {
                if (!p)
                        return null;
 
-               p.val = _lc(p.val);
+               p.val = lc(p.val);
 
                switch (p.val) {
                case 'all':
@@ -944,26 +1094,26 @@ return {
                        p.name = p.val;
                }
 
-               return (p.any || _length(p.name)) ? p : null;
+               return (p.any || length(p.name)) ? p : null;
        },
 
        parse_mac: function(val) {
                let mac = this.parse_invert(val);
-               let m = mac ? _match(mac.val, /^([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})$/i) : null;
+               let m = mac ? match(mac.val, /^([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})$/i) : null;
 
                if (!m)
                        return null;
 
-               mac.mac = _sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
-                                 _hex(m[1]), _hex(m[2]), _hex(m[3]),
-                                 _hex(m[4]), _hex(m[5]), _hex(m[6]));
+               mac.mac = sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
+                                 hex(m[1]), hex(m[2]), hex(m[3]),
+                                 hex(m[4]), hex(m[5]), hex(m[6]));
 
                return mac;
        },
 
        parse_port: function(val) {
                let port = this.parse_invert(val);
-               let m = port ? _match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
+               let m = port ? match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
 
                if (!m)
                        return null;
@@ -1002,9 +1152,9 @@ return {
                let nets = this.parse_subnet(rv.val);
 
                if (nets === null)
-                       return false;
+                       return null;
 
-               if (_length(nets))
+               if (length(nets))
                        rv.addrs = [ ...nets ];
 
                return rv;
@@ -1013,7 +1163,7 @@ return {
        parse_icmptype: function(val) {
                let rv = {};
 
-               if (_exists(ipv4_icmptypes, val)) {
+               if (exists(ipv4_icmptypes, val)) {
                        rv.family = 4;
 
                        rv.type = ipv4_icmptypes[val][0];
@@ -1021,7 +1171,7 @@ return {
                        rv.code_max = ipv4_icmptypes[val][2];
                }
 
-               if (_exists(ipv6_icmptypes, val)) {
+               if (exists(ipv6_icmptypes, val)) {
                        rv.family = rv.family ? 0 : 6;
 
                        rv.type6 = ipv6_icmptypes[val][0];
@@ -1029,8 +1179,8 @@ return {
                        rv.code6_max = ipv6_icmptypes[val][2];
                }
 
-               if (!_exists(rv, "family")) {
-                       let m = _match(val, /^([0-9]+)(\/([0-9]+))?$/);
+               if (!exists(rv, "family")) {
+                       let m = match(val, /^([0-9]+)(\/([0-9]+))?$/);
 
                        if (!m)
                                return null;
@@ -1065,14 +1215,14 @@ return {
 
                let rv = { invert: false };
 
-               rv.val = _trim(_replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
+               rv.val = trim(replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
 
-               return _length(rv.val) ? rv : null;
+               return length(rv.val) ? rv : null;
        },
 
        parse_limit: function(val) {
                let rv = this.parse_invert(val);
-               let m = rv ? _match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
+               let m = rv ? match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
 
                if (!m)
                        return null;
@@ -1096,31 +1246,26 @@ return {
        },
 
        parse_date: function(val) {
-               let m = _match(val, /^([0-9-]+)T([0-9:]+)$/);
-               let d = m ? _match(m[1], /^([0-9]{1,4})(-([0-9]{1,2})(-([0-9]{1,2}))?)?$/) : null;
-               let t = this.parse_time(m[2]);
-
-               d[3] = d[3] || 1;
-               d[5] = d[5] || 1;
+               let d = match(val, /^([0-9]{4})(-([0-9]{1,2})(-([0-9]{1,2})(T([0-9:]+))?)?)?$/);
 
-               if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] < 1 || d[3] > 12 || d[5] < 1 || d[5] > 31)
+               if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] > 12 || d[5] > 31)
                        return null;
 
-               if (m[2] && !t)
+               let t = this.parse_time(d[7] ?? "0");
+
+               if (t == null)
                        return null;
 
                return {
                        year:  +d[1],
-                       month: +d[3],
-                       day:   +d[5],
-                       hour:  t ? +t[1] : 0,
-                       min:   t ? +t[3] : 0,
-                       sec:   t ? +t[5] : 0
+                       month: +d[3] || 1,
+                       day:   +d[5] || 1,
+                       ...t
                };
        },
 
        parse_time: function(val) {
-               let t = _match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
+               let t = match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
 
                if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
                        return null;
@@ -1140,23 +1285,22 @@ return {
 
                for (let day in to_array(rv.val)) {
                        day = this.parse_enum(day, [
-                               "monday",
-                               "tuesday",
-                               "wednesday",
-                               "thursday",
-                               "friday",
-                               "saturday",
-                               "sunday"
+                               "Monday",
+                               "Tuesday",
+                               "Wednesday",
+                               "Thursday",
+                               "Friday",
+                               "Saturday",
+                               "Sunday"
                        ]);
 
                        if (!day)
                                return null;
 
-                       rv.days = rv.days || {};
-                       rv.days[day] = true;
+                       (rv.days ||= {})[day] = true;
                }
 
-               rv.days = _keys(rv.days);
+               rv.days = keys(rv.days);
 
                return rv.days ? rv : null;
        },
@@ -1173,8 +1317,7 @@ return {
                        if (day < 1 || day > 31)
                                return null;
 
-                       rv.days = rv.days || [];
-                       rv.days[day] = true;
+                       (rv.days ||= [])[day] = true;
                }
 
                return rv.days ? rv : null;
@@ -1182,7 +1325,7 @@ return {
 
        parse_mark: function(val) {
                let rv = this.parse_invert(val);
-               let m = rv ? _match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
+               let m = rv ? match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
 
                if (!m)
                        return null;
@@ -1213,13 +1356,13 @@ return {
                if (!rv)
                        return null;
 
-               rv.val = _uc(rv.val);
+               rv.val = uc(rv.val);
 
-               if (_exists(dscp_classes, rv.val)) {
+               if (exists(dscp_classes, rv.val)) {
                        rv.dscp = dscp_classes[rv.val];
                }
                else {
-                       let n = +val;
+                       let n = +rv.val;
 
                        if (n != n || n < 0 || n > 0x3F)
                                return null;
@@ -1266,7 +1409,7 @@ return {
        },
 
        parse_ipsettype: function(val) {
-               let m = _match(val, /^(src|dst|dest)_(.+)$/);
+               let m = match(val, /^(src|dst|dest)_(.+)$/);
                let t = this.parse_enum(m ? m[2] : val, [
                        "ip",
                        "port",
@@ -1279,9 +1422,9 @@ return {
        },
 
        parse_ipsetentry: function(val, set) {
-               let values = _split(val, /[ \t]+/);
+               let values = split(val, /[ \t]+/);
 
-               if (_length(values) != _length(set.types))
+               if (length(values) != length(set.types))
                        return null;
 
                let rv = [];
@@ -1290,21 +1433,28 @@ return {
                for (let i, t in set.types) {
                        switch (t) {
                        case 'ipv4_addr':
-                               ip = _iptoarr(values[i]);
+                               ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
 
-                               if (_length(ip) != 4)
-                                       return null;
+                               switch (length(ip) ?? 0) {
+                               case 0: return null;
+                               case 1: break;
+                               default: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
+                               }
 
-                               rv[i] = _arrtoip(ip);
+                               rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
                                break;
 
                        case 'ipv6_addr':
-                               ip = _iptoarr(values[i]);
+                               ip = filter(this.parse_subnet(values[i]), a => (a.family == 6));
 
-                               if (_length(ip) != 16)
-                                       return null;
+                               switch (length(ip) ?? 0) {
+                               case 0: return null;
+                               case 1: break;
+                               case 2: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
+                               }
+
+                               rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
 
-                               rv[i] = _arrtoip(ip);
                                break;
 
                        case 'ether_addr':
@@ -1330,7 +1480,30 @@ return {
                        }
                }
 
-               return _length(rv) ? rv : null;
+               return length(rv) ? rv : null;
+       },
+
+       parse_includetype: function(val) {
+               return this.parse_enum(val, [
+                       "script",
+                       "nftables"
+               ]);
+       },
+
+       parse_includeposition: function(val) {
+               return replace(this.parse_enum(val, [
+                       "ruleset-prepend",
+                       "ruleset-postpend",
+                       "ruleset-append",
+
+                       "table-prepend",
+                       "table-postpend",
+                       "table-append",
+
+                       "chain-prepend",
+                       "chain-postpend",
+                       "chain-append"
+               ]), "postpend", "append");
        },
 
        parse_string: function(val) {
@@ -1340,17 +1513,17 @@ return {
        parse_opt: function(s, opt, fn, defval, flags) {
                let val = s[opt];
 
-               if (val == null) {
+               if (val === null) {
                        if (flags & REQUIRED) {
-                               this.warn_section(s, "option '" + opt + "' is mandatory but not set");
+                               this.warn_section(s, `option '${opt}' is mandatory but not set`);
                                return NaN;
                        }
 
                        val = defval;
                }
 
-               if (_type(val) == "array") {
-                       this.warn_section(s, "option '" + opt + "' must not be a list");
+               if (type(val) == "array") {
+                       this.warn_section(s, `option '${opt}' must not be a list`);
                        return NaN;
                }
                else if (val == null) {
@@ -1360,7 +1533,7 @@ return {
                let res = this[fn](val);
 
                if (res === null) {
-                       this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
+                       this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
                        return NaN;
                }
 
@@ -1373,7 +1546,7 @@ return {
 
                if (val == null) {
                        if (flags & REQUIRED) {
-                               this.warn_section(s, "option '" + opt + "' is mandatory but not set");
+                               this.warn_section(s, `option '${opt}' is mandatory but not set`);
                                return NaN;
                        }
 
@@ -1384,61 +1557,67 @@ return {
                        let res = this[fn](val);
 
                        if (res === null) {
-                               this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
+                               this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
                                return NaN;
                        }
 
                        if (flags & FLATTEN_LIST)
-                               _push(rv, ...to_array(res));
+                               push(rv, ...to_array(res));
                        else
-                               _push(rv, res);
+                               push(rv, res);
                }
 
-               return _length(rv) ? rv : null;
+               return length(rv) ? rv : null;
        },
 
        quote: function(s, force) {
-               if (force === true || !_match(s, /^([0-9A-Fa-f:.\/]+)( \. [0-9A-Fa-f:.\/]+)*$/))
-                       return _sprintf('"%s"', _replace(s + "", /(["\\])/g, '\\$1'));
+               if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
+                       return `"${replace(s + "", /(["\\])/g, '\\$1')}"`;
 
                return s;
        },
 
        cidr: function(a) {
                if (a.range)
-                       return _sprintf("%s-%s", a.addr, a.addr2);
+                       return `${a.addr}-${a.addr2}`;
 
                if ((a.family == 4 && a.bits == 32) ||
                    (a.family == 6 && a.bits == 128))
                    return a.addr;
 
-               return _sprintf("%s/%d", apply_mask(a.addr, a.bits), a.bits);
+               if (a.bits >= 0)
+                       return `${apply_mask(a.addr, a.bits)}/${a.bits}`;
+
+               return `${a.addr}/${a.mask}`;
        },
 
-       host: function(a) {
+       host: function(a, v6brackets) {
                return a.range
-                       ? _sprintf("%s-%s", a.addr, a.addr2)
-                       : apply_mask(a.addr, a.bits);
+                       ? `${a.addr}-${a.addr2}`
+                       : (a.family == 6 && v6brackets)
+                               ? `[${apply_mask(a.addr, a.bits)}]` : apply_mask(a.addr, a.bits);
        },
 
        port: function(p) {
                if (p.min == p.max)
-                       return _sprintf('%d', p.min);
+                       return `${p.min}`;
 
-               return _sprintf('%d-%d', p.min, p.max);
+               return `${p.min}-${p.max}`;
        },
 
        set: function(v, force) {
-               v = to_array(v);
+               let seen = {};
+
+               v = filter(to_array(v), item => !seen[item]++);
 
-               if (force || _length(v) != 1)
-                       return _sprintf('{ %s }', _join(', ', _map(v, this.quote)));
+               if (force || length(v) != 1)
+                       return `{ ${join(', ', map(v, this.quote))} }`;
 
                return this.quote(v[0]);
        },
 
        concat: function(v) {
-               return _join(' . ', to_array(v));
+               return join(' . ', to_array(v));
        },
 
        ipproto: function(family) {
@@ -1464,49 +1643,58 @@ return {
                }
        },
 
+       l4proto: function(family, proto) {
+               switch (proto.name) {
+               case 'icmp':
+                       switch (family ?? 0) {
+                       case 0:
+                               return this.set(['icmp', 'ipv6-icmp']);
+
+                       case 6:
+                               return 'ipv6-icmp';
+                       }
+
+               default:
+                       return proto.name;
+               }
+       },
+
        datetime: function(stamp) {
-               return _sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
+               return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
                               stamp.year, stamp.month, stamp.day,
                               stamp.hour, stamp.min, stamp.sec);
        },
 
        date: function(stamp) {
-               return _sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
+               return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
+       },
+
+       datestamp: function(stamp) {
+               return exists(stamp, 'hour') ? this.datetime(stamp) : this.date(stamp);
        },
 
        time: function(stamp) {
-               return _sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
+               return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
        },
 
        hex: function(n) {
-               return _sprintf('0x%x', n);
+               return sprintf('0x%x', n);
        },
 
        is_loopback_dev: function(dev) {
-               let fd = _fs.open(_sprintf("/sys/class/net/%s/flags", dev), "r");
-
-               if (!fd)
-                       return false;
-
-               let flags = +fd.read("line");
-
-               fd.close();
-
-               return !!(flags & 0x8);
+               return !!(+fs.readfile(`/sys/class/net/${dev}/flags`) & 0x8);
        },
 
        is_loopback_addr: function(addr) {
-               return (_index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
+               return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
        },
 
        filter_loopback_devs: function(devs, invert) {
-               let self = this;
-               return _filter(devs, d => (self.is_loopback_dev(d) == invert));
+               return null_if_empty(filter(devs, d => (this.is_loopback_dev(d) == invert)));
        },
 
        filter_loopback_addrs: function(addrs, invert) {
-               let self = this;
-               return _filter(addrs, a => (self.is_loopback_addr(a) == invert));
+               return null_if_empty(filter(addrs, a => (this.is_loopback_addr(a) == invert)));
        },
 
 
@@ -1535,39 +1723,67 @@ return {
        },
 
        rules: function(chain) {
-               return _filter(this.state.rules, r => (r.chain == chain));
+               return filter(this.state.rules, r => (r.chain == chain));
        },
 
        redirects: function(chain) {
-               return _filter(this.state.redirects, r => (r.chain == chain));
+               return filter(this.state.redirects, r => (r.chain == chain));
        },
 
        ipsets: function() {
                return this.state.ipsets;
        },
 
+       includes: function(position, chain) {
+               let stmts = [];
+               let pad = '';
+               let pre = '';
+
+               switch (position) {
+               case 'table-prepend':
+               case 'table-append':
+                       pad = '\t';
+                       pre = '\n';
+                       break;
+
+               case 'chain-prepend':
+               case 'chain-append':
+                       pad = '\t\t';
+                       break;
+
+               default:
+                       pre = '\n';
+               }
+
+               push(stmts, pre);
+
+               for (let inc in this.state.includes)
+                       if (inc.type == 'nftables' && inc.position == position && (!chain || inc.chain == chain))
+                               push(stmts, `${pad}include "${inc.path}"\n`);
+
+               print(length(stmts) > 1 ? join('', stmts) : '');
+       },
+
        parse_setfile: function(set, cb) {
-               let fd = _fs.open(set.loadfile, "r");
+               let fd = fs.open(set.loadfile, "r");
 
                if (!fd) {
-                       _warn(_sprintf("Unable to load file '%s' for set '%s': %s\n",
-                                    set.loadfile, set.name, _fs.error()));
+                       warn(`Unable to load file '${set.loadfile}' for set '${set.name}': ${fs.error()}\n`);
                        return;
                }
 
                let line = null, count = 0;
 
                while ((line = fd.read("line")) !== "") {
-                       line = _trim(line);
+                       line = trim(line);
 
-                       if (_length(line) == 0 || _ord(line) == 35)
+                       if (length(line) == 0 || ord(line) == 35)
                                continue;
 
                        let v = this.parse_ipsetentry(line, set);
 
                        if (!v) {
-                               this.warn("Skipping invalid entry '%s' in file '%s' for set '%s'",
-                                         line, set.loadfile, set.name);
+                               this.warn(`Skipping invalid entry '${line}' in file '${set.loadfile}' for set '${set.name}'`);
                                continue;
                        }
 
@@ -1585,20 +1801,20 @@ return {
                let first = true;
                let printer = (entry) => {
                        if (first) {
-                               _print("\t\telements = {\n");
+                               print("\t\telements = {\n");
                                first = false;
                        }
 
-                       _print("\t\t\t", _join(" . ", entry), ",\n");
+                       print("\t\t\t", join(" . ", entry), ",\n");
                };
 
-               _map(set.entries, printer);
+               map(set.entries, printer);
 
                if (set.loadfile)
                        this.parse_setfile(set, printer);
 
                if (!first)
-                       _print("\t\t}\n");
+                       print("\t\t}\n");
        },
 
        parse_helper: function(data) {
@@ -1619,15 +1835,14 @@ return {
                        this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
                        return;
                }
-               else if (_length(helper.proto) > 1) {
+               else if (length(helper.proto) > 1) {
                        this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
                        return;
                }
 
-               helper.available = ((_fs.stat("/sys/module/" + helper.module) || {}).type == "directory");
+               helper.available = (fs.stat(`/sys/module/${helper.module}`)?.type == "directory");
 
-               this.state.helpers = this.state.helpers || [];
-               _push(this.state.helpers, helper);
+               push(this.state.helpers ||= [], helper);
        },
 
        parse_defaults: function(data) {
@@ -1660,19 +1875,14 @@ return {
                        auto_helper: [ "bool", "1" ],
                        custom_chains: [ "bool", null, UNSUPPORTED ],
                        disable_ipv6: [ "bool", null, UNSUPPORTED ],
-                       flow_offloading: [ "bool", null, UNSUPPORTED ],
-                       flow_offloading_hw: [ "bool", null, UNSUPPORTED ]
+                       flow_offloading: [ "bool", "0" ],
+                       flow_offloading_hw: [ "bool", "0" ]
                });
 
-               if (defs === false) {
-                       this.warn_section(data, "skipped due to invalid options");
-                       return;
-               }
-
                if (defs.synflood_protect === null)
                        defs.synflood_protect = defs.syn_flood;
 
-               _delete(defs, "syn_flood");
+               delete defs.syn_flood;
 
                this.state.defaults = defs;
        },
@@ -1697,6 +1907,8 @@ return {
                        masq_src: [ "network", null, PARSE_LIST ],
                        masq_dest: [ "network", null, PARSE_LIST ],
 
+                       masq6: [ "bool" ],
+
                        extra: [ "string", null, UNSUPPORTED ],
                        extra_src: [ "string", null, UNSUPPORTED ],
                        extra_dest: [ "string", null, UNSUPPORTED ],
@@ -1721,9 +1933,11 @@ return {
                        this.warn_section(data, "is disabled, ignoring section");
                        return;
                }
-               else if (zone.helper && !zone.helper.available) {
-                       this.warn_section(data, "uses unavailable ct helper '" + zone.helper.name + "', ignoring section");
-                       return;
+
+               for (let helper in zone.helper) {
+                       if (!helper.available) {
+                               this.warn_section(data, `uses unavailable ct helper '${zone.helper.name}'`);
+                       }
                }
 
                if (zone.mtu_fix && this.kernel < 0x040a0000) {
@@ -1731,35 +1945,47 @@ return {
                        return;
                }
 
-               if (this.state.defaults && this.state.defaults.auto_helper === false)
+               if (this.state.defaults?.auto_helper === false)
                        zone.auto_helper = false;
 
                let match_devices = [];
+               let related_physdevs = [];
                let related_subnets = [];
+               let related_ubus_networks = [];
                let match_subnets, masq_src_subnets, masq_dest_subnets;
 
-               for (let e in to_array(zone.network)) {
-                       if (_exists(this.state.networks, e.device)) {
+               for (let name, net in this.state.networks) {
+                       if (net.zone === zone.name)
+                               push(related_ubus_networks, { invert: false, device: name });
+               }
+
+               zone.network = [ ...to_array(zone.network), ...related_ubus_networks ];
+
+               for (let e in zone.network) {
+                       if (exists(this.state.networks, e.device)) {
                                let net = this.state.networks[e.device];
 
                                if (net.device) {
-                                       _push(match_devices, {
+                                       push(match_devices, {
                                                invert: e.invert,
                                                device: net.device
                                        });
                                }
 
-                               _push(related_subnets, ...(net.ipaddrs || []));
+                               if (net.physdev && !e.invert)
+                                       push(related_physdevs, net.physdev);
+
+                               push(related_subnets, ...(net.ipaddrs || []));
                        }
                }
 
-               _push(match_devices, ...to_array(zone.device));
+               push(match_devices, ...to_array(zone.device));
 
                match_subnets = subnets_split_af(zone.subnet);
                masq_src_subnets = subnets_split_af(zone.masq_src);
                masq_dest_subnets = subnets_split_af(zone.masq_dest);
 
-               _push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
+               push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
 
                let match_rules = [];
 
@@ -1768,55 +1994,109 @@ return {
 
                        r.family = family;
 
-                       r.devices_pos = _map(filter_pos(devices), d => d.device);
-                       r.devices_neg = _map(filter_neg(devices), d => d.device);
+                       r.devices_pos = null_if_empty(devices[0]);
+                       r.devices_neg = null_if_empty(devices[1]);
+                       r.devices_neg_wildcard = null_if_empty(devices[2]);
 
-                       r.subnets_pos = _map(filter_pos(subnets), this.cidr);
-                       r.subnets_neg = _map(filter_neg(subnets), this.cidr);
+                       r.subnets_pos = map(subnets[0], this.cidr);
+                       r.subnets_neg = map(subnets[1], this.cidr);
+                       r.subnets_masked = subnets[2];
 
-                       _push(match_rules, r);
+                       push(match_rules, r);
                };
 
                let family = infer_family(zone.family, [
-                       zone.helper, "ct helper"
+                       zone.helper, "ct helper",
+                       match_subnets, "subnet list"
                ]);
 
-               // check if there's no AF specific bits, in this case we can do AF agnostic matching
-               if (!family && _length(match_devices) && !_length(match_subnets[0]) && !_length(match_subnets[1])) {
-                       add_rule(0, match_devices, null, zone);
+               if (type(family) == "string") {
+                       this.warn_section(data, `${family}, skipping`);
+                       return;
                }
 
-               // we need to emit one or two AF specific rules
-               else {
-                       if (family_is_ipv4(zone) && (_length(match_devices) || _length(match_subnets[0])))
-                               add_rule(4, match_devices, match_subnets[0], zone);
+               // group non-inverted device matches into wildcard and non-wildcard ones
+               let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
 
-                       if (family_is_ipv6(zone) && (_length(match_devices) || _length(match_subnets[1])))
-                               add_rule(6, match_devices, match_subnets[1], zone);
-               }
+               for (let device in match_devices) {
+                       let m = match(device.device, /^([^+]*)(\+)?$/);
 
-               zone.match_rules = match_rules;
+                       if (!m) {
+                               this.warn_section(data, `skipping invalid wildcard pattern '${device.device}'`);
+                               continue;
+                       }
 
-               if (masq_src_subnets[0]) {
-                       zone.masq4_src_pos = _map(filter_pos(masq_src_subnets[0]), this.cidr);
-                       zone.masq4_src_neg = _map(filter_neg(masq_src_subnets[0]), this.cidr);
-               }
+                       // filter `+` (match any device) since nftables does not support
+                       // wildcard only matches
+                       if (!device.invert && m[0] == '+')
+                               continue;
 
-               if (masq_src_subnets[1]) {
-                       zone.masq6_src_pos = _map(filter_pos(masq_src_subnets[1]), this.cidr);
-                       zone.masq6_src_neg = _map(filter_neg(masq_src_subnets[1]), this.cidr);
-               }
+                       // replace inverted `+` (match no device) with invalid pattern
+                       if (device.invert && m[0] == '+') {
+                               device.device = '/never/';
+                               device.invert = false;
+                       }
 
-               if (masq_dest_subnets[0]) {
-                       zone.masq4_dest_pos = _map(filter_pos(masq_dest_subnets[0]), this.cidr);
-                       zone.masq4_dest_neg = _map(filter_neg(masq_dest_subnets[0]), this.cidr);
+                       // replace "name+" matches with "name*"
+                       else if (m[2] == '+')
+                               device.device = m[1] + '*';
+
+                       device.wildcard = !!m[2];
+
+                       if (!device.invert && device.wildcard)
+                               push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
+                       else if (!device.invert)
+                               push(plain_devices, device.device);
+                       else if (device.wildcard)
+                               push(wildcard_invert_devices, device.device);
+                       else
+                               push(plain_invert_devices, device.device);
                }
 
-               if (masq_dest_subnets[1]) {
-                       zone.masq6_dest_pos = _map(filter_pos(masq_dest_subnets[1]), this.cidr);
-                       zone.masq6_dest_neg = _map(filter_neg(masq_dest_subnets[1]), this.cidr);
+               if (length(plain_devices))
+                       push(devices, [
+                               plain_devices,
+                               plain_invert_devices,
+                               wildcard_invert_devices
+                       ]);
+               else if (!length(devices))
+                       push(devices, [
+                               null,
+                               plain_invert_devices,
+                               wildcard_invert_devices
+                       ]);
+
+               // emit zone jump rules for each device group
+               if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
+                       for (let devgroup in devices) {
+                               // check if there's no AF specific bits, in this case we can do AF agnostic matching
+                               if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
+                                       add_rule(0, devgroup, [], zone);
+                               }
+
+                               // we need to emit one or two AF specific rules
+                               else {
+                                       if (!family || family == 4)
+                                               for (let subnets in subnets_group_by_masking(match_subnets[0]))
+                                                       add_rule(4, devgroup, subnets, zone);
+
+                                       if (!family || family == 6)
+                                               for (let subnets in subnets_group_by_masking(match_subnets[1]))
+                                                       add_rule(6, devgroup, subnets, zone);
+                               }
+                       }
                }
 
+               zone.family = family;
+
+               zone.match_rules = match_rules;
+
+               zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
+               zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
+
+               zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
+               zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
+
                zone.sflags = {};
                zone.sflags[zone.input] = true;
 
@@ -1824,25 +2104,25 @@ return {
                zone.dflags[zone.output] = true;
                zone.dflags[zone.forward] = true;
 
-               zone.match_devices = _map(_filter(match_devices, d => !d.invert), d => d.device);
-               zone.match_subnets = _map(_filter(related_subnets, s => !s.invert), this.cidr);
+               zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
+               zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
 
                zone.related_subnets = related_subnets;
+               zone.related_physdevs = related_physdevs;
 
                if (zone.masq || zone.masq6)
                        zone.dflags.snat = true;
 
-               if ((zone.auto_helper && !(zone.masq || zone.masq6)) || _length(zone.helper)) {
+               if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
                        zone.dflags.helper = true;
 
-                       for (let helper in (_length(zone.helper) ? zone.helper : this.state.helpers)) {
+                       for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
                                if (!helper.available)
                                        continue;
 
                                for (let proto in helper.proto) {
-                                       this.state.rules = this.state.rules || [];
-                                       _push(this.state.rules, {
-                                               chain: "helper_" + zone.name,
+                                       push(this.state.rules ||= [], {
+                                               chain: `helper_${zone.name}`,
                                                family: helper.family,
                                                name: helper.description || helper.name,
                                                proto: proto,
@@ -1855,8 +2135,7 @@ return {
                        }
                }
 
-               this.state.zones = this.state.zones || [];
-               _push(this.state.zones, zone);
+               push(this.state.zones ||= [], zone);
        },
 
        parse_forwarding: function(data) {
@@ -1887,51 +2166,27 @@ return {
                                proto: { any: true }
                        };
 
-                       f.name = fwd.name || _sprintf("Accept %s to %s forwarding",
-                               fwd.src.any ? "any" : fwd.src.zone.name,
-                               fwd.dest.any ? "any" : fwd.dest.zone.name);
-
-                       f.chain = fwd.src.any ? "forward" : _sprintf("forward_%s", fwd.src.zone.name);
+                       f.name ||= `Accept ${fwd.src.any ? "any" : fwd.src.zone.name} to ${fwd.dest.any ? "any" : fwd.dest.zone.name} ${family ? `${this.nfproto(family, true)} ` : ''}forwarding`;
+                       f.chain = fwd.src.any ? "forward" : `forward_${fwd.src.zone.name}`;
 
                        if (fwd.dest.any)
                                f.target = "accept";
                        else
-                               f.jump_chain = _sprintf("accept_to_%s", fwd.dest.zone.name);
+                               f.jump_chain = `accept_to_${fwd.dest.zone.name}`;
 
-                       this.state.rules = this.state.rules || [];
-                       _push(this.state.rules, f);
+                       push(this.state.rules ||= [], f);
                };
 
 
-               let family = fwd.family;
-
                /* inherit family restrictions from related zones */
-               if (family === 0 || family === null) {
-                       let f1 = fwd.src.zone ? fwd.src.zone.family : 0;
-                       let f2 = fwd.dest.zone ? fwd.dest.zone.family : 0;
-
-                       if (f1 != 0 && f2 != 0 && f1 != f2) {
-                               this.warn_section(data,
-                                       _sprintf("references src %s restricted to %s and dest restricted to %s, ignoring forwarding",
-                                               fwd.src.zone.name, this.nfproto(f1, true),
-                                               fwd.dest.zone.name, this.nfproto(f2, true)));
-
-                               return;
-                       }
-                       else if (f1) {
-                               this.warn_section(data,
-                                       _sprintf("inheriting %s restriction from src %s",
-                                               this.nfproto(f1, true), fwd.src.zone.name));
-
-                               family = f1;
-                       }
-                       else if (f2) {
-                               this.warn_section(data,
-                                       _sprintf("inheriting %s restriction from dest %s",
-                                               this.nfproto(f2, true), fwd.dest.zone.name));
+               let family = infer_family(fwd.family, [
+                       fwd.src?.zone, "source zone",
+                       fwd.dest?.zone, "destination zone"
+               ]);
 
-                               family = f2;
-                       }
+               if (type(family) == "string") {
+                       this.warn_section(data, `${family}, skipping`);
+                       return;
                }
 
                add_rule(family, fwd);
@@ -1945,12 +2200,13 @@ return {
                        enabled: [ "bool", "1" ],
 
                        name: [ "string", this.section_id(data[".name"]) ],
+                       _name: [ "string", null, DEPRECATED ],
                        family: [ "family" ],
 
                        src: [ "zone_ref" ],
                        dest: [ "zone_ref" ],
 
-                       device: [ "device" ],
+                       device: [ "device", null, NO_INVERT ],
                        direction: [ "direction" ],
 
                        ipset: [ "setmatch" ],
@@ -1988,6 +2244,7 @@ return {
                        set_dscp: [ "dscp", null, NO_INVERT ],
 
                        counter: [ "bool", "1" ],
+                       log: [ "string" ],
 
                        target: [ "target" ]
                });
@@ -2002,11 +2259,7 @@ return {
                }
 
                if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
-                       this.warn_section(data, "must specify a source zone for target '" + rule.target + "'");
-                       return;
-               }
-               else if (rule.target in ["dscp", "mark"] && rule.dest) {
-                       this.warn_section(data, "must not specify option 'dest' for target '" + rule.target + "'");
+                       this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
                        return;
                }
                else if (rule.target == "dscp" && !rule.set_dscp) {
@@ -2021,14 +2274,27 @@ return {
                        this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
                        return;
                }
+               else if (rule.device?.any) {
+                       this.warn_section(data, "must not specify '*' as device");
+                       return;
+               }
+
+               switch (this.parse_bool(rule.log)) {
+               case true:
+                       rule.log = rule.name;
+                       break;
+
+               case false:
+                       delete rule.log;
+               }
 
                let ipset;
 
                if (rule.ipset) {
-                       ipset = _filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
+                       ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
 
                        if (!ipset) {
-                               this.warn_section(data, "references unknown set '" + rule.ipset.name + "'");
+                               this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
                                return;
                        }
 
@@ -2038,7 +2304,7 @@ return {
                        }
                }
 
-               let need_src_action_chain = (rule) => (rule.src && rule.src.zone && rule.src.zone.log && rule.target != "accept");
+               let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target != "accept");
 
                let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
                        let r = {
@@ -2046,27 +2312,29 @@ return {
 
                                family: family,
                                proto: proto,
-                               has_addrs: !!(_length(saddrs) || _length(daddrs)),
-                               has_ports: !!(_length(sports) || _length(dports)),
-                               saddrs_pos: _map(filter_pos(saddrs), this.cidr),
-                               saddrs_neg: _map(filter_neg(saddrs), this.cidr),
-                               daddrs_pos: _map(filter_pos(daddrs), this.cidr),
-                               daddrs_neg: _map(filter_neg(daddrs), this.cidr),
-                               sports_pos: _map(filter_pos(sports), this.port),
-                               sports_neg: _map(filter_neg(sports), this.port),
-                               dports_pos: _map(filter_pos(dports), this.port),
-                               dports_neg: _map(filter_neg(dports), this.port),
-                               smacs_pos: _map(filter_pos(rule.src_mac), m => m.mac),
-                               smacs_neg: _map(filter_neg(rule.src_mac), m => m.mac),
-                               icmp_types: _map(icmptypes, i => (family == 4 ? i.type : i.type6)),
-                               icmp_codes: _map(icmpcodes, ic => _sprintf('%d . %d', (family == 4) ? ic.type : ic.type6, (family == 4) ? ic.code_min : ic.code6_min))
+                               has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
+                               has_ports: !!(length(sports) || length(dports)),
+                               saddrs_pos: map(saddrs[0], this.cidr),
+                               saddrs_neg: map(saddrs[1], this.cidr),
+                               saddrs_masked: saddrs[2],
+                               daddrs_pos: map(daddrs[0], this.cidr),
+                               daddrs_neg: map(daddrs[1], this.cidr),
+                               daddrs_masked: daddrs[2],
+                               sports_pos: map(filter_pos(sports), this.port),
+                               sports_neg: map(filter_neg(sports), this.port),
+                               dports_pos: map(filter_pos(dports), this.port),
+                               dports_neg: map(filter_neg(dports), this.port),
+                               smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
+                               smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
+                               icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
+                               icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
                        };
 
-                       if (!_length(r.icmp_types))
-                               _delete(r, "icmp_types");
+                       if (!length(r.icmp_types))
+                               delete r.icmp_types;
 
-                       if (!_length(r.icmp_codes))
-                               _delete(r, "icmp_codes");
+                       if (!length(r.icmp_codes))
+                               delete r.icmp_codes;
 
                        if (r.set_mark) {
                                r.set_xmark = {
@@ -2075,7 +2343,7 @@ return {
                                        mask:   r.set_mark.mark | r.set_mark.mask
                                };
 
-                               _delete(r, "set_mark");
+                               delete r.set_mark;
                        }
 
                        let set_types = map_setmatch(ipset, rule.ipset, proto.name);
@@ -2088,20 +2356,33 @@ return {
                        }
 
                        if (r.target == "notrack") {
-                               r.chain = _sprintf("notrack_%s", r.src.zone.name);
+                               r.chain = `notrack_${r.src.zone.name}`;
                                r.src.zone.dflags.notrack = true;
                        }
                        else if (r.target == "helper") {
-                               r.chain = _sprintf("helper_%s", r.src.zone.name);
+                               r.chain = `helper_${r.src.zone.name}`;
                                r.src.zone.dflags.helper = true;
                        }
                        else if (r.target == "mark" || r.target == "dscp") {
-                               if (r.src) {
+                               if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
+                                       r.chain = "mangle_forward";
+                               else if (r.src?.any && r.dest?.zone)
+                                       r.chain = "mangle_postrouting";
+                               else if (r.src?.zone && r.dest?.any)
                                        r.chain = "mangle_prerouting";
+                               else if (r.src && !r.dest)
+                                       r.chain = "mangle_input";
+                               else
+                                       r.chain = "mangle_output";
+
+                               if (r.src?.zone) {
                                        r.src.zone.dflags[r.target] = true;
+                                       r.iifnames = null_if_empty(r.src.zone.match_devices);
                                }
-                               else {
-                                       r.chain = "mangle_output";
+
+                               if (r.dest?.zone) {
+                                       r.dest.zone.dflags[r.target] = true;
+                                       r.oifnames = null_if_empty(r.dest.zone.match_devices);
                                }
                        }
                        else {
@@ -2109,32 +2390,34 @@ return {
 
                                if (r.src) {
                                        if (!r.src.any)
-                                               r.chain = _sprintf("%s_%s", r.dest ? "forward" : "input", r.src.zone.name);
+                                               r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
                                        else
                                                r.chain = r.dest ? "forward" : "input";
                                }
 
                                if (r.dest && !r.src) {
                                        if (!r.dest.any)
-                                               r.chain = _sprintf("output_%s", r.dest.zone.name);
+                                               r.chain = sprintf("output_%s", r.dest.zone.name);
                                        else
                                                r.chain = "output";
                                }
 
                                if (r.dest && !r.dest.any) {
-                                       r.jump_chain = _sprintf("%s_to_%s", r.target, r.dest.zone.name);
+                                       r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
                                        r.dest.zone.dflags[r.target] = true;
                                }
                                else if (need_src_action_chain(r)) {
-                                       r.jump_chain = _sprintf("%s_from_%s", r.target, r.src.zone.name);
-                                       r.src.zone.dflags[r.target] = true;
+                                       r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
+                                       r.src.zone.sflags[r.target] = true;
                                }
                                else if (r.target == "reject")
                                        r.jump_chain = "handle_reject";
                        }
 
-                       this.state.rules = this.state.rules || [];
-                       _push(this.state.rules, r);
+                       if (r.device)
+                               r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
+
+                       push(this.state.rules ||= [], r);
                };
 
                for (let proto in rule.proto) {
@@ -2143,13 +2426,13 @@ return {
 
                        switch (proto.name) {
                        case "icmp":
-                               itypes4 = _filter(rule.icmp_type || [], family_is_ipv4);
-                               itypes6 = _filter(rule.icmp_type || [], family_is_ipv6);
+                               itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
+                               itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
                                break;
 
                        case "ipv6-icmp":
                                family = 6;
-                               itypes6 = _filter(rule.icmp_type || [], family_is_ipv6);
+                               itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
                                break;
 
                        case "tcp":
@@ -2159,24 +2442,26 @@ return {
                                break;
                        }
 
+                       sip = subnets_split_af(rule.src_ip);
+                       dip = subnets_split_af(rule.dest_ip);
+
                        family = infer_family(family, [
                                ipset, "set match",
-                               rule.src, "source zone",
-                               rule.dest, "destination zone",
+                               sip, "source IP",
+                               dip, "destination IP",
+                               rule.src?.zone, "source zone",
+                               rule.dest?.zone, "destination zone",
                                rule.helper, "helper match",
                                rule.set_helper, "helper to set"
                        ]);
 
-                       if (_type(family) == "string") {
-                               this.warn_section(data, family + ", skipping");
+                       if (type(family) == "string") {
+                               this.warn_section(data, `${family}, skipping`);
                                continue;
                        }
 
-                       sip = subnets_split_af(rule.src_ip);
-                       dip = subnets_split_af(rule.dest_ip);
-
-                       let has_ipv4_specifics = (_length(sip[0]) || _length(dip[0]) || _length(itypes4));
-                       let has_ipv6_specifics = (_length(sip[1]) || _length(dip[1]) || _length(itypes6));
+                       let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
+                       let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
 
                        /* if no family was configured, infer target family from IP addresses */
                        if (family === null) {
@@ -2190,31 +2475,39 @@ return {
 
                        /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
                        if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
-                               add_rule(0, proto, null, null, sports, dports, null, null, null, rule);
+                               add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
                        }
 
                        /* we need to emit one or two AF specific rules */
                        else {
                                if (family == 0 || family == 4) {
                                        let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
-                                       let icmp_codes = _filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
+                                       let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
 
-                                       if (_length(icmp_types) || (!_length(icmp_types) && !_length(icmp_codes)))
-                                               add_rule(4, proto, sip[0], dip[0], sports, dports, icmp_types, null, ipset, rule);
+                                       for (let saddrs in subnets_group_by_masking(sip[0])) {
+                                               for (let daddrs in subnets_group_by_masking(dip[0])) {
+                                                       if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
+                                                               add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
 
-                                       if (_length(icmp_codes))
-                                               add_rule(4, proto, sip[0], dip[0], sports, dports, null, icmp_codes, ipset, rule);
+                                                       if (length(icmp_codes))
+                                                               add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
+                                               }
+                                       }
                                }
 
                                if (family == 0 || family == 6) {
                                        let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
-                                       let icmp_codes = _filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
+                                       let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
 
-                                       if (_length(icmp_types) || (!_length(icmp_types) && !_length(icmp_codes)))
-                                               add_rule(6, proto, sip[1], dip[1], sports, dports, icmp_types, null, ipset, rule);
+                                       for (let saddrs in subnets_group_by_masking(sip[1])) {
+                                               for (let daddrs in subnets_group_by_masking(dip[1])) {
+                                                       if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
+                                                               add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
 
-                                       if (_length(icmp_codes))
-                                               add_rule(6, proto, sip[1], dip[1], sports, dports, null, icmp_codes, ipset, rule);
+                                                       if (length(icmp_codes))
+                                                               add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
+                                               }
+                                       }
                                }
                        }
                }
@@ -2225,7 +2518,8 @@ return {
                        enabled: [ "bool", "1" ],
 
                        name: [ "string", this.section_id(data[".name"]) ],
-                       family: [ "family", "4" ],
+                       _name: [ "string", null, DEPRECATED ],
+                       family: [ "family" ],
 
                        src: [ "zone_ref" ],
                        dest: [ "zone_ref" ],
@@ -2266,6 +2560,7 @@ return {
                        reflection_zone: [ "zone_ref", null, PARSE_LIST ],
 
                        counter: [ "bool", "1" ],
+                       log: [ "string" ],
 
                        target: [ "target", "dnat" ]
                });
@@ -2284,13 +2579,22 @@ return {
                        redir.target = "dnat";
                }
 
+               switch (this.parse_bool(redir.log)) {
+               case true:
+                       redir.log = redir.name;
+                       break;
+
+               case false:
+                       delete redir.log;
+               }
+
                let ipset;
 
                if (redir.ipset) {
-                       ipset = _filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
+                       ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
 
                        if (!ipset) {
-                               this.warn_section(data, "references unknown set '" + redir.ipset.name + "'");
+                               this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
                                return;
                        }
 
@@ -2302,22 +2606,24 @@ return {
 
                let resolve_dest = (redir) => {
                        for (let zone in this.state.zones) {
-                               for (let addr in zone.related_subnets) {
-                                       if (redir.dest_ip.family != addr.family)
-                                               continue;
+                               for (let zone_addr in zone.related_subnets) {
+                                       for (let dest_addr in redir.dest_ip.addrs) {
+                                               if (dest_addr.family != zone_addr.family)
+                                                       continue;
 
-                                       let a = apply_mask(redir.dest_ip.addr, addr.bits);
-                                       let b = apply_mask(addr.addr, addr.bits);
+                                               let a = apply_mask(dest_addr.addr, zone_addr.mask);
+                                               let b = apply_mask(zone_addr.addr, zone_addr.mask);
 
-                                       if (a != b)
-                                               continue;
+                                               if (a != b)
+                                                       continue;
 
-                                       redir.dest = {
-                                               any: false,
-                                               zone: zone
-                                       };
+                                               redir.dest = {
+                                                       any: false,
+                                                       zone: zone
+                                               };
 
-                                       return true;
+                                               return true;
+                                       }
                                }
                        }
 
@@ -2326,19 +2632,21 @@ return {
 
                if (redir.target == "dnat") {
                        if (!redir.src)
-                               return this.warn_section(r, "has no source specified");
+                               return this.warn_section(data, "has no source specified");
                        else if (redir.src.any)
-                               return this.warn_section(r, "must not have source '*' for dnat target");
+                               return this.warn_section(data, "must not have source '*' for dnat target");
                        else if (redir.dest_ip && redir.dest_ip.invert)
-                               return this.warn_section(r, "must not specify a negated 'dest_ip' value");
+                               return this.warn_section(data, "must not specify a negated 'dest_ip' value");
+                       else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
+                               return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
 
                        if (!redir.dest && redir.dest_ip && resolve_dest(redir))
-                               this.warn_section(r, "does not specify a destination, assuming '" + redir.dest.zone.name + "'");
+                               this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
 
                        if (!redir.dest_port)
                                redir.dest_port = redir.src_dport;
 
-                       if (redir.reflection && redir.dest && redir.dest.zone && redir.src.zone.masq) {
+                       if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
                                redir.dest.zone.dflags.accept = true;
                                redir.dest.zone.dflags.dnat = true;
                                redir.dest.zone.dflags.snat = true;
@@ -2358,6 +2666,8 @@ return {
                                return this.warn_section(data, "has no 'src_dip' option specified");
                        else if (redir.src_dip.invert)
                                return this.warn_section(data, "must not specify a negated 'src_dip' value");
+                       else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
+                               return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
                        else if (redir.src_mac)
                                return this.warn_section(data, "must not use 'src_mac' option for snat target");
                        else if (redir.helper)
@@ -2366,25 +2676,26 @@ return {
                        redir.dest.zone.dflags[redir.target] = true;
                }
 
-
                let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
                        let r = {
                                ...redir,
 
                                family: family,
                                proto: proto,
-                               has_addrs: !!(_length(saddrs) || _length(daddrs)),
+                               has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
                                has_ports: !!(sport || dport || rport),
-                               saddrs_pos: _map(filter_pos(saddrs), this.cidr),
-                               saddrs_neg: _map(filter_neg(saddrs), this.cidr),
-                               daddrs_pos: _map(filter_pos(daddrs), this.cidr),
-                               daddrs_neg: _map(filter_neg(daddrs), this.cidr),
-                               sports_pos: _map(filter_pos(to_array(sport)), this.port),
-                               sports_neg: _map(filter_neg(to_array(sport)), this.port),
-                               dports_pos: _map(filter_pos(to_array(dport)), this.port),
-                               dports_neg: _map(filter_neg(to_array(dport)), this.port),
-                               smacs_pos: _map(filter_pos(redir.src_mac), m => m.mac),
-                               smacs_neg: _map(filter_neg(redir.src_mac), m => m.mac),
+                               saddrs_pos: map(saddrs[0], this.cidr),
+                               saddrs_neg: map(saddrs[1], this.cidr),
+                               saddrs_masked: saddrs[2],
+                               daddrs_pos: map(daddrs[0], this.cidr),
+                               daddrs_neg: map(daddrs[1], this.cidr),
+                               daddrs_masked: daddrs[2],
+                               sports_pos: map(filter_pos(to_array(sport)), this.port),
+                               sports_neg: map(filter_neg(to_array(sport)), this.port),
+                               dports_pos: map(filter_pos(to_array(dport)), this.port),
+                               dports_neg: map(filter_neg(to_array(dport)), this.port),
+                               smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
+                               smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
 
                                raddr: raddrs ? raddrs[0] : null,
                                rport: rport
@@ -2401,7 +2712,8 @@ return {
 
                        switch (r.target) {
                        case "dnat":
-                               r.chain = _sprintf("dstnat_%s", r.src.zone.name);
+                               r.chain = `dstnat_${r.src.zone.name}`;
+                               r.src.zone.dflags.dnat = true;
 
                                if (!r.raddr)
                                        r.target = "redirect";
@@ -2409,12 +2721,12 @@ return {
                                break;
 
                        case "snat":
-                               r.chain = _sprintf("srcnat_%s", r.dest.zone.name);
+                               r.chain = `srcnat_${r.dest.zone.name}`;
+                               r.dest.zone.dflags.snat = true;
                                break;
                        }
 
-                       this.state.redirects = this.state.redirects || [];
-                       _push(this.state.redirects, r);
+                       push(this.state.redirects ||= [], r);
                };
 
                let to_hostaddr = (a) => {
@@ -2434,18 +2746,6 @@ return {
                        if (proto.name == "ipv6-icmp")
                                family = 6;
 
-                       family = infer_family(family, [
-                               ipset, "set match",
-                               redir.src, "source zone",
-                               redir.dest, "destination zone",
-                               redir.helper, "helper match"
-                       ]);
-
-                       if (_type(family) == "string") {
-                               this.warn_section(data, family + ", skipping");
-                               continue;
-                       }
-
                        switch (redir.target) {
                        case "dnat":
                                sip = subnets_split_af(redir.src_ip);
@@ -2461,108 +2761,160 @@ return {
                                        break;
                                }
 
-                               /* build reflection rules */
-                               if (redir.reflection && (_length(rip[0]) || _length(rip[1])) &&
-                                   redir.src && redir.src.zone && redir.src.zone[family == 4 ? "masq" : "masq6"] &&
-                                   redir.dest && redir.dest.zone) {
+                               break;
 
-                                       let refredir = {
-                                               name: redir.name + " (reflection)",
+                       case "snat":
+                               sip = subnets_split_af(redir.src_ip);
+                               dip = subnets_split_af(redir.dest_ip);
+                               rip = subnets_split_af(redir.src_dip);
 
-                                               helper: redir.helper,
+                               switch (proto.name) {
+                               case "tcp":
+                               case "udp":
+                                       sport = redir.src_port;
+                                       dport = redir.dest_port;
+                                       rport = redir.src_dport;
+                                       break;
+                               }
 
-                                               // XXX: this likely makes no sense for reflection rules
-                                               //src_mac: redir.src_mac,
+                               break;
+                       }
 
-                                               limit: redir.limit,
-                                               limit_burst: redir.limit_burst,
+                       family = infer_family(family, [
+                               ipset, "set match",
+                               sip, "source IP",
+                               dip, "destination IP",
+                               rip, "rewrite IP",
+                               redir.src?.zone, "source zone",
+                               redir.dest?.zone, "destination zone",
+                               redir.helper, "helper match"
+                       ]);
 
-                                               start_date: redir.start_date,
-                                               stop_date: redir.stop_date,
-                                               start_time: redir.start_time,
-                                               stop_time: redir.stop_time,
-                                               weekdays: redir.weekdays,
+                       if (type(family) == "string") {
+                               this.warn_section(data, `${family}, skipping`);
+                               continue;
+                       }
 
-                                               mark: redir.mark
-                                       };
+                       /* build reflection rules */
+                       if (redir.target == "dnat" && redir.reflection &&
+                           (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
+                               let refredir = {
+                                       name: `${redir.name} (reflection)`,
 
-                                       let eaddrs = subnets_split_af(_length(dip) ? dip : { addrs: redir.src.zone.related_subnets });
-                                       let rzones = _length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
+                                       helper: redir.helper,
 
-                                       for (let rzone in rzones) {
-                                               if (!is_family(rzone, family)) {
-                                                       this.warn_section(data,
-                                                               _sprintf("is restricted to IPv%d but referenced reflection zone is IPv%d only, skipping",
-                                                                       family, rzone.family));
-                                                       continue;
-                                               }
+                                       // XXX: this likely makes no sense for reflection rules
+                                       //src_mac: redir.src_mac,
 
-                                               let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
-                                               let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
+                                       limit: redir.limit,
+                                       limit_burst: redir.limit_burst,
 
-                                               refaddrs = [
-                                                       _map(refaddrs[0], to_hostaddr),
-                                                       _map(refaddrs[1], to_hostaddr)
-                                               ];
+                                       start_date: redir.start_date,
+                                       stop_date: redir.stop_date,
+                                       start_time: redir.start_time,
+                                       stop_time: redir.stop_time,
+                                       weekdays: redir.weekdays,
 
-                                               eaddrs = [
-                                                       _map(eaddrs[0], to_hostaddr),
-                                                       _map(eaddrs[1], to_hostaddr)
-                                               ];
+                                       mark: redir.mark
+                               };
 
-                                               for (let i = 0; i <= 1; i++) {
-                                                       if (_length(rip[i])) {
-                                                               refredir.src = rzone;
-                                                               refredir.dest = null;
-                                                               refredir.target = "dnat";
-                                                               add_rule(i ? 6 : 4, proto, iaddrs[i], eaddrs[i], rip[i], sport, dport, rport, null, refredir);
+                               let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
+                               let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
+
+                               for (let rzone in rzones) {
+                                       if (!is_family(rzone, family)) {
+                                               this.warn_section(data,
+                                                       `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
+                                               continue;
+                                       }
+
+                                       let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
+                                       let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
+
+                                       for (let i = 0; i <= 1; i++) {
+                                               if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
+                                                       let snat_addr = refaddrs[i]?.[0];
+
+                                                       /* For internal reflection sources try to find a suitable candiate IP
+                                                        * among the reflection zone subnets which is within the same subnet
+                                                        * as the original DNAT destination. If we can't find any matching
+                                                        * one then simply take the first candidate. */
+                                                       if (redir.reflection_src == "internal") {
+                                                               for (let zone_addr in rzone.zone.related_subnets) {
+                                                                       if (zone_addr.family != rip[i][0].family)
+                                                                               continue;
+
+                                                                       let r = apply_mask(rip[i][0].addr, zone_addr.mask);
+                                                                       let a = apply_mask(zone_addr.addr, zone_addr.mask);
+
+                                                                       if (r != a)
+                                                                               continue;
 
-                                                               for (let refaddr in refaddrs[i]) {
-                                                                       refredir.src = null;
-                                                                       refredir.dest = rzone;
-                                                                       refredir.target = "snat";
-                                                                       add_rule(i ? 6 : 4, proto, iaddrs[i], rip[i], [ refaddr ], null, rport, null, null, refredir);
+                                                                       snat_addr = zone_addr;
+                                                                       break;
                                                                }
                                                        }
-                                               }
-                                       }
-                               }
 
+                                                       if (!snat_addr) {
+                                                               this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
+                                                       }
+                                                       else if (!length(iaddrs[i])) {
+                                                               this.warn_section(data, "internal address range cannot be determined, disabling reflection");
+                                                       }
+                                                       else if (!length(eaddrs[i])) {
+                                                               this.warn_section(data, "external address range cannot be determined, disabling reflection");
+                                                       }
+                                                       else {
+                                                               refredir.src = rzone;
+                                                               refredir.dest = null;
+                                                               refredir.target = "dnat";
 
-                               break;
+                                                               for (let saddrs in subnets_group_by_masking(iaddrs[i]))
+                                                                       for (let daddrs in subnets_group_by_masking(eaddrs[i]))
+                                                                               add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
 
-                       case "snat":
-                               sip = subnets_split_af(redir.src_ip);
-                               dip = subnets_split_af(redir.dest_ip);
-                               rip = subnets_split_af(redir.src_dip);
+                                                               refredir.src = null;
+                                                               refredir.dest = rzone;
+                                                               refredir.target = "snat";
 
-                               switch (proto.name) {
-                               case "tcp":
-                               case "udp":
-                                       sport = redir.src_port;
-                                       dport = redir.dest_port;
-                                       rport = redir.src_dport;
-                                       break;
+                                                               for (let daddrs in subnets_group_by_masking(rip[i]))
+                                                                       for (let saddrs in subnets_group_by_masking(iaddrs[i]))
+                                                                               add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
+                                                       }
+                                               }
+                                       }
                                }
-
-                               break;
                        }
 
-                       if (_length(rip[0]) > 1 || _length(rip[1]) > 1)
+                       if (length(rip[0]) > 1 || length(rip[1]) > 1)
                                this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
 
+                       let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
+                           has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
+                           has_any_addr = has_ip4_addr || has_ip6_addr;
+
                        /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
-                       if (!family && !_length(sip[0]) && !_length(sip[1]) && !_length(dip[0]) && !_length(dip[1]) && !_length(rip[0]) && !_length(rip[1])) {
-                               add_rule(0, proto, null, null, null, sport, dport, rport, null, redir);
+                       if (!family && !has_any_addr) {
+                               /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
+                               if (family == null)
+                                       family = 4;
+
+                               add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
                        }
 
                        /* we need to emit one or two AF specific rules */
                        else {
-                               if (family == 0 || family == 4)
-                                       add_rule(4, proto, sip[0], dip[0], rip[0], sport, dport, rport, ipset, redir);
+                               if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
+                                       for (let saddrs in subnets_group_by_masking(sip[0]))
+                                               for (let daddrs in subnets_group_by_masking(dip[0]))
+                                                       add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
+                               }
 
-                               if (family == 0 || family == 6)
-                                       add_rule(6, proto, sip[1], dip[1], rip[1], sport, dport, rport, ipset, redir);
+                               if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
+                                       for (let saddrs in subnets_group_by_masking(sip[1]))
+                                               for (let daddrs in subnets_group_by_masking(dip[1]))
+                                                       add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
+                               }
                        }
                }
        },
@@ -2572,7 +2924,7 @@ return {
                        enabled: [ "bool", "1" ],
 
                        name: [ "string", this.section_id(data[".name"]) ],
-                       family: [ "family", "4" ],
+                       family: [ "family" ],
 
                        src: [ "zone_ref" ],
                        device: [ "string" ],
@@ -2642,8 +2994,10 @@ return {
                        return;
                }
 
-               if (snat.src && snat.src.zone)
-                       snat.src.zone.dflags.snat = true;
+               if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
+                       this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
+                       return;
+               }
 
                let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
                        let n = {
@@ -2651,25 +3005,26 @@ return {
 
                                family: family,
                                proto: proto,
-                               has_addrs: !!(_length(saddrs) || _length(daddrs) || _length(raddrs)),
+                               has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
                                has_ports: !!(sport || dport),
-                               saddrs_pos: _map(filter_pos(saddrs), this.cidr),
-                               saddrs_neg: _map(filter_neg(saddrs), this.cidr),
-                               daddrs_pos: _map(filter_pos(daddrs), this.cidr),
-                               daddrs_neg: _map(filter_neg(daddrs), this.cidr),
-                               sports_pos: _map(filter_pos(to_array(sport)), this.port),
-                               sports_neg: _map(filter_neg(to_array(sport)), this.port),
-                               dports_pos: _map(filter_pos(to_array(dport)), this.port),
-                               dports_neg: _map(filter_neg(to_array(dport)), this.port),
+                               saddrs_pos: map(saddrs[0], this.cidr),
+                               saddrs_neg: map(saddrs[1], this.cidr),
+                               saddrs_masked: saddrs[2],
+                               daddrs_pos: map(daddrs[0], this.cidr),
+                               daddrs_neg: map(daddrs[1], this.cidr),
+                               daddrs_masked: daddrs[2],
+                               sports_pos: map(filter_pos(to_array(sport)), this.port),
+                               sports_neg: map(filter_neg(to_array(sport)), this.port),
+                               dports_pos: map(filter_pos(to_array(dport)), this.port),
+                               dports_neg: map(filter_neg(to_array(dport)), this.port),
 
                                raddr: raddrs ? raddrs[0] : null,
                                rport: rport,
 
-                               chain: (snat.src && snat.src.zone) ? _sprintf("srcnat_%s", snat.src.zone.name) : "srcnat"
+                               chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
                        };
 
-                       this.state.redirects = this.state.redirects || [];
-                       _push(this.state.redirects, n);
+                       push(this.state.redirects ||= [], n);
                };
 
                for (let proto in snat.proto) {
@@ -2689,46 +3044,112 @@ return {
                                break;
                        }
 
-                       if (_length(rip[0]) > 1 || _length(rip[1]) > 1)
+                       if (length(rip[0]) > 1 || length(rip[1]) > 1)
                                this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
 
-                       /* inherit family restrictions from related zones */
-                       if (family === 0 || family === null) {
-                               let f = (rule.src && rule.src.zone) ? rule.src.zone.family : 0;
-
-                               if (f) {
-                                       this.warn_section(r,
-                                               _sprintf("inheriting %s restriction from src %s",
-                                                       this.nfproto(f1, true), rule.src.zone.name));
+                       family = infer_family(family, [
+                               sip, "source IP",
+                               dip, "destination IP",
+                               rip, "rewrite IP",
+                               snat.src?.zone, "source zone"
+                       ]);
 
-                                       family = f;
-                               }
+                       if (type(family) == "string") {
+                               this.warn_section(data, `${family}, skipping`);
+                               continue;
                        }
 
+                       if (snat.src?.zone)
+                               snat.src.zone.dflags.snat = true;
+
                        /* if no family was configured, infer target family from IP addresses */
                        if (family === null) {
-                               if ((_length(sip[0]) || _length(dip[0]) || _length(rip[0])) && !_length(sip[1]) && !_length(dip[1]) && !_length(rip[1]))
+                               if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
                                        family = 4;
-                               else if ((_length(sip[1]) || _length(dip[1]) || _length(rip[1])) && !_length(sip[0]) && !_length(dip[0]) && !_length(rip[0]))
+                               else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
                                        family = 6;
                                else
-                                       family = 0;
+                                       family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
                        }
 
                        /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
-                       if (!family && !_length(sip[0]) && !_length(sip[1]) && !_length(dip[0]) && !_length(dip[1]) && !_length(rip[0]) && !_length(rip[1])) {
-                               add_rule(0, proto, null, null, null, sport, dport, rport, snat);
+                       if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
+                               add_rule(0, proto, [], [], null, sport, dport, rport, snat);
                        }
 
                        /* we need to emit one or two AF specific rules */
                        else {
                                if (family == 0 || family == 4)
-                                       add_rule(4, proto, sip[0], dip[0], rip[0], sport, dport, rport, snat);
+                                       for (let saddr in subnets_group_by_masking(sip[0]))
+                                               for (let daddr in subnets_group_by_masking(dip[0]))
+                                                       add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
 
                                if (family == 0 || family == 6)
-                                       add_rule(6, proto, sip[1], dip[1], rip[1], sport, dport, rport, snat);
+                                       for (let saddr in subnets_group_by_masking(sip[1]))
+                                               for (let daddr in subnets_group_by_masking(dip[1]))
+                                                       add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
+                       }
+               }
+       },
+
+       parse_include: function(data) {
+               let inc = this.parse_options(data, {
+                       enabled: [ "bool", "1" ],
+
+                       path: [ "string", null, REQUIRED ],
+                       type: [ "includetype", "script" ],
+
+                       fw4_compatible: [ "bool", data.path != "/etc/firewall.user" ],
+
+                       family: [ "family", null, UNSUPPORTED ],
+                       reload: [ "bool", null, UNSUPPORTED ],
+
+                       position: [ "includeposition" ],
+                       chain: [ "string" ]
+               });
+
+               if (inc.type == "script" && !inc.fw4_compatible) {
+                       this.warn_section(data, "is not marked as compatible with fw4, ignoring section");
+                       this.warn_section(data, "requires 'option fw4_compatible 1' to be considered compatible");
+                       return;
+               }
+
+               for (let opt in [ "table", "chain", "position" ]) {
+                       if (inc.type != "nftables" && inc[opt]) {
+                               this.warn_section(data, `must not specify '${opt}' for non-nftables includes, ignoring section`);
+                               return;
+                       }
+               }
+
+               switch (inc.position ??= 'table-append') {
+               case 'ruleset-prepend':
+               case 'ruleset-append':
+               case 'table-prepend':
+               case 'table-append':
+                       if (inc.chain)
+                               this.warn_section(data, `specifies 'chain' which has no effect for position ${inc.position}`);
+
+                       delete inc.chain;
+                       break;
+
+               case 'chain-prepend':
+               case 'chain-append':
+                       if (!inc.chain) {
+                               this.warn_section(data, `must specify 'chain' for position ${inc.position}, ignoring section`);
+                               return;
                        }
+
+                       break;
+               }
+
+               let path = fs.readlink(inc.path) ?? inc.path;
+
+               if (!fs.access(path)) {
+                       this.warn_section(data, `specifies unreachable path '${path}', ignoring section`);
+                       return;
                }
+
+               push(this.state.includes ||= [], { ...inc, path });
        },
 
        parse_ipset: function(data) {
@@ -2750,7 +3171,7 @@ return {
                        netmask: [ "int", null, UNSUPPORTED ],
                        maxelem: [ "int" ],
                        hashsize: [ "int", null, UNSUPPORTED ],
-                       timeout: [ "int", null, UNSUPPORTED ],
+                       timeout: [ "int", "-1" ],
 
                        external: [ "string", null, UNSUPPORTED ],
 
@@ -2771,13 +3192,13 @@ return {
                        this.warn_section(data, "must not specify family 'any'");
                        return;
                }
-               else if (!_length(ipset.match)) {
+               else if (!length(ipset.match)) {
                        this.warn_section(data, "has no datatypes assigned");
                        return;
                }
 
-               let dirs = _map(ipset.match, m => m[0]),
-                   types = _map(ipset.match, m => m[1]),
+               let dirs = map(ipset.match, m => m[0]),
+                   types = map(ipset.match, m => m[1]),
                    interval = false;
 
                if ("set" in types) {
@@ -2797,7 +3218,9 @@ return {
                let s = {
                        ...ipset,
 
-                       types: _map(types, (t) => {
+                       fw4types: types,
+
+                       types: map(types, (t) => {
                                switch (t) {
                                case 'ip':
                                case 'net':
@@ -2815,17 +3238,21 @@ return {
                        interval: interval
                };
 
-               let self = this;
-               s.entries = _filter(_map(ipset.entry, (e) => {
-                       let v = self.parse_ipsetentry(e, s);
+               if (s.interval)
+                       push(s.flags ??= [], 'interval');
+
+               if (s.timeout >= 0)
+                       push(s.flags ??= [], 'timeout');
+
+               s.entries = filter(map(ipset.entry, (e) => {
+                       let v = this.parse_ipsetentry(e, s);
 
                        if (!v)
-                               self.warn_section(data, "ignoring invalid ipset entry '" + e + "'");
+                               this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
 
                        return v;
                }), (e) => (e != null));
 
-               this.state.ipsets = this.state.ipsets || [];
-               _push(this.state.ipsets, s);
+               push(this.state.ipsets ||= [], s);
        }
 };