class Inspec::Resources::Http::Worker::Remote

Attributes

inspec[R]

Public Class Methods

new(inspec, http_method, url, opts) click to toggle source
# File lib/inspec/resources/http.rb, line 164
def initialize(inspec, http_method, url, opts)
  unless inspec.command("curl").exist?
    raise Inspec::Exceptions::ResourceSkipped,
          "curl is not available on the target machine"
  end

  @ran_curl = false
  @inspec = inspec
  super(http_method, url, opts)
end

Public Instance Methods

body() click to toggle source
# File lib/inspec/resources/http.rb, line 180
def body
  run_curl
  @body&.strip
end
response_headers() click to toggle source
# File lib/inspec/resources/http.rb, line 185
def response_headers
  run_curl
  @response_headers
end
status() click to toggle source
# File lib/inspec/resources/http.rb, line 175
def status
  run_curl
  @status
end

Private Instance Methods

curl_command() click to toggle source
# File lib/inspec/resources/http.rb, line 226
def curl_command # rubocop:disable Metrics/AbcSize
  cmd = ["curl -i"]

  # Use curl's --head option when the method requested is HEAD. Otherwise,
  # the user may experience a timeout when curl does not properly close
  # the connection after the response is received.
  if http_method.casecmp("HEAD") == 0
    cmd << "--head"
  else
    cmd << "-X #{http_method}"
  end

  cmd << "--connect-timeout #{open_timeout}"
  cmd << "--max-time #{open_timeout + read_timeout}"
  cmd << "--user \'#{username}:#{password}\'" unless username.nil? || password.nil?
  cmd << "--insecure" unless ssl_verify?
  cmd << "--data #{Shellwords.shellescape(request_body)}" unless request_body.nil?
  cmd << "--location" if max_redirects > 0
  cmd << "--max-redirs #{max_redirects}" if max_redirects > 0

  request_headers.each do |k, v|
    cmd << "-H '#{k}: #{v}'"
  end

  if params.nil?
    cmd << "'#{url}'"
  else
    cmd << "'#{url}?#{params.map { |e| e.join("=") }.join("&")}'"
  end

  cmd.join(" ")
end
run_curl() click to toggle source
# File lib/inspec/resources/http.rb, line 192
def run_curl
  return if @ran_curl

  cmd_result = inspec.command(curl_command)
  response = cmd_result.stdout
  @ran_curl = true
  return if response.nil? || cmd_result.exit_status != 0

  # strip any carriage returns to normalize output
  response.delete!("\r")

  # split the prelude (status line and headers) and the body
  prelude, remainder = response.split("\n\n", 2)
  loop do
    break unless remainder =~ %r{^HTTP/}

    prelude, remainder = remainder.split("\n\n", 2)
  end
  @body = remainder
  prelude = prelude.lines

  # grab the status off of the first line of the prelude
  status_line = prelude.shift
  @status = status_line.split(" ", 3)[1].to_i

  # parse the rest of the prelude which will be all the HTTP headers
  @response_headers = {}
  prelude.each do |line|
    line.strip!
    key, value = line.split(":", 2)
    @response_headers[key] = value.strip
  end
end