id = "TIME"

description = "Connects to the TIME service (RFC 868, not NTP) and on success prints the date and time."

author = "Dirk Loss <http://www.dirk-loss.de>"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"demo"}

require "shortport"
require "comm"
require "stdnse"

-- Seconds between Unix epoch (1970-01-01) and NTP epoch (1900-01-01)
EPOCH1900_DIFF = 2208988800

portrule = shortport.port_or_service(37, "time", "udp")

action = function(host, port)
    local status, result = comm.exchange(host, port, '\n',
                                        {bytes=4, proto="udp", timeout=1000})
    if status then
        local pos, seconds, len = bin.unpack('>I', result)
        return os.date("%c", seconds - EPOCH1900_DIFF)
    end
end
