Skip to content

Add the option to preload stdnse.make_buffer with data#3253

Closed
nnposter wants to merge 1 commit intonmap:masterfrom
nnposter:stdnse-makebuffer
Closed

Add the option to preload stdnse.make_buffer with data#3253
nnposter wants to merge 1 commit intonmap:masterfrom
nnposter:stdnse-makebuffer

Conversation

@nnposter
Copy link

Function stdnse.make_buffer provides a very convenient method for reading from a socket in predictable chunks separated by a given pattern, such as one line at a time. This works well when the socket is connected with <socket>:connect but the benefit tends to get substantially reduced when some of the data is incidentally already received from the socket before stdnse.make_buffer has a chance to be called. One such example is when a socket is connected with comm.tryssl, which returns not just the connected socket but also data read by initial <socket>:receive. A user is then left with extracting the chunks from this initial data and gluing them together with subsequent reads from the buffer created with stdnse.make_buffer. The code would generally look something like this:

local socket, data = comm.tryssl(...)
local sep = "\r?\n"
local pos = 1
while pos <= #data do
  local p, q = data:find(sep, pos)
  if not p then break end
  process_line(data:sub(pos, p - 1))
  pos = q + 1
end
local buf = stdnse.make_buffer(socket, sep)
while true do
  local line = buf()
  if not line then break end
  if data then
    line = data:sub(pos) .. line
    data = nil
  end
  process_line(line)
end

This patch is implementing a third parameter for stdnse.make_buffer, allowing this initial, incidentally read data to be returned to the buffer and making it available for subsequent reads. The code then gets substantially simpler:

local socket, data = comm.tryssl(...)
local buf = stdnse.make_buffer(socket, "\r?\n", data)
while true do
  local line = buf()
  if not line then break end
  process_line(line)
end

This PR will be merged in after February 1 unless concerns are raised.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant