require("ipOps")

id = "Autonomous Numbers"
description = "Queries ASN's Countries codes, and BGP prefixes."
author = "Michael Pattrick <mpattrick@rhinovirus.org>, mostly stolen from ripeQuery.nse"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"

categories = {"discovery"}

hostrule = function(host, port)
        return not ipOps.isPrivate(host.ip)
end

action = function(host, port)
        local socket = nmap.new_socket()
        local status, line
        local result = ""
	local results = {}
        socket:connect("whois.cymru.com", 43)

        socket:send(" -v " .. host.ip .. "\n")

        while true do
                local status, lines = socket:receive_lines(1)

                if not status then
                        break
                else
                        result = result .. lines
                end
        end
        socket:close()

	for line in result:gmatch("[^\r\n]+") do 
		local fields={}
		fields={line:match( ("([^|]*)|"):rep(6) )}
		---a hackish trick to only get the last line
		results=fields
	end

        if (result == nil) then
                return
        end

---data example
---AS      | IP               | BGP Prefix          | CC | Registry | Allocated  | AS Name
---####    | 0.0.0.0          | 0.0.0.0/0           | NN | arin     | 1999-05-03 | Company

        return "BGP Prefix: " .. results[3]:gsub("^%s*(.-)%s*$", "%1") .. " AS number: " .. results[1]:gsub("^%s*(.-)%s*$", "%1") .. " Country Code: " .. results[4]:gsub("^%s*(.-)%s*$", "%1")
end

