local comm = require "comm"
local nmap = require "nmap"
local shortport = require "shortport"
local string = require "string"
local lpeg = require "lpeg"
local U = require "lpeg-utility"
local formulas = require "formulas"

description = [[
Detects the Skype version 2 service.
]]

---
-- @output
-- PORT   STATE SERVICE VERSION
-- 80/tcp open  skype2  Skype

author = "Brandon Enright"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"version"}


portrule = function(host, port)
  return (port.number == 80 or port.number == 443 or
    port.service == nil or port.service == "" or
    port.service == "unknown")
  and port.protocol == "tcp" and port.state == "open"
  and port.version.name_confidence < 10
  and not(shortport.port_is_excluded(port.number,port.protocol))
  and nmap.version_intensity() >= 7
end

-- Cache the returned pattern
local getquote = U.escaped_quote()

-- Substitution pattern to unescape a string
local unescape = lpeg.P {
  -- Substitute captures
  lpeg.Cs((lpeg.V "simple_char" + lpeg.V "unesc")^0),
  -- Escape char is '\'
  esc = lpeg.P "\\",
  -- Simple char is anything but escape char
  simple_char = lpeg.P(1) - lpeg.V "esc",
  -- If we hit an escape, process specials or hex code, otherwise remove the escape
  unesc = (lpeg.V "esc" * lpeg.Cs( lpeg.V "specials" + lpeg.V "code" + lpeg.P(1) ))/"%1",
  -- single-char escapes. These are the only ones service_scan uses
  specials = lpeg.S "trn0" / {t="\t", r="\r", n="\n", ["0"]="\0"},
  -- hex escape: convert to char
  code = (lpeg.P "x" * lpeg.C(lpeg.S "0123456789abcdefABCDEF"^-2))/function(c)
  return string.char(tonumber(c,16)) end,
}

-- Turn the service fingerprint reply to a probe into a binary blob
local function get_response (fp, probe)
  local i, e = string.find(fp, string.format("%s,%%d+,", probe))
  if i == nil then return nil end
  return unescape:match(getquote:match(fp, e+1))
end

action = function(host, port)
  local status, get_result, rand_result
  -- Did the service engine already do the hard work?
  if port.version and port.version.service_fp then
    -- Probes sent, replies received, but no match. Unwrap the fingerprint:
    local fp = string.gsub(port.version.service_fp, "\nSF:", "")
    get_result = get_response(fp, "GetRequest")
    for _, p in ipairs({"HTTPOptions", "RTSPRequest", "SSLSessionReq"}) do
      rand_result = get_response(fp, p)
      if rand_result then break end
    end
  end
  if not get_result then
    status, get_result = comm.exchange(host, port,
      "GET / HTTP/1.0\r\n\r\n", {bytes=26, proto=port.protocol})
    if (not status) then
      return
    end
  end
  if (get_result ~= "HTTP/1.0 404 Not Found\r\n\r\n") then
    return
  end
  -- So far so good, now see if we get random data for another request
  if not rand_result then
    status, rand_result = comm.exchange(host, port,
      "random data\r\n\r\n", {bytes=15, proto=port.protocol})
    if (not status) then
      return
    end
  end
  if formulas.looksRandom(rand_result) then
    -- Detected
    port.version.name = "skype2"
    port.version.product = "Skype"
    nmap.set_port_version(host, port)
    return
  end
  return
end
