class Shodan::Clients::Base

Constants

BASE_URL
HOST

The path to the REST API endpoint.

Attributes

key[R]

Public Class Methods

new(key: ENV["SHODAN_API_KEY"]) click to toggle source
# File lib/shodan/clients/base.rb, line 16
def initialize(key: ENV["SHODAN_API_KEY"])
  @key = key
  warn 'No key has been found or provided!' unless key?
end

Public Instance Methods

key?() click to toggle source
# File lib/shodan/clients/base.rb, line 21
def key?
  !key.nil?
end

Private Instance Methods

_host() click to toggle source
# File lib/shodan/clients/base.rb, line 27
def _host
  self.class::HOST
end
base_url() click to toggle source
# File lib/shodan/clients/base.rb, line 31
def base_url
  self.class::BASE_URL
end
delete(path, **params) click to toggle source

Perform a direct DELETE HTTP request to the REST API.

# File lib/shodan/clients/base.rb, line 70
def delete(path, **params)
  params[:key] = key

  uri = URI("#{base_url}#{path}")
  uri.query = URI.encode_www_form(params)
  req = Net::HTTP::Delete.new(uri)
  request req
end
get(path, **params) click to toggle source

Perform a direct GET HTTP request to the REST API.

# File lib/shodan/clients/base.rb, line 50
def get(path, **params)
  params[:key] = key

  uri = URI("#{base_url}#{path}")
  uri.query = URI.encode_www_form(params)
  req = Net::HTTP::Get.new(uri)
  request req
end
https_options() click to toggle source
# File lib/shodan/clients/base.rb, line 79
def https_options
  if proxy = ENV["HTTPS_PROXY"] || ENV["https_proxy"]
    uri = URI(proxy)
    {
      proxy_address: uri.hostname,
      proxy_port: uri.port,
      proxy_from_env: false,
      use_ssl: true
    }
  else
    { use_ssl: true }
  end
end
post(path, **params) click to toggle source

Perform a direct POST HTTP request to the REST API.

# File lib/shodan/clients/base.rb, line 60
def post(path, **params)
  uri = URI("#{base_url}#{path}?key=#{key}")
  req = Net::HTTP::Post.new(uri)
  req.content_type = "application/json"
  req.body = params.to_json

  request req
end
request(req) click to toggle source
# File lib/shodan/clients/base.rb, line 35
def request(req)
  Net::HTTP.start(_host, 443, https_options) do |http|
    response = http.request(req)

    if response.code.to_i != 200
      json = JSON.parse(response.body)
      raise Error, json["error"] if json.key?("error")

      raise Error, response.body
    end
    JSON.parse response.body
  end
end
turn_into_facets(facets) click to toggle source
# File lib/shodan/clients/base.rb, line 101
def turn_into_facets(facets)
  {
    facets: facets.map { |k, v| "#{k}:#{v}" }.join(",")
  }
end
turn_into_query(params) click to toggle source
# File lib/shodan/clients/base.rb, line 93
def turn_into_query(params)
  query = params.dig(:query)
  options = params.reject { |k, _| k == :query }.map { |k, v| "#{k}:#{v}" }
  {
    query: [query, options].flatten.compact.join(" ")
  }
end