class Inspec::Resources::UnixHostProvider

def initialize(inspec)

def initialize(inspec)
  super
  @has_nc = inspec.command("nc").exist?
  @has_ncat = inspec.command("ncat").exist?
  @has_net_redirections = inspec.command("strings `which bash` | grep -qE '/dev/(tcp|udp)/'").exit_status == 0
end

def missing_requirements(protocol)

def missing_requirements(protocol)
  missing = []
  if %w{tcp udp}.include?(protocol) && !@has_nc && !@has_ncat
    if @has_net_redirections
      missing << "#{timeout} (part of coreutils) or netcat must be installed" unless inspec.command(timeout).exist?
    else
      missing << "netcat must be installed"
    end
  end
  missing
end

def netcat_check_command(hostname, port, protocol)

def netcat_check_command(hostname, port, protocol)
  if @has_nc
    base_cmd = "nc"
  elsif @has_ncat
    base_cmd = "ncat"
  else
    return
  end
  if protocol == "udp"
    extra_flags = "-u"
  else
    extra_flags = ""
  end
  "echo | #{base_cmd} -v -w 1 #{extra_flags} #{hostname} #{port}"
end

def ping(hostname, port, protocol)

def ping(hostname, port, protocol)
  if %w{tcp udp}.include?(protocol)
    if @has_nc || @has_ncat
      resp = inspec.command(netcat_check_command(hostname, port, protocol))
    else
      resp = inspec.command("#{timeout} 1 bash -c \"< /dev/#{protocol}/#{hostname}/#{port}\"")
    end
  else
    # fall back to ping, but we can only test ICMP packages with ping
    resp = inspec.command("ping -w 1 -c 1 #{hostname}")
  end
  {
    success: resp.exit_status.to_i == 0,
    connection: resp.stderr,
    socket: resp.stdout,
  }
end

def resolve_with_dig(hostname)

def resolve_with_dig(hostname)
  addresses = []
  # look for IPv4 addresses
  cmd = inspec.command("dig +short A #{hostname}")
  cmd.stdout.lines.each do |line|
    matched = line.chomp.match(Resolv::IPv4::Regex)
    addresses << matched.to_s unless matched.nil?
  end
  # look for IPv6 addresses
  cmd = inspec.command("dig +short AAAA #{hostname}")
  cmd.stdout.lines.each do |line|
    matched = line.chomp.match(Resolv::IPv6::Regex)
    addresses << matched.to_s unless matched.nil?
  end
  addresses.empty? ? nil : addresses
end

def resolve_with_getent(hostname)

def resolve_with_getent(hostname)
  cmd = inspec.command("getent ahosts #{hostname}")
  return nil unless cmd.exit_status.to_i == 0
  # getent ahosts output is formatted like so:
  # $ getent ahosts www.google.com
  # 172.217.8.4     STREAM www.google.com
  # 172.217.8.4     DGRAM
  # 172.217.8.4     RAW
  # 2607:f8b0:4004:803::2004 STREAM
  # 2607:f8b0:4004:803::2004 DGRAM
  # 2607:f8b0:4004:803::2004 RAW
  addresses = []
  cmd.stdout.lines.each do |line|
    ip, = line.split(/\s+/, 2)
    next unless ip.match(Resolv::IPv4::Regex) || ip.match(Resolv::IPv6::Regex)
    addresses << ip unless addresses.include?(ip)
  end
  addresses
end

def timeout

def timeout
  "timeout"
end