main
 1# frozen_string_literal: true
 2
 3module Net
 4  module Hippie
 5    # A connection to a specific host
 6    class Connection
 7      def initialize(scheme, host, port, options = {})
 8        http = Net::HTTP.new(host, port)
 9        http.read_timeout = options.fetch(:read_timeout, 10)
10        http.open_timeout = options.fetch(:open_timeout, 10)
11        http.use_ssl = scheme == 'https'
12        http.verify_mode = options.fetch(:verify_mode, Net::Hippie.verify_mode)
13        http.set_debug_output(options[:logger]) if options[:logger]
14        apply_client_tls_to(http, options)
15        @http = http
16      end
17
18      def run(request, &block)
19        if block_given?
20          @http.request(request, &block)
21        else
22          @http.request(request)
23        end
24      end
25
26      def build_url_for(path)
27        return path if path.start_with?('http')
28
29        "#{@http.use_ssl? ? 'https' : 'http'}://#{@http.address}#{path}"
30      end
31
32      private
33
34      def apply_client_tls_to(http, options)
35        return if options[:certificate].nil? || options[:key].nil?
36
37        http.cert = OpenSSL::X509::Certificate.new(options[:certificate])
38        http.key = private_key(options[:key], options[:passphrase])
39      end
40
41      def private_key(key, passphrase, type = OpenSSL::PKey::RSA)
42        passphrase ? type.new(key, passphrase) : type.new(key)
43      end
44    end
45  end
46end