1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-31 03:49:01 +00:00

Some string optimizations in NSE

Changes fall into these categories:

1. Avoid pathological string building. Loops over x = x .. "foo" can
become very slow. Instead, use strbuf.lua, table.concat, or just one
continuous concatenation; a = x .. y .. z is one operation, better than
a = x .. y; a = a .. z

2. Use hex-escaped strings instead of string.char. I find this more
readable in many cases, and it avoids a table lookup and function call.

3. Don't duplicate code. A few libraries and scripts had re-implemented
stdnse.generate_random_string or openssl.rand_bytes.
This commit is contained in:
dmiller
2014-09-03 04:49:54 +00:00
parent 25725d369e
commit 40f36a4e3e
26 changed files with 202 additions and 243 deletions

View File

@@ -60,24 +60,25 @@ function name_encode(name, scope)
name = string.upper(name)
-- Do the L1 encoding
local L1_encoded = ""
local L1_encoded = {}
for i=1, #name, 1 do
local b = string.byte(name, i)
L1_encoded = L1_encoded .. string.char(bit.rshift(bit.band(b, 0xF0), 4) + 0x41)
L1_encoded = L1_encoded .. string.char(bit.rshift(bit.band(b, 0x0F), 0) + 0x41)
L1_encoded[i*2-1] = string.char(bit.rshift(bit.band(b, 0xF0), 4) + 0x41)
L1_encoded[i*2] = string.char(bit.rshift(bit.band(b, 0x0F), 0) + 0x41)
end
-- Do the L2 encoding
local L2_encoded = string.char(32) .. L1_encoded
local L2_encoded = { string.char(32), table.concat(L1_encoded) }
if scope ~= nil then
-- Split the scope at its periods
local piece
for piece in string.gmatch(scope, "[^.]+") do
L2_encoded = L2_encoded .. string.char(#piece) .. piece
L2_encoded[#L2_encoded+1] = string.char(#piece) .. piece
end
end
L2_encoded = table.concat(L2_encoded)
stdnse.debug3("=> '%s'", L2_encoded)
return L2_encoded
end