Nmap Development mailing list archives

parse_timespec function


From: David Fifield <david () bamsoftware com>
Date: Mon, 5 Apr 2010 14:02:18 -0600

On Fri, Apr 02, 2010 at 04:54:38PM -0700, Fyodor wrote:
On Fri, Apr 02, 2010 at 07:01:56PM -0400, Michael Pattrick wrote:

Other scripts take time arguments in seconds, not minutes. It's not the
best for this script but I'd like it if you make this script work that
way too. In the future we should have a standard function for parsing a
time specification like "60s" or "1m".

I have implemented it to stay consistent with the new argument name,
but I don't think it works well... No one would be running a fuzzer
for less then one minute.

Yeah, it will be better when we have a custom time parsing function
for NSE like David suggested.  We already have one for Nmap proper.
I've added it to docs/TODO.

But for now, I think standardizing on seconds like you've done makes
sense.  While it may be slightly annnoying to type in 1200 rather than
20 to run for 20 minutes, it beats having to look up the documentation
each time or to get it wrong.

Here's a proposed function to go in stdnse.

---
-- Parses a time duration specification, which is a number followed by a
-- unit, and returns a number of seconds. The unit is optional and
-- defaults to seconds. The possible units (case-insensitive) are
-- * <code>s</code>: seconds,
-- * <code>m</code>: minutes,
-- * <code>h</code>: hours.
-- In case of a parsing error, the function returns <code>nil</code>
-- followed by an error message.
--
-- @usage
-- parse_timespec("10") --> 10
-- parse_timespec("10s") --> 10
-- parse_timespec("10m") --> 600
-- parse_timespec("10h") --> 3600
-- parse_timespec("10z") --> nil, "Can't parse time specification \"10z\" (bad unit \"z\""
--
-- @param timespec A time specification string.
-- @return A number of seconds, or <code>nil</code> followed by an error
-- message.
function parse_timespec(timespec)
  local n, unit
  local multiplier

  n, unit = string.match(timespec, "^(%d+)(.*)$")
  if not n then
    return nil, string.format("Can't parse time specification \"%s\"", timespec)
  end
  n = tonumber(n)
  assert(n)

  unit = string.lower(unit)
  if unit == "" or unit == "s" then
    multiplier = 1
  elseif unit == "m" then
    multiplier = 60
  elseif unit == "h" then
    multiplier = 60 * 60
  else
    return nil, string.format("Can't parse time specification \"%s\" (bad unit \"%s\")", timespec, unit)
  end

  return n * multiplier
end

If this looks good, I'll commit it and change scripts to use it where
appropriate.

David Fifield
_______________________________________________
Sent through the nmap-dev mailing list
http://cgi.insecure.org/mailman/listinfo/nmap-dev
Archived at http://seclists.org/nmap-dev/


Current thread: