Class: Hkp::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/hkp.rb

Constant Summary collapse

MAX_REDIRECTS =
3

Instance Method Summary collapse

Constructor Details

#initialize(server, ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER) ⇒ Client

Returns a new instance of Client.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/hkp.rb', line 17

def initialize(server, ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER)
  uri = URI server
  @host = uri.host
  @port = uri.port
  @use_ssl = false
  @ssl_verify_mode = ssl_verify_mode

  # set port and ssl flag according to URI scheme
  case uri.scheme.downcase
  when 'hkp'
    # use the HKP default port unless another port has been given
    @port ||= 11371
  when /\A(hkp|http)s\z/
    # hkps goes through 443 by default
    @port ||= 443
    @use_ssl = true
  end
  @port ||= 80
end

Instance Method Details

#get(path, redirect_depth = 0) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/hkp.rb', line 38

def get(path, redirect_depth = 0)
  Net::HTTP.start @host, @port, use_ssl: @use_ssl,
                                verify_mode: @ssl_verify_mode do |http|

    request = Net::HTTP::Get.new path
    response = http.request request

    case response.code.to_i
    when 200
      return response.body
    when 301, 302
      if redirect_depth >= MAX_REDIRECTS
        raise TooManyRedirects
      else
        location = URI.parse(response['location'])
        if location.host && (location.host != @host || location.port != @port)
          # Cross-host redirect - create new client for the target server
          redirect_client = Client.new(response['location'], ssl_verify_mode: @ssl_verify_mode)
          return redirect_client.get(location.request_uri, redirect_depth + 1)
        else
          # Same-host redirect (relative path or same host)
          redirect_path = location.respond_to?(:request_uri) ? location.request_uri : response['location']
          return get(redirect_path, redirect_depth + 1)
        end
      end
    else
      raise InvalidResponse, response.code
    end

  end
end