fw4: filter non hw-offload capable devices when resolving lower devices
[project/firewall4.git] / root / usr / share / ucode / fw4.uc
index 932637e39f11b034b386c7cffa3d30340d5554d6..39e850741f75d294d9f3404b2f08b3c1a542eb0d 100644 (file)
@@ -1,19 +1,17 @@
-{%
+const fs = require("fs");
+const uci = require("uci");
+const ubus = require("ubus");
 
-let fs = require("fs");
-let uci = require("uci");
-let ubus = require("ubus");
+const STATEFILE = "/var/run/fw4.state";
 
-let STATEFILE = "/var/run/fw4.state";
+const PARSE_LIST   = 0x01;
+const FLATTEN_LIST = 0x02;
+const NO_INVERT    = 0x04;
+const UNSUPPORTED  = 0x08;
+const REQUIRED     = 0x10;
+const DEPRECATED   = 0x20;
 
-let PARSE_LIST   = 0x01;
-let FLATTEN_LIST = 0x02;
-let NO_INVERT    = 0x04;
-let UNSUPPORTED  = 0x08;
-let REQUIRED     = 0x10;
-let DEPRECATED   = 0x20;
-
-let ipv4_icmptypes = {
+const ipv4_icmptypes = {
        "any": [ 0xFF, 0, 0xFF ],
        "echo-reply": [ 0, 0, 0xFF ],
        "pong": [ 0, 0, 0xFF ], /* Alias */
@@ -68,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 ],
@@ -106,7 +104,7 @@ let ipv6_icmptypes = {
        "redirect": [ 137, 0, 0xFF ]
 };
 
-let dscp_classes = {
+const dscp_classes = {
        "CS0": 0x00,
        "CS1": 0x08,
        "CS2": 0x10,
@@ -156,7 +154,7 @@ function to_bits(mask) {
        let bits = 0;
 
        for (let i = 0, z = false; i < length(a); i++) {
-               z = z || !a[i];
+               z ||= !a[i];
 
                while (!z && (a[i] & 0x80)) {
                        a[i] = (a[i] << 1) & 0xff;
@@ -226,20 +224,19 @@ function null_if_empty(x) {
 }
 
 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;
 }
 
@@ -310,15 +307,15 @@ function infer_family(f, objects) {
                        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`;
                }
        }
 
@@ -332,15 +329,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}saddr`;
                        break;
 
                case 'ipv6_addr':
-                       fields[i] = sprintf('ip6 %saddr', dir);
+                       fields[i] = `ip6 ${dir}saddr`;
                        break;
 
                case 'ether_addr':
@@ -351,7 +348,7 @@ function map_setmatch(set, match, proto) {
                        break;
 
                case 'inet_service':
-                       fields[i] = sprintf('%s %sport', proto, dir);
+                       fields[i] = `${proto} ${dir}port`;
                        break;
                }
        }
@@ -359,20 +356,27 @@ function map_setmatch(set, match, proto) {
        return fields;
 }
 
-function resolve_lower_devices(devstatus, devname) {
-       let dir = fs.opendir("/sys/class/net/" + devname);
+function resolve_lower_devices(devstatus, devname, require_hwoffload) {
+       let dir = fs.opendir(`/sys/class/net/${devname}`);
        let devs = [];
 
        if (dir) {
-               if (!devstatus || devstatus[devname]?.["hw-tc-offload"]) {
-                       push(devs, devname);
-               }
-               else {
+               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)));
+                                       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();
@@ -392,18 +396,33 @@ function nft_json_command(...args) {
                                item => (type(item) == "object" && !item.metainfo));
                }
                catch (e) {
-                       warn(sprintf("Unable to parse nftables JSON output: %s\n", e));
+                       warn(`Unable to parse nftables JSON output: ${e}\n`);
                }
 
                nft.close();
        }
        else {
-               warn(sprintf("Unable to popen() %s: %s\n", cmd, fs.error()));
+               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() {
@@ -426,21 +445,36 @@ 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")) {
-                       let bus = ubus.connect();
+                       for (let zone in this.zones())
+                               for (let device in zone.related_physdevs)
+                                       push(devices, ...resolve_lower_devices(devstatus, device, true));
+
+                       if (length(devices)) {
+                               devices = sort(uniq(devices));
+
+                               if (nft_try_hw_offload(devices))
+                                       return devices;
 
-                       if (bus) {
-                               devstatus = bus.call("network.device", "status") || {};
-                               bus.disconnect();
+                               this.warn('Hardware flow offloading unavailable, falling back to software offloading');
+                               this.state.defaults.flow_offloading_hw = false;
+
+                               devices = [];
                        }
                }
 
-               for (let zone in fw4.zones())
-                       for (let device in zone.match_devices)
-                               push(devices, ...resolve_lower_devices(devstatus, device));
+               for (let zone in this.zones())
+                       for (let device in zone.related_physdevs)
+                               push(devices, ...resolve_lower_devices(devstatus, device, false));
 
-               return uniq(devices);
+               return sort(uniq(devices));
        },
 
        check_set_types: function() {
@@ -470,7 +504,7 @@ return {
                                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();
@@ -492,7 +526,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`);
                }
 
 
@@ -500,18 +534,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,
+                                       physdev: ifc.device,
                                        zone: ifc.data?.zone
                                };
 
                                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),
@@ -522,8 +556,7 @@ return {
 
                                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),
@@ -535,8 +568,7 @@ return {
                                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),
@@ -546,14 +578,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, {
                                                        ...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
                                                });
 
@@ -572,14 +604,14 @@ return {
 
                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, {
                                                        ...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++;
@@ -587,14 +619,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, {
                                                                ...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++;
@@ -661,18 +693,18 @@ 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));
 
 
                //
@@ -705,7 +737,7 @@ return {
                                fd.close();
                        }
                        else {
-                               warn("Unable to write '%s': %s\n", STATEFILE, fs.error());
+                               warn(`Unable to write '${STATEFILE}': ${fs.error()}\n`);
                        }
                }
        },
@@ -717,9 +749,9 @@ return {
                let msg = sprintf(fmt, ...args);
 
                if (getenv("TTY"))
-                       warn("\033[33m", msg, "\033[m\n");
+                       warn(`\033[33m${msg}\033[m\n`);
                else
-                       warn("[!] ", msg, "\n");
+                       warn(`[!] ${msg}\n`);
        },
 
        get: function(sid, opt) {
@@ -734,7 +766,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";
@@ -745,15 +777,15 @@ return {
                                return false;
 
                        if (type(res) == "object" && res.invert && (flags & NO_INVERT)) {
-                               this.warn_section(s, "option '" + key + '" must not be negated');
+                               this.warn_section(s, `option '${key}' must not be negated`);
                                return false;
                        }
 
                        if (res != null) {
                                if (flags & DEPRECATED)
-                                       this.warn_section(s, "option '" + key + "' is deprecated by fw4");
+                                       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");
+                                       this.warn_section(s, `option '${key}' is not supported by fw4`);
                                else
                                        rv[key] = res;
                        }
@@ -761,7 +793,7 @@ return {
 
                for (let opt in s) {
                        if (index(opt, '.') != 0 && opt != 'type' && !exists(spec, opt)) {
-                               this.warn_section(s, "specifies unknown option '" + opt + "'");
+                               this.warn_section(s, `specifies unknown option '${opt}'`);
                        }
                }
 
@@ -858,7 +890,7 @@ return {
                        val = lc(val);
 
                        for (let i = 0; i < length(choices); i++)
-                               if (substr(choices[i], 0, length(val)) == val)
+                               if (lc(substr(choices[i], 0, length(val))) == val)
                                        return choices[i];
                }
 
@@ -881,7 +913,7 @@ return {
                                c++;
                        });
 
-                       return sprintf("@%s[%d]", s[".type"], c);
+                       return `@${s['.type']}[${c}]`;
                }
 
                return s[".name"];
@@ -965,9 +997,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;
        },
@@ -986,14 +1018,10 @@ return {
                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";
-                       }
+                       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;
@@ -1210,8 +1238,8 @@ return {
                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;
+               d[3] ||= 1;
+               d[5] ||= 1;
 
                if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] < 1 || d[3] > 12 || d[5] < 1 || d[5] > 31)
                        return null;
@@ -1250,20 +1278,19 @@ 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);
@@ -1283,8 +1310,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;
@@ -1402,13 +1428,13 @@ return {
                        case 'ipv4_addr':
                                ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
 
-                               switch (length(ip)) {
+                               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] = ("net" in set.fw4types) ? ip[0].addr + "/" + ip[0].bits : ip[0].addr;
+                               rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
                                break;
 
                        case 'ipv6_addr':
@@ -1420,7 +1446,7 @@ return {
                                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] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
 
                                break;
 
@@ -1459,7 +1485,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;
                        }
 
@@ -1467,7 +1493,7 @@ return {
                }
 
                if (type(val) == "array") {
-                       this.warn_section(s, "option '" + opt + "' must not be a list");
+                       this.warn_section(s, `option '${opt}' must not be a list`);
                        return NaN;
                }
                else if (val == null) {
@@ -1477,7 +1503,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;
                }
 
@@ -1490,7 +1516,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;
                        }
 
@@ -1501,7 +1527,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;
                        }
 
@@ -1516,36 +1542,37 @@ return {
 
        quote: function(s, force) {
                if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
-                       return sprintf('"%s"', replace(s + "", /(["\\])/g, '\\$1'));
+                       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;
 
                if (a.bits >= 0)
-                       return sprintf("%s/%d", apply_mask(a.addr, a.bits), a.bits);
+                       return `${apply_mask(a.addr, a.bits)}/${a.bits}`;
 
-               return sprintf("%s/%s", a.addr, a.mask);
+               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) {
@@ -1554,7 +1581,7 @@ return {
                v = filter(to_array(v), item => !seen[item]++);
 
                if (force || length(v) != 1)
-                       return sprintf('{ %s }', join(', ', map(v, this.quote)));
+                       return `{ ${join(', ', map(v, this.quote))} }`;
 
                return this.quote(v[0]);
        },
@@ -1586,6 +1613,22 @@ 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"',
                               stamp.year, stamp.month, stamp.day,
@@ -1605,7 +1648,7 @@ return {
        },
 
        is_loopback_dev: function(dev) {
-               let fd = fs.open(sprintf("/sys/class/net/%s/flags", dev), "r");
+               let fd = fs.open(`/sys/class/net/${dev}/flags`, "r");
 
                if (!fd)
                        return false;
@@ -1670,8 +1713,7 @@ return {
                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;
                }
 
@@ -1686,8 +1728,7 @@ return {
                        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;
                        }
 
@@ -1744,10 +1785,9 @@ return {
                        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) {
@@ -1839,7 +1879,7 @@ return {
                        return;
                }
                else if (zone.helper && !zone.helper.available) {
-                       this.warn_section(data, "uses unavailable ct helper '" + zone.helper.name + "', ignoring section");
+                       this.warn_section(data, `uses unavailable ct helper '${zone.helper.name}', ignoring section`);
                        return;
                }
 
@@ -1848,10 +1888,11 @@ 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;
@@ -1872,6 +1913,9 @@ return {
                                        });
                                }
 
+                               if (net.physdev && !e.invert)
+                                       push(related_physdevs, net.physdev);
+
                                push(related_subnets, ...(net.ipaddrs || []));
                        }
                }
@@ -1903,9 +1947,15 @@ return {
                };
 
                let family = infer_family(zone.family, [
-                       zone.helper, "ct helper"
+                       zone.helper, "ct helper",
+                       match_subnets, "subnet list"
                ]);
 
+               if (type(family) == "string") {
+                       this.warn_section(data, `${family}, skipping`);
+                       return;
+               }
+
                // group non-inverted device matches into wildcard and non-wildcard ones
                let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
 
@@ -1913,7 +1963,7 @@ return {
                        let m = match(device.device, /^([^+]*)(\+)?$/);
 
                        if (!m) {
-                               this.warn_section(data, "skipping invalid wildcard pattern '" + device.device + '"');
+                               this.warn_section(data, `skipping invalid wildcard pattern '${device.device}'`);
                                continue;
                        }
 
@@ -1967,17 +2017,19 @@ return {
 
                                // we need to emit one or two AF specific rules
                                else {
-                                       if (family_is_ipv4(zone) && length(match_subnets[0]))
+                                       if (!family || family == 4)
                                                for (let subnets in subnets_group_by_masking(match_subnets[0]))
                                                        add_rule(4, devgroup, subnets, zone);
 
-                                       if (family_is_ipv6(zone) && length(match_subnets[1]))
+                                       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]);
@@ -1997,6 +2049,7 @@ return {
                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;
@@ -2009,9 +2062,8 @@ return {
                                        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,
@@ -2024,8 +2076,7 @@ return {
                        }
                }
 
-               this.state.zones = this.state.zones || [];
-               push(this.state.zones, zone);
+               push(this.state.zones ||= [], zone);
        },
 
        parse_forwarding: function(data) {
@@ -2056,51 +2107,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 && f2 && f1 != f2) {
-                               this.warn_section(data,
-                                       sprintf("references src %s restricted to %s and dest %s 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);
@@ -2120,7 +2147,7 @@ return {
                        src: [ "zone_ref" ],
                        dest: [ "zone_ref" ],
 
-                       device: [ "device" ],
+                       device: [ "device", null, NO_INVERT ],
                        direction: [ "direction" ],
 
                        ipset: [ "setmatch" ],
@@ -2172,7 +2199,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 + "'");
+                       this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
                        return;
                }
                else if (rule.target == "dscp" && !rule.set_dscp) {
@@ -2187,6 +2214,10 @@ 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;
+               }
 
                let ipset;
 
@@ -2194,7 +2225,7 @@ return {
                        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;
                        }
 
@@ -2204,7 +2235,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 = {
@@ -2227,7 +2258,7 @@ return {
                                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))
+                               icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
                        };
 
                        if (!length(r.icmp_types))
@@ -2256,11 +2287,11 @@ 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") {
@@ -2275,18 +2306,22 @@ return {
                                else
                                        r.chain = "mangle_output";
 
-                               if (r.src?.zone)
+                               if (r.src?.zone) {
                                        r.src.zone.dflags[r.target] = true;
+                                       r.iifnames = null_if_empty(r.src.zone.match_devices);
+                               }
 
-                               if (r.dest?.zone)
+                               if (r.dest?.zone) {
                                        r.dest.zone.dflags[r.target] = true;
+                                       r.oifnames = null_if_empty(r.dest.zone.match_devices);
+                               }
                        }
                        else {
                                r.chain = "output";
 
                                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";
                                }
@@ -2299,19 +2334,21 @@ return {
                                }
 
                                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) {
@@ -2336,22 +2373,24 @@ 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");
+                               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) || rule.dscp !== null);
                        let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
 
@@ -2476,7 +2515,7 @@ return {
                        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;
                        }
 
@@ -2523,12 +2562,12 @@ return {
                                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(data, "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;
@@ -2595,7 +2634,7 @@ 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)
@@ -2604,13 +2643,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) => {
@@ -2630,18 +2668,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);
@@ -2657,113 +2683,140 @@ return {
                                        break;
                                }
 
-                               /* build reflection rules */
-                               if (redir.reflection && (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
-                                       let refredir = {
-                                               name: redir.name + " (reflection)",
+                               break;
+
+                       case "snat":
+                               sip = subnets_split_af(redir.src_ip);
+                               dip = subnets_split_af(redir.dest_ip);
+                               rip = subnets_split_af(redir.src_dip);
+
+                               switch (proto.name) {
+                               case "tcp":
+                               case "udp":
+                                       sport = redir.src_port;
+                                       dport = redir.dest_port;
+                                       rport = redir.src_dport;
+                                       break;
+                               }
 
-                                               helper: redir.helper,
+                               break;
+                       }
 
-                                               // XXX: this likely makes no sense for reflection rules
-                                               //src_mac: redir.src_mac,
+                       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"
+                       ]);
 
-                                               limit: redir.limit,
-                                               limit_burst: redir.limit_burst,
+                       if (type(family) == "string") {
+                               this.warn_section(data, `${family}, skipping`);
+                               continue;
+                       }
 
-                                               start_date: redir.start_date,
-                                               stop_date: redir.stop_date,
-                                               start_time: redir.start_time,
-                                               stop_time: redir.stop_time,
-                                               weekdays: redir.weekdays,
+                       /* 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)`,
 
-                                               mark: redir.mark
-                                       };
+                                       helper: redir.helper,
 
-                                       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 ];
+                                       // XXX: this likely makes no sense for reflection rules
+                                       //src_mac: redir.src_mac,
 
-                                       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;
-                                               }
+                                       limit: redir.limit,
+                                       limit_burst: redir.limit_burst,
 
-                                               let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
-                                               let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
+                                       start_date: redir.start_date,
+                                       stop_date: redir.stop_date,
+                                       start_time: redir.start_time,
+                                       stop_time: redir.stop_time,
+                                       weekdays: redir.weekdays,
 
-                                               for (let i = 0; i <= 1; i++) {
-                                                       if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
-                                                               let snat_addr = refaddrs[i]?.[0];
+                                       mark: redir.mark
+                               };
 
-                                                               /* 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 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 ];
 
-                                                                               let r = apply_mask(rip[i][0].addr, zone_addr.mask);
-                                                                               let a = apply_mask(zone_addr.addr, zone_addr.mask);
+                               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;
+                                       }
 
-                                                                               if (r != a)
-                                                                                       continue;
+                                       let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
+                                       let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
 
-                                                                               snat_addr = zone_addr;
-                                                                               break;
-                                                                       }
-                                                               }
+                                       for (let i = 0; i <= 1; i++) {
+                                               if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
+                                                       let snat_addr = refaddrs[i]?.[0];
 
-                                                               if (snat_addr) {
-                                                                       refredir.src = rzone;
-                                                                       refredir.dest = null;
-                                                                       refredir.target = "dnat";
+                                                       /* 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;
 
-                                                                       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);
+                                                                       let r = apply_mask(rip[i][0].addr, zone_addr.mask);
+                                                                       let a = apply_mask(zone_addr.addr, zone_addr.mask);
 
-                                                                       refredir.src = null;
-                                                                       refredir.dest = rzone;
-                                                                       refredir.target = "snat";
+                                                                       if (r != a)
+                                                                               continue;
 
-                                                                       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);
+                                                                       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)
                                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])) {
+                       if (!family && !has_any_addr) {
                                /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
                                if (family == null)
                                        family = 4;
@@ -2773,13 +2826,13 @@ return {
 
                        /* we need to emit one or two AF specific rules */
                        else {
-                               if ((!family || family == 4) && (length(sip[0]) || length(dip[0]) || length(rip[0]))) {
+                               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 || family == 6) && (length(sip[1]) || length(dip[1]) || length(rip[1]))) {
+                               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);
@@ -2793,7 +2846,7 @@ return {
                        enabled: [ "bool", "1" ],
 
                        name: [ "string", this.section_id(data[".name"]) ],
-                       family: [ "family", "4" ],
+                       family: [ "family" ],
 
                        src: [ "zone_ref" ],
                        device: [ "string" ],
@@ -2868,9 +2921,6 @@ return {
                        return;
                }
 
-               if (snat.src && snat.src.zone)
-                       snat.src.zone.dflags.snat = true;
-
                let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
                        let n = {
                                ...snat,
@@ -2893,11 +2943,10 @@ return {
                                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) {
@@ -2920,19 +2969,21 @@ return {
                        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]))
@@ -2940,7 +2991,7 @@ return {
                                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 */
@@ -3049,17 +3100,15 @@ return {
                        interval: interval
                };
 
-               let self = this;
                s.entries = filter(map(ipset.entry, (e) => {
-                       let v = self.parse_ipsetentry(e, s);
+                       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);
        }
 };