lib/async/http/url_endpoint.rb



# Copyright, 2018, by Samuel G. D. Williams. <http://www.codeotaku.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

require 'async/io/host_endpoint'
require 'async/io/ssl_endpoint'
require 'async/io/ssl_socket'

require_relative 'protocol/http1'
require_relative 'protocol/https'

module Async
	module HTTP
		class URLEndpoint < Async::IO::Endpoint
			def self.parse(string, **options)
				url = URI.parse(string).normalize
				
				self.new(url, **options)
			end
			
			def initialize(url, endpoint = nil, **options)
				super(**options)
				
				raise ArgumentError.new("URL must be absolute (include scheme, host): #{url}") unless url.absolute?
				
				@url = url
				@endpoint = endpoint
			end
			
			def to_url
				url = @url.dup
				
				unless default_port?
					url.port = self.port
				end
				
				return url
			end
			
			def to_s
				"\#<#{self.class} #{self.to_url}>"
			end
			
			def inspect
				"\#<#{self.class} #{self.to_url} #{@options.inspect}>"
			end
			
			attr :url
			attr :options
			
			def address
				endpoint.address
			end
			
			def secure?
				['https', 'wss'].include?(@url.scheme)
			end
			
			def protocol
				if secure?
					Protocol::HTTPS
				else
					Protocol::HTTP1
				end
			end
			
			def default_port
				secure? ? 443 : 80
			end
			
			def default_port?
				port == default_port
			end
			
			def port
				@options[:port] || @url.port || default_port
			end
			
			def hostname
				@options[:hostname] || @url.hostname
			end
			
			def scheme
				@options[:scheme] || @url.scheme
			end
			
			def authority
				if default_port?
					hostname
				else
					"#{hostname}:#{port}"
				end
			end
			
			def path
				@url.request_uri
			end
			
			DEFAULT_ALPN_PROTOCOLS = ['h2', 'http/1.1'].freeze
			
			def alpn_protocols
				@options[:alpn_protocols] || DEFAULT_ALPN_PROTOCOLS
			end
			
			LOCALHOST = 'localhost'.freeze
			
			# We don't try to validate peer certificates when talking to localhost because they would always be self-signed.
			def ssl_verify_mode
				case self.hostname
				when LOCALHOST
					OpenSSL::SSL::VERIFY_NONE
				else
					OpenSSL::SSL::VERIFY_PEER
				end
			end
			
			def ssl_context
				@options[:ssl_context] || ::OpenSSL::SSL::SSLContext.new.tap do |context|
					if alpn_protocols = self.alpn_protocols
						context.alpn_protocols = alpn_protocols
					end
					
					context.set_params(
						verify_mode: self.ssl_verify_mode
					)
				end
			end
			
			def tcp_options
				{
					reuse_port: self.reuse_port,
					timeout: self.timeout,
				}
			end
			
			def build_endpoint(endpoint = nil)
				endpoint ||= Async::IO::Endpoint.tcp(hostname, port, tcp_options)
				
				if secure?
					# Wrap it in SSL:
					return Async::IO::SSLEndpoint.new(endpoint,
						ssl_context: self.ssl_context,
						hostname: self.hostname,
						timeout: self.timeout,
					)
				end
				
				return endpoint
			end
			
			def endpoint
				@endpoint ||= build_endpoint
			end
			
			def bind(*args, &block)
				endpoint.bind(*args, &block)
			end
			
			def connect(*args, &block)
				endpoint.connect(*args, &block)
			end
			
			def each
				return to_enum unless block_given?
				
				self.endpoint.each do |endpoint|
					yield self.class.new(@url, endpoint, @options)
				end
			end
			
			def key
				[@url.scheme, @url.userinfo, @url.host, @url.port, @options]
			end
			
			def eql? other
				self.key.eql? other.key
			end
			
			def hash
				self.key.hash
			end
		end
	end
end