Merge pull request #2197 from yangfl/master
authorHannu Nyman <hannu.nyman@iki.fi>
Wed, 10 Oct 2018 17:25:11 +0000 (20:25 +0300)
committerGitHub <noreply@github.com>
Wed, 10 Oct 2018 17:25:11 +0000 (20:25 +0300)
treewide: Fix typos in comments

applications/luci-app-splash/Makefile
applications/luci-app-statistics/Makefile
libs/luci-lib-iptparser/Makefile [new file with mode: 0644]
libs/luci-lib-iptparser/sys/iptparser.lua [new file with mode: 0644]
libs/luci-lib-iptparser/sys/iptparser.luadoc [new file with mode: 0644]
modules/luci-base/luasrc/sys/iptparser.lua [deleted file]
modules/luci-base/luasrc/sys/iptparser.luadoc [deleted file]
modules/luci-mod-status/luasrc/controller/admin/status.lua
modules/luci-mod-status/luasrc/view/admin_status/iptables.htm

index 5740aa5f7c4364923bbd18b2822bb15204838885..46537248710962768495fe91585823409740d3d0 100644 (file)
@@ -7,7 +7,7 @@
 include $(TOPDIR)/rules.mk
 
 LUCI_TITLE:=Freifunk DHCP-Splash application
-LUCI_DEPENDS:=+luci-lib-nixio +tc +kmod-sched +iptables-mod-nat-extra +iptables-mod-ipopt
+LUCI_DEPENDS:=+luci-lib-nixio +luci-lib-iptparser +tc +kmod-sched +iptables-mod-nat-extra +iptables-mod-ipopt
 
 define Package/luci-app-splash/conffiles
 /etc/config/luci_splash
index 008792a5d018078525e53ea21dc62d0d22fd7e96..b552400fed90db1510361d5649764724ac3dbffb 100644 (file)
@@ -8,6 +8,7 @@ include $(TOPDIR)/rules.mk
 
 LUCI_TITLE:=LuCI Statistics Application
 LUCI_DEPENDS:= \
+       +luci-lib-iptparser \
        +collectd +rrdtool1 +collectd-mod-rrdtool +collectd-mod-iwinfo \
        +collectd-mod-cpu +collectd-mod-memory \
        +collectd-mod-interface +collectd-mod-load +collectd-mod-network
diff --git a/libs/luci-lib-iptparser/Makefile b/libs/luci-lib-iptparser/Makefile
new file mode 100644 (file)
index 0000000..06748ad
--- /dev/null
@@ -0,0 +1,14 @@
+#
+# Copyright (C) 2018 The LuCI Team <luci@lists.subsignal.org>
+#
+# This is free software, licensed under the Apache License, Version 2.0 .
+#
+
+include $(TOPDIR)/rules.mk
+
+LUCI_TITLE:=Iptables listing parser class
+LUCI_DEPENDS:=+luci-base
+
+include ../../luci.mk
+
+# call BuildPackage - OpenWrt buildroot signature
diff --git a/libs/luci-lib-iptparser/sys/iptparser.lua b/libs/luci-lib-iptparser/sys/iptparser.lua
new file mode 100644 (file)
index 0000000..7ff665e
--- /dev/null
@@ -0,0 +1,374 @@
+--[[
+
+Iptables parser and query library
+(c) 2008-2009 Jo-Philipp Wich <jow@openwrt.org>
+(c) 2008-2009 Steven Barth <steven@midlink.org>
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+$Id$
+
+]]--
+
+local luci  = {}
+luci.util   = require "luci.util"
+luci.sys    = require "luci.sys"
+luci.ip     = require "luci.ip"
+
+local pcall = pcall
+local io = require "io"
+local tonumber, ipairs, table = tonumber, ipairs, table
+
+module("luci.sys.iptparser")
+
+IptParser = luci.util.class()
+
+function IptParser.__init__( self, family )
+       self._family = (tonumber(family) == 6) and 6 or 4
+       self._rules  = { }
+       self._chains = { }
+       self._tables = { }
+
+       local t = self._tables
+       local s = self:_supported_tables(self._family)
+
+       if s.filter then t[#t+1] = "filter" end
+       if s.nat    then t[#t+1] = "nat"    end
+       if s.mangle then t[#t+1] = "mangle" end
+       if s.raw    then t[#t+1] = "raw"    end
+
+       if self._family == 4 then
+               self._nulladdr = "0.0.0.0/0"
+               self._command  = "iptables -t %s --line-numbers -nxvL"
+       else
+               self._nulladdr = "::/0"
+               self._command  = "ip6tables -t %s --line-numbers -nxvL"
+       end
+
+       self:_parse_rules()
+end
+
+function IptParser._supported_tables( self, family )
+       local tables = { }
+       local ok, lines = pcall(io.lines,
+               (family == 6) and "/proc/net/ip6_tables_names"
+                              or "/proc/net/ip_tables_names")
+
+       if ok and lines then
+               local line
+               for line in lines do
+                       tables[line] = true
+               end
+       end
+
+       return tables
+end
+
+-- search criteria as only argument. If args is nil or an empty table then all
+-- rules will be returned.
+--
+-- The following keys in the args table are recognized:
+-- <ul>
+--  <li> table          - Match rules that are located within the given table
+--  <li> chain          - Match rules that are located within the given chain
+--  <li> target                 - Match rules with the given target
+--  <li> protocol       - Match rules that match the given protocol, rules with
+--                                             protocol "all" are always matched
+--  <li> source                 - Match rules with the given source, rules with source
+--                                             "0.0.0.0/0" (::/0) are always matched
+--  <li> destination - Match rules with the given destination, rules with
+--                                             destination "0.0.0.0/0" (::/0) are always matched
+--  <li> inputif        - Match rules with the given input interface, rules
+--                                             with input      interface "*" (=all) are always matched
+--  <li> outputif       - Match rules with the given output interface, rules
+--                                             with output     interface "*" (=all) are always matched
+--  <li> flags          - Match rules that match the given flags, current
+--                                             supported values are "-f" (--fragment)
+--                                             and "!f" (! --fragment)
+--  <li> options        - Match rules containing all given options
+-- </ul>
+-- The return value is a list of tables representing the matched rules.
+-- Each rule table contains the following fields:
+-- <ul>
+--  <li> index          - The index number of the rule
+--  <li> table          - The table where the rule is located, can be one
+--                                             of "filter", "nat" or "mangle"
+--  <li> chain          - The chain where the rule is located, e.g. "INPUT"
+--                                             or "postrouting_wan"
+--  <li> target                 - The rule target, e.g. "REJECT" or "DROP"
+--  <li> protocol              The matching protocols, e.g. "all" or "tcp"
+--  <li> flags          - Special rule options ("--", "-f" or "!f")
+--  <li> inputif        - Input interface of the rule, e.g. "eth0.0"
+--                                             or "*" for all interfaces
+--  <li> outputif       - Output interface of the rule,e.g. "eth0.0"
+--                                             or "*" for all interfaces
+--  <li> source                 - The source ip range, e.g. "0.0.0.0/0" (::/0)
+--  <li> destination - The destination ip range, e.g. "0.0.0.0/0" (::/0)
+--  <li> options        - A list of specific options of the rule,
+--                                             e.g. { "reject-with", "tcp-reset" }
+--  <li> packets        - The number of packets matched by the rule
+--  <li> bytes          - The number of total bytes matched by the rule
+-- </ul>
+-- Example:
+-- <pre>
+-- ip = luci.sys.iptparser.IptParser()
+-- result = ip.find( {
+--     target="REJECT",
+--     protocol="tcp",
+--     options={ "reject-with", "tcp-reset" }
+-- } )
+-- </pre>
+-- This will match all rules with target "-j REJECT",
+-- protocol "-p tcp" (or "-p all")
+-- and the option "--reject-with tcp-reset".
+function IptParser.find( self, args )
+
+       local args = args or { }
+       local rv   = { }
+
+       args.source      = args.source      and self:_parse_addr(args.source)
+       args.destination = args.destination and self:_parse_addr(args.destination)
+
+       for i, rule in ipairs(self._rules) do
+               local match = true
+
+               -- match table
+               if not ( not args.table or args.table:lower() == rule.table ) then
+                       match = false
+               end
+
+               -- match chain
+               if not ( match == true and (
+                       not args.chain or args.chain == rule.chain
+               ) ) then
+                       match = false
+               end
+
+               -- match target
+               if not ( match == true and (
+                       not args.target or args.target == rule.target
+               ) ) then
+                       match = false
+               end
+
+               -- match protocol
+               if not ( match == true and (
+                       not args.protocol or rule.protocol == "all" or
+                       args.protocol:lower() == rule.protocol
+               ) ) then
+                       match = false
+               end
+
+               -- match source
+               if not ( match == true and (
+                       not args.source or rule.source == self._nulladdr or
+                       self:_parse_addr(rule.source):contains(args.source)
+               ) ) then
+                       match = false
+               end
+
+               -- match destination
+               if not ( match == true and (
+                       not args.destination or rule.destination == self._nulladdr or
+                       self:_parse_addr(rule.destination):contains(args.destination)
+               ) ) then
+                       match = false
+               end
+
+               -- match input interface
+               if not ( match == true and (
+                       not args.inputif or rule.inputif == "*" or
+                       args.inputif == rule.inputif
+               ) ) then
+                       match = false
+               end
+
+               -- match output interface
+               if not ( match == true and (
+                       not args.outputif or rule.outputif == "*" or
+                       args.outputif == rule.outputif
+               ) ) then
+                       match = false
+               end
+
+               -- match flags (the "opt" column)
+               if not ( match == true and (
+                       not args.flags or rule.flags == args.flags
+               ) ) then
+                       match = false
+               end
+
+               -- match specific options
+               if not ( match == true and (
+                       not args.options or
+                       self:_match_options( rule.options, args.options )
+               ) ) then
+                       match = false
+               end
+
+               -- insert match
+               if match == true then
+                       rv[#rv+1] = rule
+               end
+       end
+
+       return rv
+end
+
+
+-- through external commands.
+function IptParser.resync( self )
+       self._rules = { }
+       self._chain = nil
+       self:_parse_rules()
+end
+
+
+function IptParser.tables( self )
+       return self._tables
+end
+
+
+function IptParser.chains( self, table )
+       local lookup = { }
+       local chains = { }
+       for _, r in ipairs(self:find({table=table})) do
+               if not lookup[r.chain] then
+                       lookup[r.chain]   = true
+                       chains[#chains+1] = r.chain
+               end
+       end
+       return chains
+end
+
+
+--                             and "rules". The "rules" field is a table of rule tables.
+function IptParser.chain( self, table, chain )
+       return self._chains[table:lower()] and self._chains[table:lower()][chain]
+end
+
+
+function IptParser.is_custom_target( self, target )
+       for _, r in ipairs(self._rules) do
+               if r.chain == target then
+                       return true
+               end
+       end
+       return false
+end
+
+
+-- [internal] Parse address according to family.
+function IptParser._parse_addr( self, addr )
+       if self._family == 4 then
+               return luci.ip.IPv4(addr)
+       else
+               return luci.ip.IPv6(addr)
+       end
+end
+
+-- [internal] Parse iptables output from all tables.
+function IptParser._parse_rules( self )
+
+       for i, tbl in ipairs(self._tables) do
+
+               self._chains[tbl] = { }
+
+               for i, rule in ipairs(luci.util.execl(self._command % tbl)) do
+
+                       if rule:find( "^Chain " ) == 1 then
+
+                               local crefs
+                               local cname, cpol, cpkt, cbytes = rule:match(
+                                       "^Chain ([^%s]*) %(policy (%w+) " ..
+                                       "(%d+) packets, (%d+) bytes%)"
+                               )
+
+                               if not cname then
+                                       cname, crefs = rule:match(
+                                               "^Chain ([^%s]*) %((%d+) references%)"
+                                       )
+                               end
+
+                               self._chain = cname
+                               self._chains[tbl][cname] = {
+                                       policy     = cpol,
+                                       packets    = tonumber(cpkt or 0),
+                                       bytes      = tonumber(cbytes or 0),
+                                       references = tonumber(crefs or 0),
+                                       rules      = { }
+                               }
+
+                       else
+                               if rule:find("%d") == 1 then
+
+                                       local rule_parts   = luci.util.split( rule, "%s+", nil, true )
+                                       local rule_details = { }
+
+                                       -- cope with rules that have no target assigned
+                                       if rule:match("^%d+%s+%d+%s+%d+%s%s") then
+                                               table.insert(rule_parts, 4, nil)
+                                       end
+
+                                       -- ip6tables opt column is usually zero-width
+                                       if self._family == 6 then
+                                               table.insert(rule_parts, 6, "--")
+                                       end
+
+                                       rule_details["table"]       = tbl
+                                       rule_details["chain"]       = self._chain
+                                       rule_details["index"]       = tonumber(rule_parts[1])
+                                       rule_details["packets"]     = tonumber(rule_parts[2])
+                                       rule_details["bytes"]       = tonumber(rule_parts[3])
+                                       rule_details["target"]      = rule_parts[4]
+                                       rule_details["protocol"]    = rule_parts[5]
+                                       rule_details["flags"]       = rule_parts[6]
+                                       rule_details["inputif"]     = rule_parts[7]
+                                       rule_details["outputif"]    = rule_parts[8]
+                                       rule_details["source"]      = rule_parts[9]
+                                       rule_details["destination"] = rule_parts[10]
+                                       rule_details["options"]     = { }
+
+                                       for i = 11, #rule_parts  do
+                                               if #rule_parts[i] > 0 then
+                                                       rule_details["options"][i-10] = rule_parts[i]
+                                               end
+                                       end
+
+                                       self._rules[#self._rules+1] = rule_details
+
+                                       self._chains[tbl][self._chain].rules[
+                                               #self._chains[tbl][self._chain].rules + 1
+                                       ] = rule_details
+                               end
+                       end
+               end
+       end
+
+       self._chain = nil
+end
+
+
+-- [internal] Return true if optlist1 contains all elements of optlist 2.
+--            Return false in all other cases.
+function IptParser._match_options( self, o1, o2 )
+
+       -- construct a hashtable of first options list to speed up lookups
+       local oh = { }
+       for i, opt in ipairs( o1 ) do oh[opt] = true end
+
+       -- iterate over second options list
+       -- each string in o2 must be also present in o1
+       -- if o2 contains a string which is not found in o1 then return false
+       for i, opt in ipairs( o2 ) do
+               if not oh[opt] then
+                       return false
+               end
+       end
+
+       return true
+end
diff --git a/libs/luci-lib-iptparser/sys/iptparser.luadoc b/libs/luci-lib-iptparser/sys/iptparser.luadoc
new file mode 100644 (file)
index 0000000..071e7d5
--- /dev/null
@@ -0,0 +1,69 @@
+---[[
+LuCI iptables parser and query library
+
+@cstyle        instance
+]]
+module "luci.sys.iptparser"
+
+---[[
+Create a new iptables parser object.
+
+@class function
+@name  IptParser
+@param family  Number specifying the address family. 4 for IPv4, 6 for IPv6
+@return        IptParser instance
+]]
+
+---[[
+Find all firewall rules that match the given criteria. Expects a table with
+
+search criteria as only argument. If args is nil or an empty table then all
+rules will be returned.
+]]
+
+---[[
+Rebuild the internal lookup table, for example when rules have changed
+
+through external commands.
+@class function
+@name IptParser.resync
+@return        nothing
+]]
+
+---[[
+Find the names of all tables.
+
+@class function
+@name IptParser.tables
+@return                Table of table names.
+]]
+
+---[[
+Find the names of all chains within the given table name.
+
+@class function
+@name IptParser.chains
+@param table   String containing the table name
+@return                Table of chain names in the order they occur.
+]]
+
+---[[
+Return the given firewall chain within the given table name.
+
+@class function
+@name IptParser.chain
+@param table   String containing the table name
+@param chain   String containing the chain name
+@return                Table containing the fields "policy", "packets", "bytes"
+--                             and "rules". The "rules" field is a table of rule tables.
+]]
+
+---[[
+Test whether the given target points to a custom chain.
+
+@class function
+@name IptParser.is_custom_target
+@param target  String containing the target action
+@return                        Boolean indicating whether target is a custom chain.
+]]
+
diff --git a/modules/luci-base/luasrc/sys/iptparser.lua b/modules/luci-base/luasrc/sys/iptparser.lua
deleted file mode 100644 (file)
index 7ff665e..0000000
+++ /dev/null
@@ -1,374 +0,0 @@
---[[
-
-Iptables parser and query library
-(c) 2008-2009 Jo-Philipp Wich <jow@openwrt.org>
-(c) 2008-2009 Steven Barth <steven@midlink.org>
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-        http://www.apache.org/licenses/LICENSE-2.0
-
-$Id$
-
-]]--
-
-local luci  = {}
-luci.util   = require "luci.util"
-luci.sys    = require "luci.sys"
-luci.ip     = require "luci.ip"
-
-local pcall = pcall
-local io = require "io"
-local tonumber, ipairs, table = tonumber, ipairs, table
-
-module("luci.sys.iptparser")
-
-IptParser = luci.util.class()
-
-function IptParser.__init__( self, family )
-       self._family = (tonumber(family) == 6) and 6 or 4
-       self._rules  = { }
-       self._chains = { }
-       self._tables = { }
-
-       local t = self._tables
-       local s = self:_supported_tables(self._family)
-
-       if s.filter then t[#t+1] = "filter" end
-       if s.nat    then t[#t+1] = "nat"    end
-       if s.mangle then t[#t+1] = "mangle" end
-       if s.raw    then t[#t+1] = "raw"    end
-
-       if self._family == 4 then
-               self._nulladdr = "0.0.0.0/0"
-               self._command  = "iptables -t %s --line-numbers -nxvL"
-       else
-               self._nulladdr = "::/0"
-               self._command  = "ip6tables -t %s --line-numbers -nxvL"
-       end
-
-       self:_parse_rules()
-end
-
-function IptParser._supported_tables( self, family )
-       local tables = { }
-       local ok, lines = pcall(io.lines,
-               (family == 6) and "/proc/net/ip6_tables_names"
-                              or "/proc/net/ip_tables_names")
-
-       if ok and lines then
-               local line
-               for line in lines do
-                       tables[line] = true
-               end
-       end
-
-       return tables
-end
-
--- search criteria as only argument. If args is nil or an empty table then all
--- rules will be returned.
---
--- The following keys in the args table are recognized:
--- <ul>
---  <li> table          - Match rules that are located within the given table
---  <li> chain          - Match rules that are located within the given chain
---  <li> target                 - Match rules with the given target
---  <li> protocol       - Match rules that match the given protocol, rules with
---                                             protocol "all" are always matched
---  <li> source                 - Match rules with the given source, rules with source
---                                             "0.0.0.0/0" (::/0) are always matched
---  <li> destination - Match rules with the given destination, rules with
---                                             destination "0.0.0.0/0" (::/0) are always matched
---  <li> inputif        - Match rules with the given input interface, rules
---                                             with input      interface "*" (=all) are always matched
---  <li> outputif       - Match rules with the given output interface, rules
---                                             with output     interface "*" (=all) are always matched
---  <li> flags          - Match rules that match the given flags, current
---                                             supported values are "-f" (--fragment)
---                                             and "!f" (! --fragment)
---  <li> options        - Match rules containing all given options
--- </ul>
--- The return value is a list of tables representing the matched rules.
--- Each rule table contains the following fields:
--- <ul>
---  <li> index          - The index number of the rule
---  <li> table          - The table where the rule is located, can be one
---                                             of "filter", "nat" or "mangle"
---  <li> chain          - The chain where the rule is located, e.g. "INPUT"
---                                             or "postrouting_wan"
---  <li> target                 - The rule target, e.g. "REJECT" or "DROP"
---  <li> protocol              The matching protocols, e.g. "all" or "tcp"
---  <li> flags          - Special rule options ("--", "-f" or "!f")
---  <li> inputif        - Input interface of the rule, e.g. "eth0.0"
---                                             or "*" for all interfaces
---  <li> outputif       - Output interface of the rule,e.g. "eth0.0"
---                                             or "*" for all interfaces
---  <li> source                 - The source ip range, e.g. "0.0.0.0/0" (::/0)
---  <li> destination - The destination ip range, e.g. "0.0.0.0/0" (::/0)
---  <li> options        - A list of specific options of the rule,
---                                             e.g. { "reject-with", "tcp-reset" }
---  <li> packets        - The number of packets matched by the rule
---  <li> bytes          - The number of total bytes matched by the rule
--- </ul>
--- Example:
--- <pre>
--- ip = luci.sys.iptparser.IptParser()
--- result = ip.find( {
---     target="REJECT",
---     protocol="tcp",
---     options={ "reject-with", "tcp-reset" }
--- } )
--- </pre>
--- This will match all rules with target "-j REJECT",
--- protocol "-p tcp" (or "-p all")
--- and the option "--reject-with tcp-reset".
-function IptParser.find( self, args )
-
-       local args = args or { }
-       local rv   = { }
-
-       args.source      = args.source      and self:_parse_addr(args.source)
-       args.destination = args.destination and self:_parse_addr(args.destination)
-
-       for i, rule in ipairs(self._rules) do
-               local match = true
-
-               -- match table
-               if not ( not args.table or args.table:lower() == rule.table ) then
-                       match = false
-               end
-
-               -- match chain
-               if not ( match == true and (
-                       not args.chain or args.chain == rule.chain
-               ) ) then
-                       match = false
-               end
-
-               -- match target
-               if not ( match == true and (
-                       not args.target or args.target == rule.target
-               ) ) then
-                       match = false
-               end
-
-               -- match protocol
-               if not ( match == true and (
-                       not args.protocol or rule.protocol == "all" or
-                       args.protocol:lower() == rule.protocol
-               ) ) then
-                       match = false
-               end
-
-               -- match source
-               if not ( match == true and (
-                       not args.source or rule.source == self._nulladdr or
-                       self:_parse_addr(rule.source):contains(args.source)
-               ) ) then
-                       match = false
-               end
-
-               -- match destination
-               if not ( match == true and (
-                       not args.destination or rule.destination == self._nulladdr or
-                       self:_parse_addr(rule.destination):contains(args.destination)
-               ) ) then
-                       match = false
-               end
-
-               -- match input interface
-               if not ( match == true and (
-                       not args.inputif or rule.inputif == "*" or
-                       args.inputif == rule.inputif
-               ) ) then
-                       match = false
-               end
-
-               -- match output interface
-               if not ( match == true and (
-                       not args.outputif or rule.outputif == "*" or
-                       args.outputif == rule.outputif
-               ) ) then
-                       match = false
-               end
-
-               -- match flags (the "opt" column)
-               if not ( match == true and (
-                       not args.flags or rule.flags == args.flags
-               ) ) then
-                       match = false
-               end
-
-               -- match specific options
-               if not ( match == true and (
-                       not args.options or
-                       self:_match_options( rule.options, args.options )
-               ) ) then
-                       match = false
-               end
-
-               -- insert match
-               if match == true then
-                       rv[#rv+1] = rule
-               end
-       end
-
-       return rv
-end
-
-
--- through external commands.
-function IptParser.resync( self )
-       self._rules = { }
-       self._chain = nil
-       self:_parse_rules()
-end
-
-
-function IptParser.tables( self )
-       return self._tables
-end
-
-
-function IptParser.chains( self, table )
-       local lookup = { }
-       local chains = { }
-       for _, r in ipairs(self:find({table=table})) do
-               if not lookup[r.chain] then
-                       lookup[r.chain]   = true
-                       chains[#chains+1] = r.chain
-               end
-       end
-       return chains
-end
-
-
---                             and "rules". The "rules" field is a table of rule tables.
-function IptParser.chain( self, table, chain )
-       return self._chains[table:lower()] and self._chains[table:lower()][chain]
-end
-
-
-function IptParser.is_custom_target( self, target )
-       for _, r in ipairs(self._rules) do
-               if r.chain == target then
-                       return true
-               end
-       end
-       return false
-end
-
-
--- [internal] Parse address according to family.
-function IptParser._parse_addr( self, addr )
-       if self._family == 4 then
-               return luci.ip.IPv4(addr)
-       else
-               return luci.ip.IPv6(addr)
-       end
-end
-
--- [internal] Parse iptables output from all tables.
-function IptParser._parse_rules( self )
-
-       for i, tbl in ipairs(self._tables) do
-
-               self._chains[tbl] = { }
-
-               for i, rule in ipairs(luci.util.execl(self._command % tbl)) do
-
-                       if rule:find( "^Chain " ) == 1 then
-
-                               local crefs
-                               local cname, cpol, cpkt, cbytes = rule:match(
-                                       "^Chain ([^%s]*) %(policy (%w+) " ..
-                                       "(%d+) packets, (%d+) bytes%)"
-                               )
-
-                               if not cname then
-                                       cname, crefs = rule:match(
-                                               "^Chain ([^%s]*) %((%d+) references%)"
-                                       )
-                               end
-
-                               self._chain = cname
-                               self._chains[tbl][cname] = {
-                                       policy     = cpol,
-                                       packets    = tonumber(cpkt or 0),
-                                       bytes      = tonumber(cbytes or 0),
-                                       references = tonumber(crefs or 0),
-                                       rules      = { }
-                               }
-
-                       else
-                               if rule:find("%d") == 1 then
-
-                                       local rule_parts   = luci.util.split( rule, "%s+", nil, true )
-                                       local rule_details = { }
-
-                                       -- cope with rules that have no target assigned
-                                       if rule:match("^%d+%s+%d+%s+%d+%s%s") then
-                                               table.insert(rule_parts, 4, nil)
-                                       end
-
-                                       -- ip6tables opt column is usually zero-width
-                                       if self._family == 6 then
-                                               table.insert(rule_parts, 6, "--")
-                                       end
-
-                                       rule_details["table"]       = tbl
-                                       rule_details["chain"]       = self._chain
-                                       rule_details["index"]       = tonumber(rule_parts[1])
-                                       rule_details["packets"]     = tonumber(rule_parts[2])
-                                       rule_details["bytes"]       = tonumber(rule_parts[3])
-                                       rule_details["target"]      = rule_parts[4]
-                                       rule_details["protocol"]    = rule_parts[5]
-                                       rule_details["flags"]       = rule_parts[6]
-                                       rule_details["inputif"]     = rule_parts[7]
-                                       rule_details["outputif"]    = rule_parts[8]
-                                       rule_details["source"]      = rule_parts[9]
-                                       rule_details["destination"] = rule_parts[10]
-                                       rule_details["options"]     = { }
-
-                                       for i = 11, #rule_parts  do
-                                               if #rule_parts[i] > 0 then
-                                                       rule_details["options"][i-10] = rule_parts[i]
-                                               end
-                                       end
-
-                                       self._rules[#self._rules+1] = rule_details
-
-                                       self._chains[tbl][self._chain].rules[
-                                               #self._chains[tbl][self._chain].rules + 1
-                                       ] = rule_details
-                               end
-                       end
-               end
-       end
-
-       self._chain = nil
-end
-
-
--- [internal] Return true if optlist1 contains all elements of optlist 2.
---            Return false in all other cases.
-function IptParser._match_options( self, o1, o2 )
-
-       -- construct a hashtable of first options list to speed up lookups
-       local oh = { }
-       for i, opt in ipairs( o1 ) do oh[opt] = true end
-
-       -- iterate over second options list
-       -- each string in o2 must be also present in o1
-       -- if o2 contains a string which is not found in o1 then return false
-       for i, opt in ipairs( o2 ) do
-               if not oh[opt] then
-                       return false
-               end
-       end
-
-       return true
-end
diff --git a/modules/luci-base/luasrc/sys/iptparser.luadoc b/modules/luci-base/luasrc/sys/iptparser.luadoc
deleted file mode 100644 (file)
index 071e7d5..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
----[[
-LuCI iptables parser and query library
-
-@cstyle        instance
-]]
-module "luci.sys.iptparser"
-
----[[
-Create a new iptables parser object.
-
-@class function
-@name  IptParser
-@param family  Number specifying the address family. 4 for IPv4, 6 for IPv6
-@return        IptParser instance
-]]
-
----[[
-Find all firewall rules that match the given criteria. Expects a table with
-
-search criteria as only argument. If args is nil or an empty table then all
-rules will be returned.
-]]
-
----[[
-Rebuild the internal lookup table, for example when rules have changed
-
-through external commands.
-@class function
-@name IptParser.resync
-@return        nothing
-]]
-
----[[
-Find the names of all tables.
-
-@class function
-@name IptParser.tables
-@return                Table of table names.
-]]
-
----[[
-Find the names of all chains within the given table name.
-
-@class function
-@name IptParser.chains
-@param table   String containing the table name
-@return                Table of chain names in the order they occur.
-]]
-
----[[
-Return the given firewall chain within the given table name.
-
-@class function
-@name IptParser.chain
-@param table   String containing the table name
-@param chain   String containing the chain name
-@return                Table containing the fields "policy", "packets", "bytes"
---                             and "rules". The "rules" field is a table of rule tables.
-]]
-
----[[
-Test whether the given target points to a custom chain.
-
-@class function
-@name IptParser.is_custom_target
-@param target  String containing the target action
-@return                        Boolean indicating whether target is a custom chain.
-]]
-
index 4f04cce5456622e6a075a16b91e3b3361fb82070..5b496d83f2375e42e5808f1b9d78a9b94dd1908d 100644 (file)
@@ -8,6 +8,7 @@ function index()
        entry({"admin", "status", "overview"}, template("admin_status/index"), _("Overview"), 1)
 
        entry({"admin", "status", "iptables"}, template("admin_status/iptables"), _("Firewall"), 2).leaf = true
+       entry({"admin", "status", "iptables_dump"}, call("dump_iptables")).leaf = true
        entry({"admin", "status", "iptables_action"}, post("action_iptables")).leaf = true
 
        entry({"admin", "status", "routes"}, template("admin_status/routes"), _("Routes"), 3)
@@ -44,6 +45,37 @@ function action_dmesg()
        luci.template.render("admin_status/dmesg", {dmesg=dmesg})
 end
 
+function dump_iptables(family, table)
+       local prefix = (family == "6") and "ip6" or "ip"
+       local ok, lines = pcall(io.lines, "/proc/net/%s_tables_names" % prefix)
+       if ok and lines then
+               local s
+               for s in lines do
+                       if s == table then
+                               local ipt = io.popen(
+                                       "/usr/sbin/%stables -t %s --line-numbers -nxvL"
+                                       %{ prefix, table })
+
+                               if ipt then
+                                       luci.http.prepare_content("text/plain")
+
+                                       while true do
+                                               s = ipt:read(1024)
+                                               if not s then break end
+                                               luci.http.write(s)
+                                       end
+
+                                       ipt:close()
+                                       return
+                               end
+                       end
+               end
+       end
+
+       luci.http.status(404, "No such table")
+       luci.http.prepare_content("text/plain")
+end
+
 function action_iptables()
        if luci.http.formvalue("zero") then
                if luci.http.formvalue("family") == "6" then
index 51e428e40e01a66402134c2bf0b60b3cab0e2467..50defac90eff7ed7afc8d6a670c91f9230140326 100644 (file)
@@ -1,16 +1,11 @@
 <%#
  Copyright 2008-2009 Steven Barth <steven@midlink.org>
- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org>
+ Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
  Licensed to the public under the Apache License 2.0.
 -%>
 
 <%-
-
-       require "luci.sys.iptparser"
-       local wba = require "luci.tools.webadmin"
        local fs = require "nixio.fs"
-       local io = require "io"
-
        local has_ip6tables = fs.access("/usr/sbin/ip6tables")
        local mode = 4
 
                mode = luci.dispatcher.context.requestpath
            mode = tonumber(mode[#mode] ~= "iptables" and mode[#mode]) or 4
        end
+-%>
 
-       local ipt = luci.sys.iptparser.IptParser(mode)
+<%+header%>
 
-       local rowcnt = 1
-       function rowstyle()
-               rowcnt = rowcnt + 1
-               return (rowcnt % 2) + 1
-       end
+<style type="text/css">
+       span.jump, .cbi-tooltip-container {
+               border-bottom: 1px dotted blue;
+               cursor: pointer;
+       }
 
-       function link_target(t,c)
-               if ipt:is_custom_target(c) then
-                       return '<a href="#rule_%s_%s">%s</a>' %{ t:lower(), c, c }
-               end
-               return c
-       end
+       ul {
+               list-style: none;
+       }
+
+       .references {
+               position: relative;
+       }
+
+       .references .cbi-tooltip {
+               left: 0 !important;
+               top: 1.5em !important;
+       }
+
+       h4 > span {
+               font-size: 90%;
+       }
+</style>
+
+<script type="text/javascript">//<![CDATA[
+       var table_names = [ 'Filter', 'NAT', 'Mangle', 'Raw' ];
+
+       function create_table_section(table)
+       {
+               var idiv = document.getElementById('iptables'),
+                   tdiv = idiv.querySelector('[data-table="%s"]'.format(table)),
+                   title = '<%:Table%>: %s'.format(table);
+
+               if (!tdiv) {
+                       tdiv = E('div', { 'data-table': table }, [
+                               E('h3', {}, title),
+                               E('div')
+                       ]);
+
+                       if (idiv.firstElementChild.nodeName.toLowerCase() === 'p')
+                               idiv.removeChild(idiv.firstElementChild);
+
+                       var added = false, thisIdx = table_names.indexOf(table);
+
+                       idiv.querySelectorAll('[data-table]').forEach(function(child) {
+                               var childIdx = table_names.indexOf(child.getAttribute('data-table'));
+
+                               if (added === false && childIdx > thisIdx) {
+                                       idiv.insertBefore(tdiv, child);
+                                       added = true;
+                               }
+                       });
+
+                       if (added === false)
+                               idiv.appendChild(tdiv);
+               }
+
+               return tdiv.lastElementChild;
+       }
+
+       function create_chain_section(table, chain, policy, packets, bytes, references)
+       {
+               var tdiv = create_table_section(table),
+                   cdiv = tdiv.querySelector('[data-chain="%s"]'.format(chain)),
+                   title;
+
+               if (policy)
+                       title = '<%:Chain%> <em>%s</em> <span>(<%:Policy%>: <em>%s</em>, %d <%:Packets%>, %.2mB <%:Traffic%>)</span>'.format(chain, policy, packets, bytes);
+               else
+                       title = '<%:Chain%> <em>%s</em> <span class="references">(%d <%:References%>)</span>'.format(chain, references);
+
+               if (!cdiv) {
+                       cdiv = E('div', { 'data-chain': chain }, [
+                               E('h4', { 'id': 'rule_%s_%s'.format(table.toLowerCase(), chain) }, title),
+                               E('div', { 'class': 'table' }, [
+                                       E('div', { 'class': 'tr table-titles' }, [
+                                               E('div', { 'class': 'th center' }, '<%:Pkts.%>'),
+                                               E('div', { 'class': 'th center' }, '<%:Traffic%>'),
+                                               E('div', { 'class': 'th' }, '<%:Target%>'),
+                                               E('div', { 'class': 'th' }, '<%:Prot.%>'),
+                                               E('div', { 'class': 'th' }, '<%:In%>'),
+                                               E('div', { 'class': 'th' }, '<%:Out%>'),
+                                               E('div', { 'class': 'th' }, '<%:Source%>'),
+                                               E('div', { 'class': 'th' }, '<%:Destination%>'),
+                                               E('div', { 'class': 'th' }, '<%:Options%>'),
+                                               E('div', { 'class': 'th' }, '<%:Comment%>')
+                                       ])
+                               ])
+                       ]);
+
+                       tdiv.appendChild(cdiv);
+               }
+               else {
+                       cdiv.firstElementChild.innerHTML = title;
+               }
+
+               return cdiv.lastElementChild;
+       }
+
+       function update_chain_section(chaintable, rows)
+       {
+               if (!chaintable)
+                       return;
+
+               cbi_update_table(chaintable, rows, '<%:No rules in this chain.%>');
 
-       function link_iface(i)
-               local net = wba.iface_get_network(i)
-               if net and i ~= "lo" then
-                       return '<a href="%s">%s</a>' %{
-                               url("admin/network/network", net), i
+               if (rows.length === 0 &&
+                   document.querySelector('form > [data-hide-empty="true"]'))
+                       chaintable.parentNode.style.display = 'none';
+               else
+                       chaintable.parentNode.style.display = '';
+
+               chaintable.parentNode.setAttribute('data-empty', rows.length === 0);
+       }
+
+       function hide_empty(btn)
+       {
+               var hide = (btn.getAttribute('data-hide-empty') === 'false');
+
+               btn.setAttribute('data-hide-empty', hide);
+               btn.value = hide ? '<%:Show empty chains%>' : '<%:Hide empty chains%>';
+               btn.blur();
+
+               document.querySelectorAll('[data-chain][data-empty="true"]')
+                       .forEach(function(chaintable) {
+                               chaintable.style.display = hide ? 'none' : '';
+                       });
+       }
+
+       function jump_target(ev)
+       {
+               var link = ev.target,
+                   table = findParent(link, '[data-table]').getAttribute('data-table'),
+                   chain = link.textContent,
+                   num = +link.getAttribute('data-num'),
+                   elem = document.getElementById('rule_%s_%s'.format(table.toLowerCase(), chain));
+
+               if (elem) {
+                       (document.documentElement || document.body.parentNode || document.body).scrollTop = elem.offsetTop - 40;
+                       elem.classList.remove('flash');
+                       void elem.offsetWidth;
+                       elem.classList.add('flash');
+
+                       if (num) {
+                               var rule = elem.nextElementSibling.childNodes[num];
+                               if (rule) {
+                                       rule.classList.remove('flash');
+                                       void rule.offsetWidth;
+                                       rule.classList.add('flash');
+                               }
                        }
+               }
+       }
 
-               end
-               return i
-       end
+       function parse_output(table, s)
+       {
+               var current_chain = null;
+               var current_rules = [];
+               var seen_chains = {};
+               var chain_refs = {};
+               var re = /([^\n]*)\n/g;
+               var m, m2;
 
-       local tables = { "Filter", "NAT", "Mangle", "Raw" }
-       if mode == 6 then
-               tables = { "Filter", "Mangle", "Raw" }
-               local ok, lines = pcall(io.lines, "/proc/net/ip6_tables_names")
-               if ok and lines then
-                       local line
-                       for line in lines do
-                               if line == "nat" then
-                                       tables = { "Filter", "NAT", "Mangle", "Raw" }
-                               end
-                       end
-               end
-       end
--%>
+               while ((m = re.exec(s)) != null) {
+                       if (m[1].match(/^Chain (.+) \(policy (\w+) (\d+) packets, (\d+) bytes\)$/)) {
+                               var chain = RegExp.$1,
+                                   policy = RegExp.$2,
+                                   packets = +RegExp.$3,
+                                   bytes = +RegExp.$4;
 
-<%+header%>
+                               update_chain_section(current_chain, current_rules);
 
-<style type="text/css">
-       span:target {
-               color: blue;
-               text-decoration: underline;
+                               seen_chains[chain] = true;
+                               current_chain = create_chain_section(table, chain, policy, packets, bytes);
+                               current_rules = [];
+                       }
+                       else if (m[1].match(/^Chain (.+) \((\d+) references\)$/)) {
+                               var chain = RegExp.$1,
+                                   references = +RegExp.$2;
+
+                               update_chain_section(current_chain, current_rules);
+
+                               seen_chains[chain] = true;
+                               current_chain = create_chain_section(table, chain, null, null, null, references);
+                               current_rules = [];
+                       }
+                       else if (m[1].match(/^num /)) {
+                               continue;
+                       }
+                       else if ((m2 = m[1].match(/^(\d+) +(\d+) +(\d+) +(.*?) +(\S+) +(\S*) +(\S+) +(\S+) +([a-f0-9:.]+\/\d+) +([a-f0-9:.]+\/\d+) +(.+)$/)) !== null) {
+                               var num = +m2[1],
+                                   pkts = +m2[2],
+                                   bytes = +m2[3],
+                                   target = m2[4],
+                                   proto = m2[5],
+                                   indev = m2[7],
+                                   outdev = m2[8],
+                                   srcnet = m2[9],
+                                   dstnet = m2[10],
+                                   options = m2[11] || '-',
+                                   comment = '-';
+
+                               options = options.trim().replace(/(?:^| )\/\* (.+) \*\//,
+                                       function(m1, m2) {
+                                               comment = m2.replace(/^!fw3(: |$)/, '').trim() || '-';
+                                               return '';
+                                       }) || '-';
+
+                               current_rules.push([
+                                       '%.2m'.format(pkts).nobr(),
+                                       '%.2mB'.format(bytes).nobr(),
+                                       target ? '<span class="target">%s</span>'.format(target) : '-',
+                                       proto,
+                                       (indev !== '*') ? '<span class="ifacebadge">%s</span>'.format(indev) : '*',
+                                       (outdev !== '*') ? '<span class="ifacebadge">%s</span>'.format(outdev) : '*',
+                                       srcnet,
+                                       dstnet,
+                                       options,
+                                       comment
+                               ]);
+
+                               if (target) {
+                                       chain_refs[target] = chain_refs[target] || [];
+                                       chain_refs[target].push([ current_chain, num ]);
+                               }
+                       }
+               }
+
+               update_chain_section(current_chain, current_rules);
+
+               document.querySelectorAll('[data-table="%s"] [data-chain]'.format(table))
+                       .forEach(function(cdiv) {
+                               if (!seen_chains[cdiv.getAttribute('data-chain')]) {
+                                       cdiv.parentNode.removeChild(cdiv);
+                                       return;
+                               }
+
+                               cdiv.querySelectorAll('.target').forEach(function(tspan) {
+                                       if (seen_chains[tspan.textContent]) {
+                                               tspan.classList.add('jump');
+                                               tspan.addEventListener('click', jump_target);
+                                       }
+                               });
+
+                               cdiv.querySelectorAll('.references').forEach(function(rspan) {
+                                       var refs = chain_refs[cdiv.getAttribute('data-chain')];
+                                       if (refs && refs.length) {
+                                               rspan.classList.add('cbi-tooltip-container');
+                                               rspan.appendChild(E('small', { 'class': 'cbi-tooltip ifacebadge', 'style': 'top:1em; left:auto' }, [ E('ul') ]));
+
+                                               refs.forEach(function(ref) {
+                                                       var chain = ref[0].parentNode.getAttribute('data-chain'),
+                                                           num = ref[1];
+
+                                                       rspan.lastElementChild.lastElementChild.appendChild(E('li', {}, [
+                                                               '<%:Chain%> ',
+                                                               E('span', {
+                                                                       'class': 'jump',
+                                                                       'data-num': num,
+                                                                       'onclick': 'jump_target(event)'
+                                                               }, chain),
+                                                               ', <%:Rule%> #%d'.format(num)
+                                                       ]));
+                                               });
+                                       }
+                               });
+                       });
        }
-</style>
+
+       table_names.forEach(function(table) {
+               XHR.poll(5, '<%=url("admin/status/iptables_dump", tostring(mode))%>/' + table.toLowerCase(), null,
+                       function (xhr) {
+                               parse_output(table, xhr.responseText);
+                       });
+       });
+//]]></script>
 
 <h2 name="content"><%:Firewall Status%></h2>
 
 </ul>
 <% end %>
 
-<div class="cbi-map" style="position: relative">
-
+<div style="position: relative">
        <form method="post" action="<%=url("admin/status/iptables_action")%>" style="position: absolute; right: 0">
                <input type="hidden" name="token" value="<%=token%>" />
                <input type="hidden" name="family" value="<%=mode%>" />
+               <input type="button" class="cbi-button" data-hide-empty="false" value="<%:Hide empty chains%>" onclick="hide_empty(this)" />
                <input type="submit" class="cbi-button" name="zero" value="<%:Reset Counters%>" />
                <input type="submit" class="cbi-button" name="restart" value="<%:Restart Firewall%>" />
        </form>
+</div>
 
-       <div class="cbi-section">
-
-               <% for _, tbl in ipairs(tables) do chaincnt = 0 %>
-                       <h3><%:Table%>: <%=tbl%></h3>
-
-                       <% for _, chain in ipairs(ipt:chains(tbl)) do
-                               rowcnt    = 0
-                               chaincnt  = chaincnt + 1
-                               chaininfo = ipt:chain(tbl, chain)
-                       %>
-                               <h4  id="rule_<%=tbl:lower()%>_<%=chain%>">
-                                       <%:Chain%> <em><%=chain%></em>
-                                       (<%- if chaininfo.policy then -%>
-                                               <%:Policy%>: <em><%=chaininfo.policy%></em>, <%:Packets%>: <%=chaininfo.packets%>, <%:Traffic%>: <%=wba.byte_format(chaininfo.bytes)-%>
-                                       <%- else -%>
-                                               <%:References%>: <%=chaininfo.references-%>
-                                       <%- end -%>)
-                               </h4>
-
-                               <div class="cbi-section-node">
-                                       <div class="table" style="font-size:90%">
-                                               <div class="tr table-titles cbi-rowstyle-<%=rowstyle()%>">
-                                                       <div class="th hide-xs"><%:Pkts.%></div>
-                                                       <div class="th nowrap"><%:Traffic%></div>
-                                                       <div class="th col-5"><%:Target%></div>
-                                                       <div class="th"><%:Prot.%></div>
-                                                       <div class="th"><%:In%></div>
-                                                       <div class="th"><%:Out%></div>
-                                                       <div class="th"><%:Source%></div>
-                                                       <div class="th"><%:Destination%></div>
-                                                       <div class="th col-9 hide-xs"><%:Options%></div>
-                                               </div>
-
-                                               <% for _, rule in ipairs(ipt:find({table=tbl, chain=chain})) do %>
-                                                       <div class="tr cbi-rowstyle-<%=rowstyle()%>">
-                                                               <div class="td"><%=rule.packets%></div>
-                                                               <div class="td nowrap"><%=wba.byte_format(rule.bytes)%></div>
-                                                               <div class="td col-5"><%=rule.target and link_target(tbl, rule.target) or "-"%></div>
-                                                               <div class="td"><%=rule.protocol%></div>
-                                                               <div class="td"><%=link_iface(rule.inputif)%></div>
-                                                               <div class="td"><%=link_iface(rule.outputif)%></div>
-                                                               <div class="td"><%=rule.source%></div>
-                                                               <div class="td"><%=rule.destination%></div>
-                                                               <div class="td col-9 hide-xs"><%=#rule.options > 0 and luci.util.pcdata(table.concat(rule.options, " ")) or "-"%></div>
-                                                       </div>
-                                               <% end %>
-
-                                               <% if rowcnt == 1 then %>
-                                                       <div class="tr cbi-rowstyle-<%=rowstyle()%>">
-                                                               <div class="td" colspan="9"><em><%:No rules in this chain%></em></div>
-                                                       </div>
-                                               <% end %>
-                                       </div>
-                               </div>
-                       <% end %>
-
-                       <% if chaincnt == 0 then %>
-                               <em><%:No chains in this table%></em>
-                       <% end %>
-
-                       <br /><br />
-               <% end %>
-       </div>
+<div id="iptables">
+       <p><em><%:Collecting data...%></em></p>
 </div>
 
 <%+footer%>