From 8875b3cd18772d8e97cc797d09b5faab14f25a4a Mon Sep 17 00:00:00 2001 From: Nodir Temirkhodjaev Date: Mon, 19 Jan 2015 17:24:15 +0500 Subject: [PATCH] Add IPv4 address ranges parsing. --- bin/lua/wipf/util/fs.lua | 2 +- bin/lua/wipf/util/ip.lua | 57 +++++++++++++++++++++++++++++++++++++--- test/wipf_test.lua | 9 +++++-- 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/bin/lua/wipf/util/fs.lua b/bin/lua/wipf/util/fs.lua index 35f06802..7fa9dd2d 100644 --- a/bin/lua/wipf/util/fs.lua +++ b/bin/lua/wipf/util/fs.lua @@ -59,7 +59,7 @@ end -- Convert Win32 path to Native path local function path_to_dospath(path) - local drive, sub_path = string.match(path, [[(%w:)(\.+)]]) + local drive, sub_path = string.match(path, [[(%a:)(\.+)]]) if not drive then return path end diff --git a/bin/lua/wipf/util/ip.lua b/bin/lua/wipf/util/ip.lua index 3835e663..c4227e4d 100644 --- a/bin/lua/wipf/util/ip.lua +++ b/bin/lua/wipf/util/ip.lua @@ -1,14 +1,65 @@ -- WIPF IP Utilities +local bit = require"bit" + local sys = require"sys" local sock = require"sys.sock" -- Convert IPv4 ranges in text to 'from_ip4' & 'to_ip4' arrays with numbers -local function ip4range_to_numbers(text) - local from, to = {}, {} +local ip4range_to_numbers +do + local function parse_address_mask(line) + local from, sep, mask = string.match(line, "([%d%.]+)%s*(%S)%s*(%S+)") - return from, to + local from_ip = sock.inet_pton(from, true) + if not from_ip then + return + end + + local to_ip + if sep == '-' then -- e.g. "127.0.0.0-127.255.255.255" + to_ip = sock.inet_pton(mask, true) + if not to_ip then + return + end + elseif sep == '/' then -- e.g. "127.0.0.0/24" + local nbits = tonumber(mask) + if nbits > 32 then + return + elseif nbits == 32 then + to_ip = 0xFFFFFFFF + else + to_ip = bit.bor(from_ip, bit.lshift(1, nbits) - 1) + end + end + + return from_ip, to_ip + end + + ip4range_to_numbers = function (text) + local iprange_from, iprange_to = {}, {} + local index = 0 + + for line in string.gmatch(text, "%s*(%S+)%s*\n?") do + local from, to + + if line == "*" then + from, to = 0, 0xFFFFFFFF + else + from, to = parse_address_mask(line) + end + + if from then + index = index + 1 + iprange_from[index], iprange_to[index] = from, to + end + end + + iprange_from.n, iprange_to.n = index, index + + return iprange_from, iprange_to + end end diff --git a/test/wipf_test.lua b/test/wipf_test.lua index 445f4fcd..bd937657 100644 --- a/test/wipf_test.lua +++ b/test/wipf_test.lua @@ -61,8 +61,13 @@ do D:\Utils\Dev\Git\* ]] - local iprange_from, iprange_to = wipf_ip.ip4range_to_numbers(ip_include) - print(#iprange_from, #iprange_to) + local iprange_from_inc, iprange_to_inc = + wipf_ip.ip4range_to_numbers(ip_include) + assert(iprange_from_inc.n == iprange_to_inc.n) + + local iprange_from_exc, iprange_to_exc = + wipf_ip.ip4range_to_numbers(ip_exclude) + assert(iprange_from_exc.n == iprange_to_exc.n) print("OK") end