Factor out the code that checks for an element in a table from shortport.lua to

eliminate some nested loops.
This commit is contained in:
david 2009-01-19 21:46:39 +00:00
parent 2e5795b109
commit 5a5df904f1

View file

@ -6,6 +6,20 @@
module(... or "shortport", package.seeall)
---
-- See if a table contains a value.
-- @param t A table repesenting a set.
-- @param value The value to check for.
-- @return True if <code>t</code> contains <code>value</code>, false otherwise.
local function includes(t, value)
for _, elem in ipairs(t) do
if elem == value then
return true
end
end
return false
end
--- Return a portrule that returns true when given an open port matching a
-- single port number or a list of port numbers.
-- @param port A single port number or a list of port numbers.
@ -32,17 +46,9 @@ portnumber = function(port, _proto, _state)
end
return function(host, port)
for _, state in pairs(state_table) do
if(port.protocol == proto and port.state == state) then
for _, _port in ipairs(port_table) do
if(port.number == _port) then
return true
end
end
end
end
return false
return includes(state_table, port.state)
and includes(port_table, port.number)
and port.protocol == proto
end
end
@ -79,17 +85,9 @@ service = function(service, _proto, _state)
end
return function(host, port)
for _, state in pairs(state_table) do
if(port.protocol == proto and port.state == state) then
for _, service in ipairs(service_table) do
if(port.service == service) then
return true
end
end
end
end
return false
return includes(state_table, port.state)
and includes(service_table, port.service)
and port.protocol == proto
end
end
@ -119,14 +117,8 @@ port_or_service = function(_port, _service, proto, _state)
end
return function(host, port)
for _, state in pairs(state_table) do
local port_checker = portnumber(_port, proto, state)
local service_checker = service(_service, proto, state)
if (port_checker(host, port) or service_checker(host, port)) then
return true
end
end
return false
local port_checker = portnumber(_port, proto, state_table)
local service_checker = service(_service, proto, state_table)
return port_checker(host, port) or service_checker(host, port)
end
end